项目中为了优化性能,将UIWebView替换为WKWebView,踩了一些坑:
1、WKWebVIew在iOS11之后才可以使用Xib构建,如果项目支持iOS11之前的系统,那么就不能直接用Xib构建了,但是替换还是要的,所以采取了如下方案:
构建一个空白的placeView,与原UIWebView一样的布局,用来占位的。然后我们再手动创建WKWebView,添加到空白的placeView中。
此外需要注意的点是:如果采用wkView.frame = placeView.bounds构建,需要在viewDidLayoutSubviews中更新一下frame。
2、不能加载http的链接:
屏幕快照 2018-07-09 下午3.16.35.png然后再实现NavigationDelegate代理方法:
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential,card);
}
}
3、web页面不能点击了,是因为web页面打开了了一个新的页面,需要如下设置
// 在请求开始加载之前,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
if (navigationAction.targetFrame == nil) {
[webView loadRequest:navigationAction.request];
}
if (decisionHandler) {
decisionHandler(WKNavigationActionPolicyAllow);
}
}
4、获取到web的title
方案1:创建WKWebView时添加监听,在监听中获取到title:
- (WKWebView*)webView
{
if (!_webView) {
_webView = [[WKWebView alloc]initWithFrame:CGRectZero];
_webView.navigationDelegate = self;
[self.webBgView addSubview:_webView];
[_webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
}
return _webView;
}
//WkWebView的 回调
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
if ([keyPath isEqualToString:@"title"]) {
if (object == self.webView) {
NSString *str = self.webView.title;
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
方案2:使用java的函数
//加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation
{
[_hud stopAnimating];
[self.webView evaluateJavaScript:@"document.getElementById('title').innerHTML" completionHandler:^(id _Nullable string, NSError * _Nullable error) {
if (!error && [string isKindOfClass:[NSString class]]) {
NSString *str = string;
_ttLabel.text = str&&str.length >0?str:[@"Travel Information" internationalString:@"CCP"];
_ttLabel.hidden = NO;
}
}];
}
5、使用本地的html,该如何加载:
NSString *str1 = [[NSBundle mainBundle] pathForResource:@"travalAirport" ofType:@"html"];
NSURL *url = [NSURL fileURLWithPath:str1];
NSData *data = [NSData dataWithContentsOfFile:str1];
[self.webView loadData:data MIMEType:@"text/html" characterEncodingName:@"UTF-8" baseURL:url];
加油~
网友评论