How to detect and handle HTTP error codes in UIWebView?

You could capture the URLRequest here:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

and hand the request over to the delegate and return no. Then in the received response call from NSURLConnection cancel the connection and if everything is fine (check response) load the urlrequest once more in the webview. Make sure to return YES in the above call when loading the urlrequest again.

Not very elegant, but it might work.


My implementation inspired by Radu Simionescu's response :

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSCachedURLResponse *urlResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:webView.request];
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) urlResponse.response;
    NSInteger statusCode = httpResponse.statusCode;
    if (statusCode > 399) {
        NSError *error = [NSError errorWithDomain:@"HTTP Error" code:httpResponse.statusCode userInfo:@{@"response":httpResponse}];
        // Forward the error to webView:didFailLoadWithError: or other
    }
    else {
        // No HTTP error
    }
}

It manages HTTP client errors (4xx) and HTTP server errors (5xx).

Note that cachedResponseForRequest returns nil if the response is not cached, in that case statusCode is assigned to 0 and the response is considered errorless.