这适用于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 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,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: Developer: Guides and Sample Code: Technical Note TN2232: HTTPS Server Trust Evaluation
要创建自签名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
解决方法
将自签名SSL证书(通过拖放)安装到iPhone模拟器上后,转到设置>一般>关于>证书信任设置并为您的证书启用完全信任.