自从我使用iOS 9升级现有项目以来,我不断收到错误:
发生SSL错误,无法与服务器建立安全连接。
对于iOS9,Apple作为App Transport Security (ATS)的一部分,在iOS 9中做出了一个激进的决定,禁用了来自iOS应用程序的所有不安全的HTTP流量。
要简单地禁用ATS,您可以通过打开Info.plist来执行此步骤,并添加以下行:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
在我的情况下,我在我的模拟器中遇到了这个问题,因为我的计算机的日期落后于当前日期。因此,当您遇到SSL错误时,请检查此案例。
即使允许任意加载(NSAllowsArbitraryLoads = true
)是一个很好的解决方法,您也不应该完全禁用ATS,而是启用您想要允许的HTTP连接:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>yourserver.com</key>
<dict>
<!--Include to allow subdomains-->
<key>NSIncludesSubdomains</key>
<true/>
<!--Include to allow HTTP requests-->
<key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
<true/>
<!--Include to specify minimum TLS version-->
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.1</string>
</dict>
</dict>
</dict>
iOS 9强制使用HTTPS的连接为TLS 1.2以避免最近的漏洞。在iOS 8中,甚至支持未加密的HTTP连接,因此旧版本的TLS也没有出现任何问题。作为解决方法,您可以将此代码段添加到Info.plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
如果您只是针对特定域,可以尝试将其添加到应用程序的Info.plist中:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>example.com</key>
<dict>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
似乎iOS 9.0.2中断了对有效HTTPS端点的请求。我目前的怀疑是它需要SHA-256证书,否则它会因此错误而失败。
要重现,请使用safari检查UIWebView,然后尝试导航到任意HTTPS端点:
location.href = "https://d37gvrvc0wt4s1.cloudfront.net/js/v1.4/rollbar.min.js"
// [Error] Failed to load resource: An SSL error has occurred and a secure connection to the server cannot be made. (rollbar.min.js, line 0)
现在尝试google(因为他们当然有SHA-256证书):
location.href = "https://google.com"
// no problemo
添加运输安全性的例外(如上面的@stéphane-bruckert的回答所述)可以解决这个问题。我还假设完全禁用NSAppTransportSecurity
也会起作用,虽然我已经读过完全禁用它可能会危及您的应用审核。
[编辑]我发现简单地枚举我在NSExceptionDomains
dict中连接的域修复了这个问题,即使将NSExceptionAllowsInsecureHTTPLoads
设置为true也是如此。 :\
问题是服务器端的ssl证书。任何事情都在干扰或证书与服务不匹配。例如,当一个站点拥有www.mydomain.com的ssl证书,而您使用的服务在myservice.mydomain.com上运行时。那是一台不同的机器。
当我将HTTPS URL指定为:https://www.mywebsite.com时,我收到同样的错误。然而,当我指定它没有三个W时,它工作正常:https://mywebsite.com。
Xcode项目 - > goto info.plist和Click + Button然后添加(App Transport Security Settings)展开,允许任意载入设置为YES。谢谢
我的问题是NSURLConnection
,并且在iOS9中被弃用,因此我将所有API更改为NSURLSession
并解决了我的问题。