根据您收到无效证书错误并且您正在使用 NSURLConnection 的评论,您的解决方案是实现这些委托。看看这是否能解决问题。
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]
forAuthenticationChallenge:challenge];
}
请注意,您基本上忽略了 SSL 错误并允许连接继续进行。因此,如果您要打开应用程序进行黑客攻击。对于测试,您可以使用它,但请确保在生产环境中安装正确的证书。
但是,如果您想正确处理此问题并在证书不正确的情况下警告用户,您可以这样做。
OSStatus err = noErr;
BOOL trusted = NO;
NSURLProtectionSpace * protectionSpace = challenge.protectionSpace;
SecTrustRef serverTrustRef = protectionSpace.serverTrust;
SecTrustResultType trustResult;
//check if the server trust that we got from the server can be trusted by default
err = SecTrustEvaluate(serverTrustRef, &trustResult);
trusted = (err == noErr) && ((trustResult == kSecTrustResultProceed) || (trustResult == kSecTrustResultUnspecified));
if (trusted) //if the site is trusted then continue with that trust
{
[challenge.sender useCredential:[NSURLCredential credentialForTrust:protectionSpace.serverTrust]
forAuthenticationChallenge:challenge];
}
else //if not then warn the user about this and let the user make a decision
{
//warn the user about the cert problem using a dialog with options to continue or ignore.
//Continue alert action call : [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]
forAuthenticationChallenge:challenge];
//Dont continue action: [challenge.sender continueWithoutCredentialForAuthenticationChallenge:_challenge];
//OR call: [sender cancelAuthenticationChallenge:challenge];
}
}