前言
公司因业务调整,需要使用h5页面,以前使用的webview在这次改革中因出现bug被淘汰了,于是我就开始苦逼的填坑之路.借此记录我的辛路历程(吐槽历程)....
正文
关于webview与wkwebview的区别,百度比比皆是,我就不多陈述.
填坑一:
在项目中改用wkwebview加载页面,页面只显示在屏幕的左上角(屏幕的1/4处),其余部分空白.而在我的测试demo中显示正常.(抓狂中.....).百度的很多都没解决方法.于是使用笨方法,在以前备份的项目中新建一个viewcontroller加载页面,竟奇迹般的好了.....无语中...求解惑...
填坑三:无网络或服务器异常情况下加载本地页面(以下的本地页面放在同一路径下)
页面加载失败会执行代理方法是:
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(nonnull NSError *)error;
填坑三:iOS 9加载本地页面的问题
iOS 9推出的加载本地页面的方法,加载页面没有效果.(无解...彻底崩溃)只能另辟他路:
NSString *path = [[NSBundle mainBundle] pathForResource:@"404" ofType:@"html"];
NSString * str = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[_webView loadHTMLString:str baseURL:[NSBundle mainBundle].resourceURL];
填坑四:iOS 8加载本地页面的问题
在iOS 8的环境下使用上面的代码页面呈缩小状态(无解...).另辟他路:
NSURL *pathUrl = [[NSBundle mainBundle] URLForResource:@"404" withExtension:@"html"];
[self.webView loadRequest:[NSURLRequest requestWithURL:pathUrl]];
填坑五:由四坑引起的页面不显示的坑
在收到响应决定跳转的代理方法中判断条件不足导致,完整判断如下:
/* 3.在收到服务器的响应头,根据response相关信息,决定是否跳转。 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
NSString *urlstring = [navigationResponse.response.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlstring];
NSString *urlhost = [url host];
NSString *comhost = @"项目网址的host";
NSError *error = nil;
if (![urlhost hasPrefix:comhost] && [[[url scheme] lowercaseString] isEqualToString:@"http"]){
decisionHandler(WKNavigationResponsePolicyCancel);
[self loadFailViewWithError:error];
}else{
decisionHandler(WKNavigationResponsePolicyAllow);
}}
填坑六:由五坑引起的点击页面上的刷新按钮,一直刷新的坑
在失败的代理方法中未做判断,导致无网络状态下点击,产生死循环.唉(还是太菜啊)
添加判断如下:
- (void)loadFailViewWithError:(NSError *)error{
[[LoadingTool shareLoadingTool] hideLoadingViewFromView:self.view];
NSDictionary *userinfo = error.userInfo;
NSURL *url = [NSURL URLWithString:userinfo[@"NSErrorFailingURLStringKey"]];
if ([[[url scheme] lowercaseString] isEqualToString:@"http"]){
NSString *path = [[NSBundle mainBundle] pathForResource:@"404" ofType:@"html"];
if(path){if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
NSString * str = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
[_webView loadHTMLString:str baseURL:[NSBundle mainBundle].resourceURL];
}else {
NSURL *pathUrl = [[NSBundle mainBundle] URLForResource:@"404" withExtension:@"html"];
[self.webView loadRequest:[NSURLRequest requestWithURL:pathUrl]];}}}}
这是目前为止遇到的所有坑,以上只是我个人贱解,欢迎大家指教!同时也欢迎大家给出更多的填坑之法.
学习的榜样:
blog.csdn.net/chenyong05314/article/details/53735215
www.brighttj.com/ios/ios-wkwebview-new-features-and-use.html