How to detect and handle HTTP error codes in UIWebView?

前端 未结 9 711
无人及你
无人及你 2021-02-02 11:54

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         


        
9条回答
  •  无人共我
    2021-02-02 12:41

    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.

提交回复
热议问题