前言
公司因業(yè)務(wù)調(diào)整,需要使用h5頁面,以前使用的webview在這次改革中因出現(xiàn)bug被淘汰了,于是我就開始苦逼的填坑之路.借此記錄我的辛路歷程(吐槽歷程)....
正文
關(guān)于webview與wkwebview的區(qū)別,百度比比皆是,我就不多陳述.
填坑一:
? ?在項目中改用wkwebview加載頁面,頁面只顯示在屏幕的左上角(屏幕的1/4處),其余部分空白.而在我的測試demo中顯示正常.(抓狂中.....).百度的很多都沒解決方法.于是使用笨方法,在以前備份的項目中新建一個viewcontroller加載頁面,竟奇跡般的好了.....無語中...求解惑...
填坑三:無網(wǎng)絡(luò)或服務(wù)器異常情況下加載本地頁面(以下的本地頁面放在同一路徑下)
? ?頁面加載失敗會執(zhí)行代理方法是:
- (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的環(huán)境下使用上面的代碼頁面呈縮小狀態(tài)(無解...).另辟他路:
NSURL *pathUrl = [[NSBundle mainBundle] URLForResource:@"404" withExtension:@"html"];
[self.webView loadRequest:[NSURLRequest requestWithURL:pathUrl]];
填坑五:由四坑引起的頁面不顯示的坑
在收到響應(yīng)決定跳轉(zhuǎn)的代理方法中判斷條件不足導(dǎo)致,完整判斷如下:
/* 3.在收到服務(wù)器的響應(yīng)頭,根據(jù)response相關(guān)信息,決定是否跳轉(zhuǎn)。 */
- (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 = @"項目網(wǎng)址的host";
NSError *error = nil;
if (![urlhost hasPrefix:comhost] && [[[url scheme] lowercaseString] isEqualToString:@"http"]){
decisionHandler(WKNavigationResponsePolicyCancel);
[self loadFailViewWithError:error];
}else{
decisionHandler(WKNavigationResponsePolicyAllow);
}}
填坑六:由五坑引起的點擊頁面上的刷新按鈕,一直刷新的坑
在失敗的代理方法中未做判斷,導(dǎo)致無網(wǎng)絡(luò)狀態(tài)下點擊,產(chǎn)生死循環(huán).唉(還是太菜啊)
添加判斷如下:
- (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