WKWebView catch HTTP error codes WKWebView catch HTTP error codes ios ios

WKWebView catch HTTP error codes

The key was to wait for the response and then inspect the object, no error is called on http code

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {    if ([navigationResponse.response isKindOfClass:[NSHTTPURLResponse class]]) {        NSHTTPURLResponse * response = (NSHTTPURLResponse *)navigationResponse.response;        if (response.statusCode == 401) {            // here we go        }    }    decisionHandler(WKNavigationResponsePolicyAllow);}

Swift version:

public func webView(    _ webView: WKWebView,    decidePolicyFor navigationResponse: WKNavigationResponse,    decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {    if        let httpResponse = navigationResponse.response as? HTTPURLResponse,        !(200..<400).contains(httpResponse.statusCode)    {        // Do something    }    decisionHandler(.allow)}