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

당신 같은 소리는 한 번 봐 소요 navigationDelegate의를 WKWebView.
luk2302

비슷한 문제는 - 당신을 도울 수 있습니다 - stackoverflow.com/questions/46793618/ios-wkwebview-vs-uiwebview
Krunal

답변:


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 : webViewDidFinishLoad , didFinishNavigation 것은 , 당신은 참조로 8.0 이상 iOS 용도 가능합니다
알레산드로 Ornano

stackoverflow.com/questions/46171410/... - 사람의 도움을 저에게이 문제 @AlessandroOrnano
시바

4
이 메서드는 WKNavigationDelegate(not WKUIDelegate) 에서 선언된다는 점에 유의하십시오 .
Mike Keskinov

30

마이그레이션을 위한 Objective-C 방법 은 다음과 같습니다.

1) shouldStartLoadWithRequest-> determinePolicyForNavigationAction

전화하는 것을 잊지 마십시오 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))
}
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.