Xcode7支持HTTP

/ 0评 / 0

最近在Xcode 7中向服务器发送请求访问JSON数据时, 控制台打印了以下错误信息:

Application Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'

看原因应该是获取到的NSData数据为空, 所以在调用+ JSONObjectWithData: 方法时出现错误. 检验http链接可以正常访问. 后来发现在iOS9应用通讯安全策略进行了升级, 已不再支持http这种不安全的协议:

App Transport Security

App Transport Security (ATS) enforces best practices in the secure connections between an app and its back end. ATS prevents accidental disclosure, provides secure default behavior, and is easy to adopt; it is also on by default in iOS 9 and OS X v10.11. You should adopt ATS as soon as possible, regardless of whether you’re creating a new app or updating an existing one.

If you’re developing a new app, you should use HTTPS exclusively. If you have an existing app, you should use HTTPS as much as you can right now, and create a plan for migrating the rest of your app as soon as possible. In addition, your communication through higher-level APIs needs to be encrypted using TLS version 1.2 with forward secrecy. If you try to make a connection that doesn't follow this requirement, an error is thrown. If your app needs to make a request to an insecure domain, you have to specify this domain in your app's Info.plist file.

至于为什么http不安全, http是超文本传输协议, 信息采用明文传输, 而https则使用SSL加密传输协议进行传输. 既然服务器的链接并不是我们前端所能决定的, 如果一定要发送http协议的请求, 可以修改当前项目的Info.plist文件来实现:

方式一: 使用文本编辑Info.plist, 在当中添加:


NSAppTransportSecurity

  NSAllowsArbitraryLoads
  

方式二: 在Info.plist中添加:

xcode-http

以上两种方式所实现的效果是一致的, 但是并不严谨, 建议有选择的允许HTTP请求(这个操作方法与上文"方式一"相同):

NSAppTransportSecurity

  NSExceptionDomains
  
    域名.com
    
      
      NSIncludesSubdomains
      
      
      NSTemporaryExceptionAllowsInsecureHTTPLoads
      
      
      NSTemporaryExceptionMinimumTLSVersion
      TLSv1.1
    
  

当然, 以上方法都是建立在所访问的请求是HTTP类型的基础上, 一劳永逸的方法就是让服务端升级使用TLS 1.2 SSL加密请求的HTTPS协议.

服务器已支持TLS 1.2 SSL ,但iOS9上还是不行,还要进行链接里的适配操作。”那是因为:ATS只信任知名CA颁发的证书,小公司所使用的 self signed certificate,还是会被ATS拦截。对此,建议使用链接中给出的NSExceptionDomains,并将你们公司的域名挂在下面。

评论已关闭。