创建WkWebView
//js调用oc 例如 点击WkWebView内一个js编写的按钮 触发oc内操作
/// 偏好设置,涉及JS交互
WKWebViewConfiguration * configuration = [[WKWebViewConfiguration alloc] init];
configuration.preferences= [[WKPreferencesalloc]init];
configuration.preferences.javaScriptEnabled = YES;
configuration.preferences.javaScriptCanOpenWindowsAutomatically = NO;
configuration.processPool= [[WKProcessPoolalloc]init];
configuration.allowsInlineMediaPlayback = YES;
// if (iOS9()) {
// /// 缓存机制(未研究)
// configuration.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
// }
configuration.userContentController = [[WKUserContentController alloc] init];
WKWebView*wkWebView = [[WKWebViewalloc]initWithFrame:CGRectMake(0,0,self.width,self.height)configuration:configuration];
wkWebView.navigationDelegate = self;
wkWebView.UIDelegate=self;
[selfaddSubview:wkWebView];
self.wkWebview= wkWebView;
[self.wkWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
WKUserContentController *ContentController = self.wkWebview.configuration.userContentController;
[ContentControlleraddScriptMessageHandler:selfname:@"didclickflyjidimap"];///didclickflyjidimap 是与前端协议方法名
[ContentControlleraddScriptMessageHandler:selfname:@"didclickimg"];
[ContentControlleraddScriptMessageHandler:selfname:@"didclickIpone"];
[ContentControlleraddScriptMessageHandler:selfname:@"didlogin"];
////////////
//触发方法时操作
- (void)userContentController:(nonnullWKUserContentController*)userContentController didReceiveScriptMessage:(nonnullWKScriptMessage*)message {
if ([message.name isEqualToString:@"didclickflyjidimap"]) {
NSArray*arr = message.body;
if(arr.count>0) {
[selfgoMapWithX:arr[0]withY:arr[1]];
}
}elseif([message.nameisEqualToString:@"didclickimg"]){
NSArray*arr = message.body;
if(arr.count>0) {
[selffadaTuLiuLan:arr[0]];
}
}elseif([message.nameisEqualToString:@"didclickIpone"]){
NSArray*arr = message.body;
if(arr.count>0) {
[selfboDaIpone:arr[0]];
}
}elseif([message.nameisEqualToString:@"didlogin"]){
BOOLyesNO = [selfjianChaYeNoLogin];
if(yesNO ==YES){
}else{
//这里是已经登录了的
[self.wkWebview evaluateJavaScript:@"page.gotoUrl()" completionHandler:nil];
}
}
}
///////////
// oc调用js [self.flyJiDi_wkWebview evaluateJavaScript:@"oneClick()" completionHandler:nil];
/* js端代码
$(".jiaohu").on("click", function () {
alert("js://webview?arg1=111&arg2=222");
oneClick();
})
function oneClick() {
//didclickflyjidimap();
window.webkit.messageHandlers.didclickflyjidimap.postMessage(["2017-12-28","17:18"]);
}
*/