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

Tomen picture Tomen · Oct 12, 2010 · Viewed 16.1k times · Source

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?

Answer

Lily Ballard picture Lily Ballard · Jan 13, 2011

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.