1WKWebview的使用
1.1导入<WebKit/WebLit>
@property(nonatomic,strong) WKWebView *contentWebView;
1.2configuration
WKWebViewConfiguration * config = [[WKWebViewConfiguration alloc] init];
WKPreferences* prefierences = [[WKPreferencesalloc]init];
prefierences.javaScriptCanOpenWindowsAutomatically = YES;
prefierences.javaScriptEnabled=YES; //可以相应web的JS
config.preferences= prefierences;
self.contentWebView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
2存在的坑
2.1 缓存问题
前端在更改了页面之后,由于缓存,导致请求的页面没有更新。可能会出现代码没有问题,逻辑也没问题,但就是无法进行交互的情况。暴力的方式就是,直接在模拟器上删除APP,然后重新运行。
2.2页面无法跳转
实现WKNavigationDelegate协议
- (void)webView:(WKWebView*)webViewdecidePolicyForNavigationAction:(WKNavigationAction*)navigationActiondecisionHandler:(void(^)(WKNavigationActionPolicy))decisionHandler { decisionHandler(WKNavigationActionPolicyAllow);
//allow或者cancel
}
2.3JS调用原生
2.3.1添加对js方法的监听
[self.contentWebView.configuration.userContentController addScriptMessageHandler:self name:@"{{function_name}}"];
// 移除方法 [self.contentWebView.configuration.userContentController removeScriptMessageHandlerForName:@"{{function_name}}"];
2.3.2前端页面的代码
window.webkit.messageHandlers.{{function_name}}.postMessage("")
postMessage("")表示传递了一个空字符串作为参数。如果iOS不需要参数,也请传一个空字符串或者NULL,如果写成postMessage(),会导致iOS无法监听到这个方法
2.3.3iOS处理JS的“请求”
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
if ([message.name isEqualToString:@"{{function_name}}"]) {
NSString*idStr = message.body; //传过来的参数,
}elseif(){
}
2.3.4iOS调用JS方法
NSString*jsFunction = [NSStringstringWithFormat:@"{{other_function}}('%@')",jsonStr];
[self.contentWebViewevaluateJavaScript: jsFcuntion completionHandler:^(id_Nullabledata,NSError*_Nullableerror) {
}];
{{other_function}}表示你想调用的web里面的js方法,jsonStr代表传过去的值,是一个字符串,其他类型的参数不确定是否能调用,最终合成一个string 让iOS去处理
注意:{{function_name}} ,{{other_function}} 应该换成和前端约定好的字段,最终的代码不带{{}}
2.4内存不释放
[self.contentWebView.configuration.userContentController addScriptMessageHandler:self name:@"xxx"];
的addScriptMessageHandler:self 可能导致一个循环引用 self->web view->config->userContentController->self,造成self无法正常dealloc,可以调整为在viewwillappear:中添加JS监听,在viewDidDesappear中移除这个监听。
网友评论