Print View

Basic Authentication using NSURLConnection sendSynchronousRequest fails with (NSURLErrorDomain error -1012.)

Issue

When using a NSURLConnection with a synchronous connection using sendSynchronousRequest and Basic Authentication, the following error may be seen:

"The operation couldn’t be completed. (NSURLErrorDomain error -1012.)"

This evaluates to the constant:

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

Resolution

Use the NSURLCredentialStorage, and ensure the authenticationMethod is set to NSURLAuthenticationMethodHTTPBasic, persistence is set to NSURLCredentialPersistenceForSession or NSURLCredentialPersistencePermanent, and all parameters are correct, including host, username, password and in particular, realm:

NNSURLCredential *credential = [[NSURLCredential alloc]
                                initWithUser: @"username"
                                password: @"password"
                                persistence: NSURLCredentialPersistenceForSession];                              
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
                                         initWithHost: @"server.domain.com"
                                         port: 80
                                         protocol: @"http"
                                         realm: @"Secure Area"
                                         authenticationMethod: NSURLAuthenticationMethodHTTPBasic];
[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential forProtectionSpace:protectionSpace];

References

Products

Apple Xcode 3.2 (iOS SDK 4.2)

Created: 2nd February 2011
Updated: 2nd February 2011

Print View

© 2005-2024 Jamie Morrison