A synchronous NSURLConnection
will absolutely work with NSURLCredentialStorage
. Here’s how things usually work:
NSURLConnection
requests the page from the server- The server replies with a 401 response
NSURLConnection
looks to see what credentials it can glean from the URL- If the URL did not provide full credentials (username and password),
NSURLConnection
will also consultNSURLCredentialStorage
to fill in the gaps - If full credentials have still not been determined,
NSURLConnection
will send the-connection:didReceiveAuthenticationChallenge:
delegate method asking for credentials - If the
NSURLConnection
now finally has full credentials, it retries the original request including authorization data.
By using the synchronous connection method, you only lose out on step 5, the ability to provide custom authentication. So, you can either pre-provide authentication credentials in the URL, or place them in NSURLCredentialStorage
before sending the request. e.g.
NSURLRequest *request =
[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://user:[email protected]"]];
[NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
or:
NSURLCredential *credential = [NSURLCredential credentialWithUser:@"user"
password:@"pass"
persistence:NSURLCredentialPersistenceForSession];
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
initWithHost:@"example.com"
port:0
protocol:@"http"
realm:nil
authenticationMethod:nil];
[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential
forProtectionSpace:protectionSpace];
[protectionSpace release];
NSURLRequest *request =
[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com"]];
[NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];