前段時間做項(xiàng)目的時候遇到 http 不能使用的情況,特此總結(jié)一下解決方法。
輸出的錯誤信息如下:
App 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.
官方文檔是這樣解釋的:
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'sInfo.plistfile.
注 : App Transport Security (ATS) 是 IOS9 中引入的新特性
以上用一句話概括就是: 新特性要求 App 內(nèi)訪問的網(wǎng)絡(luò)必須使用HTTPS協(xié)議
解決方案
1.在 Info.plist 中添加NSAppTransportSecurity類型Dictionary。
2.在NSAppTransportSecurity下添加NSAllowsArbitraryLoads類型Boolean, 值設(shè)為YES

以上方法雖然解決了 http 不能正常使用的問題,但是蘋果提供的安全保障也被關(guān)閉了, 對于不支持 https 協(xié)議的應(yīng)該首先考慮 例外
方法如下:
右鍵 Info.plist 選擇 open with source code
添加類似如下配置:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>qq.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
<key>sina.com.cn</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
注 : 根據(jù)自己需要的域名修改
NSIncludeSubdomains 是否包括子域;