How to detect and handle HTTP error codes in UIWebView?

前端 未结 9 676
无人及你
无人及你 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:54

    NSURLConnection is the class you are looking for, I don't think this can be done directly in a UIWebView.

    You can use the synchronous method

    + (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error
    

    Or the Asynchronous ones. These are harder to setup as you have to append all the bits of data you get into the 1 NSData, but the end result is the same.


    Regardless of if you use the Synchronous or Asynchronous methods:

    If you get a NSError* object then there was a COMMS error. As noted in the other responses, this is NOT a HTTP status code but rather a communication problem.

    If the connection succeeded, you get an NSURLResponse and NSData. Importantly the NSURLResponse for HTTP requests is actually the NSHTTPURLResponse subclass!

    Then you must check the response to see what the error code is. Try this (where _responseInfo is your NSURLResponse object):

      NSInteger httpStatusCode = (NSHTTPURLResponse*)_responseInfo.statusCode;
    

    responseInfo should always be a NSHTTPURLResponse for HTTP requests... but you might be wise to have an assert there just in case.

    IF the statusCode is a success (i.e. 200) then your NSData object should contain the data of the response (whatever that may be). If the status code indicates an error then the NSData may contain a textual description of the error from the server.

    NB. I really don't recommend tyring to parse the NSData object for the error message. That's what the HTTP 'statusCode' is for!

提交回复
热议问题