在使用后台会话配置时,我发现了一个关于 NSURLSession 的有线连接。我们在与服务器联系时使用自分配证书,一个工具:
- (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 {
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
if ([self.securityPolicy evaluateServerTrust:challenge.protectionSpace.serverTrust forDomain:challenge.protectionSpace.host]) {
disposition = NSURLSessionAuthChallengeUseCredential;
credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
} else {
disposition = NSURLSessionAuthChallengeCancelAuthenticationChallenge;
}
NSLog(@"ServerTrust:%@", task.originalRequest.URL);
} else if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodClientCertificate]) {
if (self.clientCertCredential && [challenge previousFailureCount] == 0) {
credential = self.clientCertCredential;
disposition = NSURLSessionAuthChallengeUseCredential;
NSLog(@"ClientCert:%@", task.originalRequest.URL);
} else {
disposition = NSURLSessionAuthChallengePerformDefaultHandling;
}
} else {
disposition = NSURLSessionAuthChallengePerformDefaultHandling;
}
}
if (completionHandler) {
completionHandler(disposition, credential);
}
}
使用 defaultSessionConfiguration 时效果很好,但是当我将会话配置更改为后台会话配置时,将循环调用此委托方法,不会调用任何其他委托方法,并且此请求将永远不会完成。
这是控制台输出:
2014-08-11 15:36:01.204 OneBox [1736:a413] ServerTrust: https://demo.mycompany.com/api/v1/files/351/1/9cc69106455d11599a08ed978fbdbe1d/contents 2014-08-11 15:36: 01.232 OneBox[1736:1413] ClientCert: https://demo.mycompany.com/api/v1/files/351/1/9cc69106455d11599a08ed978fbdbe1d/contents 2014-08-11 15:36:02.068 OneBox[1736:8c03] ServerTrust: https://demo.mycompany.com/api/v1/files/351/1/9cc69106455d11599a08ed978fbdbe1d/contents 2014-08-11 15:36:02.076 OneBox[1736:1413] ClientCert: https://demo.mycompany.com /api/v1/files/351/1/9cc69106455d11599a08ed978fbdbe1d/contents 2014-08-11 15:36:12.728 OneBox[1736:1413] ServerTrust: https://demo.mycompany.com/api/v1/files/351/ 1/9cc69106455d11599a08ed978fbdbe1d/内容 2014-08-11 15:36:12.735 OneBox[1736:1413] ClientCert: https://demo.mycompany.com/api/v1/files/351/1/9cc69106455d11599a08ed978fbdbe1d/contents