23

this question is identical to the following: WKWebView catch HTTP error codes; unfortunately the methods in Obj-C are not applicable to Swift 4, thus the cited WKNavigationResponse.response is no longer of type NSHTTPURLResponse so it doesn't have the http status code.

But the issue is still the same: I need to get the http status code of the answer to detect if the expected page is loaded or not.

Please note that webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) delegate is not called in case of 404 but only in case of network issue (i.e. server offline); the func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) is called instead.

Thanks a lot for your answers.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Francesco Piraneo G.
  • 882
  • 3
  • 11
  • 25

2 Answers2

47

Using a WKNavigationDelegate on the WKWebView you can get the status code from the response each time one is received.

func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse,
             decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {

    if let response = navigationResponse.response as? HTTPURLResponse {
        if response.statusCode == 401 {
            // ...
        }
    }
    decisionHandler(.allow)
}
Onato
  • 9,916
  • 5
  • 46
  • 54
kumar reddy
  • 494
  • 5
  • 5
4

HTTPURLResponse is a subclass of URLResponse. The Swift way of “conditional downcasting” is the conditional cast as?, this can be combined with conditional binding if let:

func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse,
             decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {

    if let response = navigationResponse.response as? HTTPURLResponse {
        if response.statusCode == 401 {
            // ...
        }
    }
    decisionHandler(.allow)
}
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382