2

有人知道如何在 2.0 版本的 AFNetworking 中处理身份验证吗?我尝试了以下但没有成功。该块被调用(我在那里有一个 NSLog)但响应仍然是 401 错误

[self setTaskDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing *credential) {
    *credential = [[NSURLCredential alloc] initWithUser:username password:password persistence:NSURLCredentialPersistenceForSession];
    return NSURLSessionAuthChallengeUseCredential;
}];
4

2 回答 2

4

我认为这是 AFNetworking 2.0 中的一个错误。这是实现:

- (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);
    }
}

请注意,即使您指定NSURLSessionAuthChallengeUseCredential了 , AFNetworking 也会传回NSURLSessionAuthChallengePerformDefaultHandling,其中指出“挑战的默认处理 - 好像未实现此委托;凭据参数被忽略。”

于 2013-08-25T02:24:36.890 回答
0

斯威夫特 3.0

覆盖给定的方法,

override func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {

    completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))

}
于 2017-01-12T16:43:17.463 回答