How to detect and handle HTTP error codes in UIWebView? How to detect and handle HTTP error codes in UIWebView? ios ios

How to detect and handle HTTP error codes in UIWebView?


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.


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.


You're mis-interpreting what -didFailLoadWithError is for. Technically, the request succeeded. It was able to hit the server and find that the file you're requesting doesn't exist (i.e. 404). The -didFailLoadWithError method will get called if the server doesn't exist, for example. Your server exists. The file doesn't. The web view is not going to interpret errors in the content. The purpose of -didFailLoadWithError from the UIWebViewDelegate Apple Docs is:

Sent if a web view failed to load content.

From the Wikipedia article on HTTP 404:

The 404 or Not Found error message is a HTTP standard response code indicating that the client was able to communicate with the server but the server could not find what was requested. 404 errors should not be confused with "server not found" or similar errors, in which a connection to the destination server could not be made at all.

In all likelihood you'll have to parse the response text for a 404 which you could obtain with an NSURLConnection/NSURLRequest combination rather than a web view.

Best Regards,