iOS: How can i receive HTTP 401 instead of -1012 NSURLErrorUserCancelledAuthentication

I have a problem similar to the one described in the link below.

NSHTTPURLResponse statusCode is returning zero when it should be 401

I use [NSURLConnection sendSynchronousRequest:returningResponse:error:] to get data from a server.

When NSURLConnection receives the HTTP Code 401, it does not return anything but an error object with code -1012 from the NSURLErrorDomain. -1012 corresponds to NSURLErrorUserCancelledAuthentication. Since I have to parse the HTTP Header I need to get the original error and not what NSURLConnection made out of it.

Is there a way to receive the original 401 http packet?


Yes. Stop using the synchronous API. If you use the asynchronous delegate-based API then you have a lot more control over the connection. With this API, except in cases where an error is encountered before the HTTP header is received, you will always receive -connection:didReceiveResponse:, which gives you access to the HTTP header fields (encapsulated in an NSURLResponse object). You can also implement authentication using the relevant delegate methods if you are so inclined.


Workaround:

[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue new] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

NSHTTPURLResponse *aResponse = (NSHTTPURLResponse *)response;
int statusCodeResponse = aResponse.statusCode;

NSString *strError = [NSString stringWithFormat:@"%@", [connectionError description]];
if ([strError rangeOfString:@"Code=-1012"].location != NSNotFound) {
    statusCodeResponse = 401;
   }

Is not the best solution, but it works!