pdiddy
pdiddy

Reputation: 6297

NSURLConnection sendSynchronousRequest response is nil upon invalid credential

I'm getting a weird behavior where using sendSynchronousRequest or sendAsynchronousRequest with invalid credential will make the nsurlresponse nil. But the old way with the [[NSURLConnection alloc] initWithRequest:request delegate:self]; I get the 401 response code.

The error value using the sendSynchronousRequest or sendAsynchronousRequest is

Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)" UserInfo=0x756ecb0 {NSErrorFailingURLKey=myurl, NSErrorFailingURLStringKey=myurl, NSUnderlyingError=0x75704d0 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1012.)"

Does someone have a clue as to why it is like that? Any information on this is appreciated. I was expecting to get a 401 response from sendSynchronousRequest or sendAsynchronousRequest

Thanks,

Upvotes: 2

Views: 1293

Answers (1)

jhabbott
jhabbott

Reputation: 19311

This error is caused when a WWW-Authenticate: HTTP header is returned with the 401 response, asking for user-interaction to enter valid credentials. The NSURLConnection processes the HTTP headers and the response body, returning the response data correctly as an NSData object, but leaving the returningResponse object as nil.

According to Apple's Foundation Constants Reference, the error -1012 is:

NSURLErrorUserCancelledAuthentication

Returned when an asynchronous request for authentication is cancelled by the user.

This is typically incurred by clicking a “Cancel” button in a username/password dialog, rather than the user making an attempt to authenticate.

I am speculating that it automatically treats the WWW-Authenticate: header as a request for credentials that was cancelled by the user (since it is headless) and generates the error. Then some other part of the code-path that should set the response is not executed because there was an error. Personally I think this is either a bug or bad design. It should be ok to get a valid HTTP response and an error at the same time, either way, you get a valid HTTP response so the returningResponse should be set. Bad Apple!

Upvotes: 4

Related Questions