【问题标题】:Unable to check DeviceMotionEvent permission state无法检查 DeviceMotionEvent 权限状态
【发布时间】:2021-10-19 06:27:00
【问题描述】:

是否可以检查是否已授予 DeviceMotionEvent 权限?以及我们如何将请求警报文本从“localhost想要访问运动和方向”更改为“应用名称想要访问运动和方向”?

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");
    }
 }

【问题讨论】:

    标签: ionic-framework ios13 devicemotion


    【解决方案1】:

    您能否阐明“是否可以检查”的含义?

    您的代码可用于此类用途。即如果未授予权限状态。

    请注意,如果“常规非 iOS13+ 设备”也有 DeviceMotionEvent,则不会触发您的 else 块。为此,您应该像这样使用 Platform.is:

    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');
       }
    
    }
    
    

    至于自定义消息,据我所知,这只是iOS的一个选项。

    将以下内容添加到 Ionic 项目文件夹底部的 config.xml 中。注意:您可能只需要添加实际的配置文件条目,但为了清楚起见会显示完整的对象

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

    【讨论】:

    • 感谢您的回答,我想在请求权限之前添加一个复选标记,例如之前是否已授予或拒绝权限,则无需再次请求
    • “requestPermission”这个名字有点用词不当。它是开源的,因此您可以通过 IDE ALT-CLICK 进入代码。 “requestPermission”检查是否设置了权限并返回状态。只有没有设置它才会激活本机请求机制。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-07
    • 2012-05-10
    • 2017-03-18
    • 2020-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多