问题
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)
}
回答1:
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)
}
}
回答2:
Subbu is correct just for swift4
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
print("loading error", error)
if(error._code == NSURLErrorNotConnectedToInternet){
loadingLabel.text = "Hit Cancel to return back"
}
errorDisplay(error: "Loading error. Please try again later.\(error)")
spinner.stopAnimating()
loadingLabel.text = "Hit Cancel to return back"
}
来源:https://stackoverflow.com/questions/31666444/load-custom-error-htmlstring-when-wkwebview-loadrequest-fails