UIWebView => WKWebView Equivalent
UIWebViewDelegate => WKNavigationDelegate
delegate => navigationDelegate
didFailLoadWithError => didFailNavigation
webViewDidFinishLoad => didFinishNavigation
webViewDidStartLoad => didStartProvisionalNavigation
shouldStartLoadWithRequest => decidePolicyForNavigationAction
About shouldStartLoadWithRequest
you can write:
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
print("webView:(webView) decidePolicyForNavigationAction:(navigationAction) decisionHandler:(decisionHandler)")
switch navigationAction.navigationType {
case .linkActivated:
if navigationAction.targetFrame == nil {
self.webView?.loadRequest(navigationAction.request)
}
if let url = navigationAction.request.url, !url.absoluteString.hasPrefix("http://www.myWebSite.com/example") {
UIApplication.shared.open(url)
print(url.absoluteString)
decisionHandler(.cancel)
return
}
default:
break
}
if let url = navigationAction.request.url {
print(url.absoluteString)
}
decisionHandler(.allow)
}
And for the didFailLoadWithError
:
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print("webView:(webView) didFailNavigation:(navigation) withError:(error)")
let testHTML = Bundle.main.path(forResource: "back-error-bottom", ofType: "jpg")
let baseUrl = URL(fileURLWithPath: testHTML!)
let htmlString = "myErrorInHTML"
self.webView.loadHTMLString(htmlString, baseURL: baseUrl)
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…