I want to inform user when HTTP error 404 etc is received. How can I detect that? I\'ve already tried to implement
- (void)webView:(UIWebView *)webView didFailL
I am new to iOS and Swift development, and needed to find a way to accomplish this as well, using WKWebView (not UI). I was fortunate enough to run across this site that gave me the following answer, which works perfectly for my needs. It might help passers-by that are looking for the same answer I was.
Using this function (from WKNavigationDelegate):
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void)
You can create custom responses based on the HTTP response, like so:
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
// get the statuscode
guard let statusCode = (navigationResponse.response as? HTTPURLResponse)?.statusCode
else {
decisionHandler(.allow)
return
}
// respond or pass-through however you like
switch statusCode {
case 400..<500:
webView.loadHTMLString("You shall not pass!
", baseURL: nil)
case 500..<600:
webView.loadHTMLString("Sorry, our fault.
", baseURL: nil)
default:
print("all might be well")
}
decisionHandler(.allow)
}