iOS13下WKWebview申请陀螺仪权限
2020-07-16 本文已影响0人
辉过来辉过去
本地生成个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需要实现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加载完成后执行调用植入的js方法
[self.webView evaluateJavaScript:@"requestSensorPermission()" completionHandler:^(id _Nullable respone, NSError * _Nullable error) {
}];
执行后会弹出权限对话框
//接收到警告面板
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
completionHandler();
}
点击允许, 完事了!!!
IMG_0831.jpg