Load custom htmlString error when WKWebView loadRequest fails

In my controller, I have a call to WKWebViewInstance.loadRequest (url). If the Internet is not available, I want to upload an error message to WKWebView.

I found that

func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) 

Called when WKWEbView navigation fails without an Internet connection. When I call the webView.loadHtmlString () call inside the above delegation method, nothing happens.

How to detect a lack of network connectivity while a WKWEbView navigation request is made, and instead load the corrected error message into the web view?

My delegate method code

  func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) { webView.stopLoading() webView.loadHTMLString(Constants.OfflineHtmlString!,baseURL: nil) } 
+5
source share
1 answer

IF you need to display an error message for the user when he is not connected to the Internet,

You can check if you are connected to the Internet even before downloading the request; Reachability is a popular api that usually helps to verify this. There seems to be a quick port here https://github.com/ashleymills/Reachability.swift

I recommend using the above option; If you still want to allow it to crash and then display an error, make sure you specify OfflineHtmlString and check the error code before loading OfflineHtmlString ;

I don't know if your html string is really; If it is valid, I would do something like below;

 func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) { if(error.code == NSURLErrorNotConnectedToInternet){ webView.loadHTMLString(Constants.OfflineHtmlString!,baseURL: nil) } } 
+6
source

All Articles