Search code examples
objective-cioscocoansurlconnection

How to detect if NSURLConnection's sendSynchronousRequest:returningResponse:error: ended up being timed out or other error


I use NSURLConnection's sendSynchronousRequest:returningResponse:error: method (in a separate NSOperation thread) to connect to external server to retreive data. How do I know if the operation ended timed out, or some other network error?


Solution

  • If there was an error, the error parameter will be non-nil when sendSynchronousRequest:returningResponse:error: returns.

    You can retrieve the error code by checking the value returned by [NSError code]. The error code for time out is NSURLErrorTimedOut.

    For instance:

    NSError *error = nil;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]
    
    if (error.code == NSURLErrorTimedOut) {
    // Handle time out here
    }