How do I get the last HTTP Status Code from a UIWebView?

后端 未结 9 2134
栀梦
栀梦 2020-12-08 16:43

I would like to detect when a page load request give to a UIWebView has returned a status code in the 5xx or 4xx range.

I\'ve setup the delegate for the web view a

9条回答
  •  感情败类
    2020-12-08 17:17

    Here's a work-around to get HTTP response code, but with sending just one request to each URL:-

    BOOL isLoad;
    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
        NSLog(@"Requesting: %@ - %d - %@", request.URL.absoluteString, navigationType, request.URL.host);
        if (navigationType != UIWebViewNavigationTypeOther) {
            //Store last selected URL
            self.loadedURL = request.URL.absoluteString;
        }
        if (!isLoad && [request.URL.absoluteString isEqualToString:loadedURL]) {
            [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                if (connectionError || ([response respondsToSelector:@selector(statusCode)] && [((NSHTTPURLResponse *)response) statusCode] != 200 && [((NSHTTPURLResponse *)response) statusCode] != 302)) {
                    //Show error message
                    [self showErrorMessage];
                }else {
                    isLoad = YES;
                    [_wbView loadData:data MIMEType:[response MIMEType]
                     textEncodingName:[response textEncodingName]
                              baseURL:[response URL]];
                }
            }];
            return NO;
        }
        isLoad = NO;
        return YES;
    }
    

提交回复
热议问题