The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.
問題
在根據《IOS開發指南 從helloworld到AppStore上架 第四版》學習的時候,看到第八章『樹形導航結構』使用WKWebView進行三級導航展示詳情,發現白屏
解決方案
WKWebView根據『WKNavigationDelegate』協議有幾個方法,可以追蹤載入進度
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
NSLog(@"準備載入頁面");
}
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
NSLog(@"開始載入頁面");
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
NSLog(@"已載入全部頁面");
}
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
NSLog(@"載入失敗1");
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
NSLog(@"載入失敗2%@",error.userInfo);
}
重新執行後,發現進入了didFailProvisionalNavigation
方法,這個時候我們列印error.code
得到值為-1022
。
2017-09-22 11:08:40.096041+0800 treeNavigation[6176:2793155] http://baike.baidu.com/view/3961.htm
2017-09-22 11:08:40.171849+0800 treeNavigation[6176:2793155] 準備載入頁面
2017-09-22 11:08:40.184887+0800 treeNavigation[6176:2793155] 載入失敗2{
NSErrorFailingURLKey = "http://baike.baidu.com/view/3961.htm";
NSErrorFailingURLStringKey = "http://baike.baidu.com/view/3961.htm";
NSLocalizedDescription = "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.";
NSUnderlyingError = "Error Domain=kCFErrorDomainCFNetwork Code=-1022 "(null)"";
"_WKRecoveryAttempterErrorKey" = "<WKReloadFrameErrorRecoveryAttempter: 0x17403eae0>";
}
看到這裡基本上就能猜到https
的問題了,然後我們將url進行一次搜尋替換,就可以了。
self.url = [self.url stringByReplacingOccurrencesOfString:@"http://" withString:@"https://"];