从ios12.2(具体版本可能有些许出入)开始,ios限制http地址的陀螺仪事件,必须https才能够,咱们的站点必须是https才能正常生效,因而乎一大堆程序员吭哧吭哧的填好了坑。ios
固然虽然咱们天天如履薄冰,战战兢兢,并不能改变线上某功能忽然bug的现象。程序员
因而乎忽然有一天用户反馈,iphone xr的微信做品摇一摇不生效,在确认https无误后,便开始痛苦的联机调试,发现监听事件devicemotion未生效,从而查阅资料显示最新版系统陀螺仪功能增长了限制,必须用户手动受权才能正常,拉起受权的事件为微信
DeviceMotionEvent.requestPermission() .then( response => { if ( response == "granted" ) { // 赞成 } else { // 拒绝 } }).catch(() => { // 通常为非用户主动受权 })
这里有几点须要注意:app
所以根据上述状况,咱们的流程图大概以下:iphone
function iosCheck() { return new Promise((resolve, reject) => { if (typeof( DeviceMotionEvent ) !== "undefined" && typeof( DeviceMotionEvent.requestPermission ) === "function") { getPermission().then(() => { resolve(); }).catch((e) => { // 用户拒绝 if (e.type === 1) { // 用户上次状态为拒绝,提示弹窗 } else if (e.type === 2) { // 用户首次进入,获取权限失败,需手动开启,弹窗引导 // bind event $(modal).on('touchstart', () => { getPermission().then(() => { resolve(); }).catch(() => { // 用户拒绝受权,提示 }); }) } }); } else { resolve(); } }) } function getPermission() { return new Promise((resolve, reject) => { DeviceMotionEvent.requestPermission() .then( response => { if ( response == "granted" ) { resolve(); } else { reject({type: 1}); } }).catch(() => { reject({type: 2}); }) }) } iosCheck().then(() => { window.addEventListener('devicemotion', deviceMotionHandler, false); })
固然若是更谨慎一些的话,咱们能够在iosCheck方法中增长当前版本的限制。spa