隨着ios的系統升級,安全協議越來越嚴格,例如ios系統手機的運動和方向感控被限制了,必須得用戶手動授權方可進行,前端爲了要實現搖一搖功能,必須要具備以下思路。
1、必須是https協議,即打開h5頁面的鏈接開頭必須是https://…
2、搖一搖功能開啓必須經過用戶授權,必須用戶手動點擊確定。
JS相關設置代碼:
var SHAKE_THRESHOLD = 1000;
var last_update = 0;
var x = y = z = last_x = last_y = last_z = 0;
function shakeInit() {
if (window.DeviceMotionEvent) {
window.addEventListener('devicemotion', deviceMotionHandler, false);
} else {
alert('not support mobile event');
}
}
function deviceMotionHandler(eventData) {
var acceleration = eventData.accelerationIncludingGravity;//eventData.acceleration;
var curTime = new Date().getTime();
if ((curTime - last_update) > 100) {
var diffTime = curTime - last_update;
last_update = curTime;
x = acceleration.x;
y = acceleration.y;
z = acceleration.z;
var speed = Math.abs(x + y + z - last_x - last_y - last_z) / diffTime * 10000;
if (speed > SHAKE_THRESHOLD) {
alert('搖手機了');
}
}
last_x = x;
last_y = y;
last_z = z;
}
shakeInit();
// 安卓手機均可正常實現搖一搖,以下代碼針對ios手機做授權處理
function iosGrantedTips(){
var ua = navigator.userAgent.toLowerCase(); //判斷移動端設備,區分android,iphone,ipad和其它
if(ua.indexOf("like mac os x") > 0){ //判斷蘋果設備
// 正則判斷手機系統版本
var reg = /os [\d._]*/gi ;
var verinfo = ua.match(reg) ;
var version = (verinfo+"").replace(/[^0-9|_.]/ig,"").replace(/_/ig,".");
var arr=version.split(".");
console.log(arr[0]+"."+arr[1]+"."+arr[2]) //獲取手機系統版本
if (arr[0]>12&&arr[1]>2) { //對13.3以後的版本處理,包括13.3
DeviceMotionEvent.requestPermission().then(permissionState => {
if (permissionState === 'granted') { //已授權
shakeInit() //搖一搖
} else if(permissionState === 'denied'){// 打開的鏈接不是https開頭
alert("當前IOS系統拒絕訪問動作與方向。請退出微信,重新進入活動頁面獲取權限。")
}
}).catch((err)=>{
alert("用戶未允許權限")
//======這裏可以防止重複授權,需要改動,因爲獲取權限需要點擊事件才能觸發,所以這裏可以改成某個提示框===//
console.log("由於IOS系統需要手動獲取訪問動作與方向的權限,爲了保證搖一搖正常運行,請在訪問提示中點擊允許!")
ios13granted();
});
}else{ //13.3以前的版本
alert("蘋果系統13.3以前的版本")
}
}
}
function ios13granted() {
if (typeof DeviceMotionEvent.requestPermission === 'function') {
DeviceMotionEvent.requestPermission().then(permissionState => {
if (permissionState === 'granted') {
shakeInit() //搖一搖
} else if(permissionState === 'denied'){// 打開的鏈接不是https開頭
alert("當前IOS系統拒絕訪問動作與方向。請退出微信,重新進入活動頁面獲取權限。")
}
}).catch((error) => {
alert("請求設備方向或動作訪問需要用戶手勢來提示")
})
} else {
// 處理常規的非iOS 13+設備
alert("處理常規的非iOS 13+設備")
}
}
iosGrantedTips();