兼容iOS13+和微信7.0.12+的摇一摇(devicemotion)

查了无数帖子,终于解决了iOS13+系统上Safari里的陀螺仪数据无法读取这个问题;
为了实现摇一摇,要读取陀螺仪数据,计算后进行相应操作,但iOS13,准确的说是beta2之后新增了一个权限,必须申请后才可以读取陀螺仪数据。
所以现在的前提是两个:必须是https,必须先获得权限;

https这个就不说了;
获取权限的代码如下:

function permission () {
    if ( typeof( DeviceMotionEvent ) !== "undefined" && typeof( DeviceMotionEvent.requestPermission ) === "function" ) {
        DeviceMotionEvent.requestPermission()
            .then( response => {
                console.log(response);
                if ( response == "granted" ) {
                    window.addEventListener( "devicemotion", (e) => {
                    	console.log(e.acceleration);
                        //do sth.(同样可以在这里进行摇一摇判断,相当于如果是iOS13+,则执行这里)
                        //进入摇一摇判断
			             var acc = e.acceleration;
			             x = acc.x;
			             y = acc.y;
			             if (Math.abs(x - lastX) > speed || Math.abs(y - lastY) > speed) {
			                 //触发摇一摇
			                 //do sth.
			             }
			             lastX = x;
			             lastY = y;
			                    })
			                }
			            })
            .catch( console.error )
    } else {
        alert( "DeviceMotionEvent is not defined" );
    }
}

你需要做的就是,先判断设备是否是ios13+,然后对应申请权限或直接执行代码;

var speed = 15;//5~25,数字越大灵敏度越低
var x = y = z = lastX = lastY = lastZ = 0;
if (window.DeviceOrientationEvent) {
     if (navigator.userAgent.indexOf('MicroMessenger/7.0.12') > -1 && navigator.userAgent.indexOf('iPhone OS 13') > -1) permission();
     else {
         console.log('普通ios或安卓');
         window.addEventListener( "devicemotion", (e) => {
         	 //进入摇一摇判断
             var acc = e.acceleration;
             x = acc.x;
             y = acc.y;
             if (Math.abs(x - lastX) > speed || Math.abs(y - lastY) > speed) {
                 //触发摇一摇
                 //do sth.
             }
             lastX = x;
             lastY = y;
         })
     }
 } else {
     console.log('不支持陀螺仪');
 }

终于是解决了!

你可能感兴趣的:(兼容iOS13+和微信7.0.12+的摇一摇(devicemotion))