9

这适用于 iOS 10.2 及更低版本,但升级到 10.3 后,当模拟器尝试通过 HTTPS 连接到在 localhost 上运行的开发服务器时,Xcode 控制台输出以下错误:

NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802)
[] nw_coretls_callback_handshake_message_block_invoke_3 tls_handshake_continue: [-9807]

打印出节目error返回的URLSessionDataTask内容:

Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x600000527080>, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, NSErrorPeerCertificateChainKey=(
    "<cert(0x7ff3e1867200) s: localhost i: localhost>"
), NSUnderlyingError=0x60800024e880 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, kCFStreamPropertySSLPeerTrust=<SecTrustRef: 0x600000527080>, _kCFNetworkCFStreamSSLErrorOriginalValue=-9802, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, kCFStreamPropertySSLPeerCertificates=(
    "<cert(0x7ff3e1867200) s: localhost i: localhost>"
)}}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://localhost:3000/v1/login, NSErrorFailingURLStringKey=https://localhost:3000/v1/login, NSErrorClientCertificateStateKey=0}

参考:Apple:开发人员:指南和示例代码:技术说明 TN2232:HTTPS 服务器信任评估


要创建自签名 SSL 证书,我使用了以下命令:

openssl genrsa -aes256 -passout pass:x -out server.pass.key 2048
openssl rsa -passin pass:x -in server.pass.key -out server.key
rm server.pass.key
openssl req -new -sha256 -key server.key -out server.csr -subj /CN=localhost
openssl x509 -req -sha512 -days 365 -in server.csr -signkey server.key -out server.crt

来源:GitHub - seviu/iOS-SSL-localhost

4

2 回答 2

12

将您的自签名 SSL 证书(通过拖放)安装到 iPhone 模拟器上后,转到设置 > 常规 > 关于 > 证书信任设置并为您的证书启用完全信任。

于 2017-04-09T04:51:30.220 回答
0

我也有同样的问题,你必须实现 didRecieveChallenge 委托方法来处理 SSl 错误

在下面添加;URLSession 委托方法或 URLConnnection 委托方法的 didReceiveChallenge 委托方法中的代码之一。

- (void)URLSession :( NSURLSession *)session didReceiveChallenge :( NSURLAuthenticationChallenge *)challenge completionHandler :( void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler {   NSURLSessionAuthChallengeDisposition lDisposition = NSURLSessionAuthChallengeUseCredential;
NSURLCredential *credential = [[NSURLCredential alloc] init];


if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
    credential = [NSURLCredential credentialForTrust: challenge.protectionSpace.serverTrust];
    lDisposition = NSURLSessionAuthChallengeUseCredential;
}
completionHandler(lDisposition, credential);}
于 2017-09-28T08:31:36.860 回答