OC代码
- (WKWebView *)webView
{
if (!_webView) {
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
WKUserContentController * wkUController = [[WKUserContentController alloc] init];
[wkUController addScriptMessageHandler:self name:@"jsCallOCFunction"];
config.userContentController = wkUController;
_webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - kNavHeight - kTabbarHeight)configuration:config];
_webView.backgroundColor = [UIColor whiteColor];
_webView.UIDelegate = self;
_webView.scrollView.bounces = NO;
_webView.navigationDelegate = self;
}
return _webView;
}
实现代理:这里以点击H5文件链接下载文件为例
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
NSDictionary *dic = message.body;
if ([dic[@"method"] isEqualToString:@"downloadFilePreview"]) {
NSString *url = dic[@"url"];
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"name"] = dic[@"name"];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
[HttpTool downLoadFileWithUrl:url params:params success:^(id json) {
[MBProgressHUD hideHUDForView:self.view];
if (json) {
DownLoadFilePreviewController *downVc = [[DownLoadFilePreviewController alloc]init];
downVc.url = json;
self.isrefresh = NO;
[self.navigationController pushViewController:downVc animated:YES];
}else{
[MBProgressHUD hideHUDForView:self.view];
[MBProgressHUD showError:@"下载文件失败,请稍后重试"];
}
} failure:^(NSError *error) {
[MBProgressHUD hideHUDForView:self.view];
[MBProgressHUD showError:@"下载文件失败,请稍后重试"];
}];
}
}
H5代码
window.webkit.messageHandlers.scan.postMessage()
网友评论