Anybody know how to handle authentication in the 2.0 version of AFNetworking? I tried the below without success. The block is getting called (I had an NSLog in there) but the response is still a 401 error
[self setTaskDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing *credential) {
*credential = [[NSURLCredential alloc] initWithUser:username password:password persistence:NSURLCredentialPersistenceForSession];
return NSURLSessionAuthChallengeUseCredential;
}];
I think this is a bug in AFNetworking 2.0. Here is the implementation:
- (void)URLSession:(NSURLSession *)session
task:(NSURLSessionTask *)task
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler
{
NSURLSessionAuthChallengeDisposition disposition = NSURLSessionAuthChallengePerformDefaultHandling;
__block NSURLCredential *credential = nil;
if (self.taskDidReceiveAuthenticationChallenge) {
disposition = self.taskDidReceiveAuthenticationChallenge(session, task, challenge, &credential);
} else {
[self URLSession:session didReceiveChallenge:challenge completionHandler:completionHandler];
return;
}
if (completionHandler) {
completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, credential);
}
}
Note that even though you're specifying NSURLSessionAuthChallengeUseCredential
, AFNetworking is passing back NSURLSessionAuthChallengePerformDefaultHandling
, which states "Default handling for the challenge - as if this delegate were not implemented; the credential parameter is ignored."