ioswkwebview

How to get webView didFail called


I am working on a wrapper for WKWebView and want to make sure I handle possible errors.

How can I make WKNavigationDelegate's method

func webView(_: WKWebView, didFail _: WKNavigation!, withError error: Error)

called?

The first thing I tried was to call webView.load(request) with invalid url. As a result, func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) only was called -- not what I wanted.

The second thing I tried was to call webView.loadHTMLString(html, baseURL: nil) with malformed html. Nevertheless, webView displayed without throwing an error.


Solution

  • You can load a valid URL and stop loading manually as soon as the navigation is committed.

    func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
     print("didCommit called - stopping navigation now.")
     webView.stopLoading()
    }
        
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
     print("didFail navigation called")
    }