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

后端 未结 9 2151
栀梦
栀梦 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:39

    Here is a nice example where they use a combination of creating a NSURLConnection for the first loading, and the UIWebView for the next pages:

    http://www.ardalahmet.com/2011/08/18/how-to-detect-and-handle-http-status-codes-in-uiwebviews/

    Basically this is the main trick, using the YES/NO return value of shouldStartLoadRequest:

    - (BOOL) webView:(UIWebView *)webView 
         shouldStartLoadWithRequest:(NSURLRequest *)request 
                     navigationType:(UIWebViewNavigationType)navigationType
    {
        if (_sessionChecked) {
            // session already checked.
            return YES;
        }
    
        // will check session.
    
        NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
        if (conn == nil) {
            NSLog(@"cannot create connection");
        }
        return NO;
    }
    

    This should get you going without using synchronous requests, especially combined with Jeff's answer.

提交回复
热议问题