archana parmar
archana parmar

Reputation: 11

Unable to check DeviceMotionEvent permission state

Is it possible to check if DeviceMotionEvent permission has already been granted or not? And how we can change the request alert text from "localhost would like to access motion and orientation" to "App name would like to access motion and orientation"?

public requestDeviceMotion() {
    if typeof (DeviceMotionEvent as any).requestPermission === 'function') {
      (DeviceMotionEvent as any).requestPermission()
        .then(permissionState => {
          if (permissionState === 'granted') {
            window.addEventListener('devicemotion', () => { });
          }
        })
        .catch(console.error);
    } else {
      // handle regular non iOS 13+ devices
      console.log("not iOS");
    }
 }

Upvotes: 0

Views: 487

Answers (1)

user796446
user796446

Reputation:

Could you clarify what is meant by "Is it possible to check"?

You code is valid for such a purposes. i.e. If permission state is not granted.

Note that your else block won't be triggered by "regular non iOS13+ devices" if they also have DeviceMotionEvent. For this you should use Platform.is like so:

public requestDeviceMotion() {
   if (typeof DeviceMotionEvent.requestPermission === 'function') {
     DeviceMotionEvent.requestPermission().then(permissionStatus => {
       if (permissionState === 'granted') {
        // window.addEventListener('devicemotion', () => { });
        // I commented this out because you should not do this.
        // This will cause a memory leak. You should make the listener
        // a function which can then be removed in destroy lifecycle event
        // but that is outside the scope of your question
       }
     }

   } else if (!this.platform.is('ios')) {
     console.log('not ios');
   }

}

As for customizing the message, as far as I know, this is only an option for iOS.

Add the following to your config.xml at the base of your Ionic project folder. NOTE: You will probably only need to add the actual config-file entry but complete object is shown for clarity

<platform name="ios">
   <config-file parent="NSMotionUsageDescription" target="*-Info.plist">
     <string>This is your new message</string>
   </config-file>
</platform>

Upvotes: 0

Related Questions