iOS8之后苹果推出WKWebView代替UIWebView说是更轻量级加载更快,最近的项目中用到WKWebView与JS的交互,下面来总结一下使用
1.WKWebView的初始化
@property(nonatomic,strong)WKUserContentController * usercontentVC;
_usercontentVC = [[WKUserContentController alloc]init];
config.userContentController = _usercontentVC;
WKPreferences *preferences = [[WKPreferences alloc] init];
config.preferences = preferences;
//是否允许与js进行交互,默认是YES的,如果设置为NO,js的代码就不起作用了 preferences.javaScriptEnabled = YES;
_webview = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) configuration:config]; _webview.backgroundColor = [UIColor whiteColor];
_webview.UIDelegate = self; //设置代理
_webview.navigationDelegate = self;
_webview.allowsBackForwardNavigationGestures = YES;
_webview.allowsLinkPreview = YES; //允许连接3Dtouch
_webview.customUserAgent = @"WebView/1.0.0";
[self.view addSubview:_webview];
2.webView向JS发送消息
- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^ _Nullable)(_Nullable id, NSError * _Nullable error))completionHandler
这个方法是web调用JS,javaScriptString是JS方法和参数
eg:
NSString * js_str = [NSString stringWithFormat:@"locationResult('%@','%f','%f')",_reGeocode.formattedAddress,_location.coordinate.longitude,_location.coordinate.latitude];
[self.webview evaluateJavaScript:js_str completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"----------locationerror = %@",error);
}];
3.js向原生发送消息
//添加自定义的脚本
WKUserScript *js = [[WKUserScript alloc] initWithSource:jsSource injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO];
[_usercontentVC addUserScript:js];
[_usercontentVC addScriptMessageHandler:self name:@"currentCookies"]; //这里self要遵循协 WKScriptMessageHandler
在这个方法中收到消息:
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
if ([message.name isEqualToString:@"appMessage"]) {
NSString *cookiesStr = message.body; //message.body返回的是一个id类型的对象,所以可以支持很多种js的参数类型(js的function除外)
NSLog(@"当前的消息为: %@", cookiesStr);
//可以在这里接受到js的消息,添加自己要做的功能
}
}
4.最后一点是,当服务端的内容更新后,我们会发现本地的还是之前的内容,这里我们需要清除缓存
NSArray * types =@[WKWebsiteDataTypeMemoryCache,WKWebsiteDataTypeDiskCache];
NSSet *websiteDataTypes = [NSSet setWithArray:types];
NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{ }]; //清除缓存的方法
网友评论