本地生成個(gè)motion.js文件
function requestSensorPermission() {
if (typeof(DeviceMotionEvent) !== 'undefined' && typeof(DeviceMotionEvent.requestPermission) === 'function') {
DeviceMotionEvent.requestPermission().then(response => {
if (response == 'granted') {
window.addEventListener('devicemotion', (e) => { })
}
}).catch(console.error)
}
};
使用WKUserScript方式植入js代碼, webview需要實(shí)現(xiàn)WKUIDelegate的彈窗代理方法
WKWebViewConfiguration* config = [[WKWebViewConfiguration alloc] init];
config.userContentController = [[WKUserContentController alloc] init];
NSError *error = nil;
NSString *js = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"motion" ofType:@"js"] encoding:NSUTF8StringEncoding error:&error];
WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
[config.userContentController addUserScript:script];
_webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, -KNavHeight, SCREEN_WIDTH, SCREEN_HEIGHT + KNavHeight - kTabbarHeight) configuration:config];
_webView.navigationDelegate = self;
_webView.UIDelegate = self;
在WKWebview加載完成后執(zhí)行調(diào)用植入的js方法
[self.webView evaluateJavaScript:@"requestSensorPermission()" completionHandler:^(id _Nullable respone, NSError * _Nullable error) {
}];
執(zhí)行后會彈出權(quán)限對話框
//接收到警告面板
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
completionHandler();
}
點(diǎn)擊允許, 完事了!!!