Using NSURLCredentialStorage with a synchronous NSURLConnection
I am having a problem very similar to this question here: Can I use NSURLCredentialStorage for HTTP Basic Authentication?
The author of that question accepted an answer but later posted that the solution code was returning NSURLErrorUserCancelledAuthentication errors. I am using DIGEST authentication, but otherwise my code is doing the same thing, and returns the same error.
I do not want to send the username and password in cleartext, so I definitely don't want to simply tack the username and password onto the front of the URL. Is there some way to get NSURLConnection's sendSynchronousRequest:returningResponse:error: method to consult the shared NSURLCredentialStorage? It sounds like the type of thing a category would be good for, but I haven't the faintest idea of how I would do it--it sounds like I'd have to completely reimplement the sendSynchronousRequest:returningResponse:error: method to get it to work.
How can I perform a synchronous URL connection that consults the shared NSURLCredentialStorage?
This may not entirely answer your question, but: synchronous fetches via NSURLConnection have a host of problems (authentication being the least one), and if at all possible you should really restructure your app to use the asynchronous API instead, which will most likely not have the problem you see regarding authentication.
Absolutely you can. Create your NSURLCredential, and add to NSURLCredentialStorage as the default for the protection space. Example:
// Permananent, session, whatever. NSURLCredential *credential = [NSURLCredential credentialWithUser:username password:password persistence: NSURLCredentialPersistencePermanent]; // Make sure that if the server you are accessing presents a realm, you set it here. NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:@"blah.com" port:0 protocol:@"http" realm:nil authenticationMethod:NSURLAuthenticationMethodHTTPBasic]; // Store it [[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential forProtectionSpace:protectionSpace];
At this point, any subsequent NSURLConnection that is challenged using a protection space that matches what you set will use this credential