Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load custom error htmlString when WKWebView loadRequest fails

In my controller I have a call to WKWebViewInstance.loadRequest(url). If there is no internet available, I want to load an error message in the WKWebView.

I have found that

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

gets called when a WKWEbView navigation fails with no internet connection. When I make the webView.loadHtmlString() call inside the above delegate method, nothing happens.

How do I detect the absence of network connection while WKWEbView navigation request is made and load a fixed error message into web view instead?

My delegate method code is

   func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
    webView.stopLoading()
    webView.loadHTMLString(Constants.OfflineHtmlString!,baseURL:  nil)
}
like image 522
shrutim Avatar asked Jul 28 '15 02:07

shrutim


1 Answers

IF the need is to display error Info to the user when not connected to internet,

You can check if you are connected to the internet even before loading the request; Reachability is a popular api that usually helps checking this. There seems to be a swift port of it here https://github.com/ashleymills/Reachability.swift

I recommend to pursue the above option; In case you still want to allow it to fail and then display the error, Ensure the correctness of your OfflineHtmlString and verify the error code before loading the OfflineHtmlString;

I don't know if your html string is valid; Provided 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)
   }
}
like image 152
Subbu Avatar answered Oct 19 '22 10:10

Subbu