Migracja z UIWebView do WKWebView


108

w mojej aplikacji migruję z UIWebView do WKWebView, jak mogę przepisać te funkcje dla WKWebView?

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

i

    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)
    }

Brzmi jak powinien przyjrzeć navigationDelegatez WKWebView.
luk2302

Odpowiedzi:


211

UIWebView => Odpowiednik WKWebView

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

O shouldStartLoadWithRequesttym możesz napisać:

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)
}

Oraz dla 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 i didFinishNavigation nie są dokładnie takie same. Metoda didFinishNavigation jest wywoływana przed pełnym załadowaniem strony.
Michał Cichon

dokumentacja mówi, że ta metoda jest przeznaczona tylko dla OSX. Pytanie dotyczyło iOS
Gargo

1
@Gargo Spójrz na oba opisy: webViewDidFinishLoad , didFinishNavigation , jak widać, jest dostępne również na iOS 8.0+
Alessandro Ornano

stackoverflow.com/questions/46171410/… - ktoś mi pomoże w tym problemie @AlessandroOrnano
Siva

4
Zwróć uwagę, że te metody są zadeklarowane w WKNavigationDelegate(nie WKUIDelegate).
Mike Keskinov

30

Oto metody Objective-C dotyczące migracji

1) shouldStartLoadWithRequest -> decydujPolicyForNavigationAction

Pamiętaj, aby zadzwonić do 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
powinno to być WKNavigationTypeLinkActivatedraczej niż UIWebViewNavigationTypeLinkClicked?
CupawnTae

12

Migracja UIWebView do WKWebView, Swift 4 :

Odpowiednik 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
    }
}

Odpowiednik webViewDidStartLoad:

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

Odpowiednik 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/"))
    }
}

Odpowiednik webViewDidFinishLoad:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    print(String(describing: webView.url))
}
Korzystając z naszej strony potwierdzasz, że przeczytałeś(-aś) i rozumiesz nasze zasady używania plików cookie i zasady ochrony prywatności.
Licensed under cc by-sa 3.0 with attribution required.