Generally I like to just "fire and forget" with NSURL's sendAsynchronousRequest class method using the completion handler block but it seems that might not be an option when authentication is needed.
When using a completion handler style request like this:
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.mysite.com/"]]
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
//Do Stuff
}];
What is the proper way to handle authentication? Do I need to alloc and init the NSURLConnection and set a delegate instead of doing using this class method style? I think I understand how to authenticate correctly with the delegate function but I'm trying to figure out if I can include that in the completionHandler block or if there is a better way to do this.
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if ([challenge previousFailureCount] > 0) {
NSLog(@"Authentication Failure");
[connection cancel];
}
else
{
NSURLCredential *credential = [NSURLCredential credentialWithUser:self.username
password:self.password
persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
}