WKWebView相对UIWebView的直观优势
- 更多的支持HTML5的特性
- 官方宣称的高达60fps的滚动刷新率以及内置手势
- 占用更少的内存
现在总结一下我们用WKWebView时经常用到的一些操作
页面允许跳转与取消
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{if (navigationAction.targetFrame == nil) {[webView loadRequest:navigationAction.request];}if ([navigationAction.request.URL.absoluteString containsString:@"wexin://"]){ //当url中存在weixin://时不进行页面跳转,进行其它操作//TODO: 做一些其它操作decisionHandler(WKNavigationActionPolicyCancel);}else{decisionHandler(WKNavigationActionPolicyAllow);}
}
WK与JS交互
//**********WK与JS交互**********
//配置
- (WKWebViewConfiguration *)configuration{if (!_configuration) {_configuration = [[WKWebViewConfiguration alloc] init];WKUserContentController *userContentController = [[WKUserContentController alloc] init];//jumpQRCode是和JS约定好的字符串,保证JS调用OC时判断相同就行,没有具体限制[userContentController addScriptMessageHandler:self name:@"jumpQRCode"]; _configuration.userContentController = userContentController;self.webView.configuration = _configuration;}return _configuration;
}
//JS调用OC
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{if ([message.name isEqualToString:@"openQRCode”]) {[self openQRCode];}
}
- (void)openQRCode{
//OC调用JS
NSString *JSResult = [NSString stringWithFormat:@"callback('%@','%@')", index,strScan]; //JS方法名和参数
[self.webView evaluateJavascript:JSResult completionHandler:^(id _Nullable result, NSError * _Nullable error) {NSLog(@"完成....");
}];
}
WKWebView加载Webp
COOKIE丢失
NSString *COOKIEStr = [self setJSCOOKIE];
WKUserScript *COOKIEScipt = [[WKUserScript alloc] initWithSource:COOKIEStr injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
WKUserContentController *wku = [[WKUserContentController alloc] init];
[wku addScriptMessageHandler:self name:@"openPay"];
[wku addUserScript:COOKIEScipt];-(NSString *)setJSCOOKIE{NSMutableDictionary *COOKIEsDic = [[LFCacheTool lf_getCacheObjectFromKey:COOKIES] mutableCopy];__block NSString *COOKIEStr = @"";[COOKIEsDic enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {NSDictionary *dic = obj;NSString *appendString;if ([self.url rangeOfString:@"丢失COOKIE的链接"].location != NSNotFound){//根据后台需要的样式修改COOKIE(多参数少参数都可能获取失败)appendString= [NSString stringWithFormat:@"'%@=%@;path=/;domain=%@';",key, dic[@"Value"],@"丢失COOKIE的链接"];}COOKIEStr = [NSString stringWithFormat:@"%@document.COOKIE=%@",COOKIEStr,appendString];}];return COOKIEStr;
}