【发布时间】:2016-05-06 18:26:04
【问题描述】:
我正在使用不再是有效 SSL 证书的自定义 SSL 连接到服务器。我更新了我的 info.plist 以允许任意和添加的代码绕过 NSURLConnection 委托的挑战。
-(void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSLog(@"willSendRequestForAuthenticationChallenge");
BOOL trusted = NO;
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
NSString *thePath = [[NSBundle mainBundle] pathForResource:@"cert" ofType:@"der"];
NSData *certData = [[NSData alloc] initWithContentsOfFile:thePath];
CFDataRef certDataRef = (__bridge_retained CFDataRef)certData;
SecCertificateRef cert = SecCertificateCreateWithData(NULL, certDataRef);
SecPolicyRef policyRef = SecPolicyCreateBasicX509();
SecCertificateRef certArray[1] = { cert };
CFArrayRef certArrayRef = CFArrayCreate(NULL, (void *)certArray, 1, NULL);
SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
SecTrustSetAnchorCertificates(serverTrust, certArrayRef);
SecTrustResultType trustResult;
SecTrustEvaluate(serverTrust, &trustResult);
trusted = (trustResult == kSecTrustResultUnspecified);
CFRelease(certArrayRef);
CFRelease(policyRef);
CFRelease(cert);
CFRelease(certDataRef);
}
if (trusted) {
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
} else {
[challenge.sender performDefaultHandlingForAuthenticationChallenge:challenge];
}
}
但是,间歇性地发生 SSL 错误。它没有调用代理willSendRequestForAuthenticationChallenge,而是直接调用didFailWithError 代理。
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
【问题讨论】:
标签: ios objective-c ssl nsurlconnection