从UIWebView迁移到WKWebView


106

在我的应用程序中,我从UIWebView迁移到WKWebView,如何为WKWebView重写这些功能?

    func webViewDidStartLoad(webView: UIWebView){}
    func webViewDidFinishLoad(webView: UIWebView){}

    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print("webview asking for permission to start loading")
        if navigationType == .LinkActivated && !(request.URL?.absoluteString.hasPrefix("http://www.myWebSite.com/exemlpe"))!{
            UIApplication.sharedApplication().openURL(request.URL!)
            print(request.URL?.absoluteString)
            return false
        }
        print(request.URL?.absoluteString)
        lastUrl = (request.URL?.absoluteString)!

        return true
    }


    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        print("webview did fail load with error: \(error)")
        let testHTML = NSBundle.mainBundle().pathForResource("back-error-bottom", ofType: "jpg")
        let baseUrl = NSURL(fileURLWithPath: testHTML!)

        let htmlString:String! = "myErrorinHTML"
        self.webView.loadHTMLString(htmlString, baseURL: baseUrl)
    }

听起来您应该看看navigationDelegateWKWebView
luk2302 '16

Answers:


205

UIWebView => WKWebView等效

didFailLoadWithError => didFailNavigation
webViewDidFinishLoad => didFinishNavigation
webViewDidStartLoad => didStartProvisionalNavigation
shouldStartLoadWithRequest => decidePolicyForNavigationAction

关于shouldStartLoadWithRequest你可以写:

func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: ((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 where !url.absoluteString.hasPrefix("http://www.myWebSite.com/example") {
            UIApplication.sharedApplication().openURL(url)
            print(url.absoluteString)
            decisionHandler(.Cancel)
        return
        }
        default:
            break
    }

    if let url = navigationAction.request.URL {
        print(url.absoluteString)
    }
    decisionHandler(.Allow)
}

对于didFailLoadWithError

func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation, withError error: NSError) {
    print("webView:\(webView) didFailNavigation:\(navigation) withError:\(error)")
    let testHTML = NSBundle.mainBundle().pathForResource("back-error-bottom", ofType: "jpg")
    let baseUrl = NSURL(fileURLWithPath: testHTML!)

    let htmlString:String! = "myErrorinHTML"
    self.webView.loadHTMLString(htmlString, baseURL: baseUrl)
}

1
webViewDidFinishLoad和didFinishNavigation不完全相同。在页面完全加载之前,将调用didFinishNavigation方法。
Michal Cichon

文档说此方法仅适用于osx。问题是针对iOS
Gargo

1
@Gargo看一下这两个描述:webViewDidFinishLoaddidFinishNavigation,如您所见,也可用于iOS 8.0+
Alessandro Ornano

stackoverflow.com/questions/46171410/…- 有人帮我这个问题@AlessandroOrnano
Siva

4
请注意,这些方法是在WKNavigationDelegate(不是WKUIDelegate)中声明的。
Mike Keskinov

30

这是用于迁移Objective-C方法

1)shouldStartLoadWithRequest-> DecisionPolicyForNavigationAction

记得打电话给 decisionHandler

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
       if (navigationAction.navigationType == UIWebViewNavigationTypeLinkClicked) {

       }
       NSString *url = [navigationAction.request.URL query];

       decisionHandler(WKNavigationActionPolicyAllow);
}

2)webViewDidStartLoad-> didStartProvisionalNavigation

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
}

3)webViewDidFinishLoad-> didFinishNavigation

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
}

4)didFailLoadWithError-> didFailNavigation

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
}

3
应该是WKNavigationTypeLinkActivated而不是UIWebViewNavigationTypeLinkClicked
CupawnTae

12

将UIWebView迁移到WKWebView,Swift 4

等效于shouldStartLoadWithRequest

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    var action: WKNavigationActionPolicy?

    defer {
        decisionHandler(action ?? .allow)
    }

    guard let url = navigationAction.request.url else { return }

    print(url)

    if navigationAction.navigationType == .linkActivated, url.absoluteString.hasPrefix("http://www.example.com/open-in-safari") {
        action = .cancel                  // Stop in WebView
        UIApplication.shared.openURL(url) // Open in Safari
    }
}

等效于webViewDidStartLoad

func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    print(String(describing: webView.url))
}

等效于didFailLoadWithError

func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
    let nserror = error as NSError
    if nserror.code != NSURLErrorCancelled {
        webView.loadHTMLString("404 - Page Not Found", baseURL: URL(string: "http://www.example.com/"))
    }
}

等效于webViewDidFinishLoad

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    print(String(describing: webView.url))
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.