[Swift]Xcode模拟器无法请求http接口问题

1.以前偷懒一直是这样设置

bash 复制代码
<key>NSAppTransportSecurity</key>
<dict>
	<key>NSAllowsArbitraryLoads</key>
	<true/>
	<key>NSAllowsArbitraryLoadsInWebContent</key>
	<true/>
</dict>

现在我在Xcode16.3上,这种设置方式在真机上能请求http(应该是设备开启了开发者模式),但在模拟器上请求http是被拒绝的。报错如下:

Cannot start load of Task <AAC1C590-5604-43A7-984F-3D486C5996DF>.<1> since it does not conform to ATS policy

Task <AAC1C590-5604-43A7-984F-3D486C5996DF>.<1> finished with error [-1022] Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." UserInfo={NSLocalizedDescription=The resource could not be loaded because the App Transport Security policy requires the use of a secure connection., NSErrorFailingURLStringKey=http://114.55.151.190:9527/api/onlineGoods/getGoodsList?page=1\&pageSize=20, NSErrorFailingURLKey=http://114.55.151.190:9527/api/onlineGoods/getGoodsList?page=1\&pageSize=20, _NSURLErrorRelatedURLSessionTaskErrorKey=(

"LocalDataTask <AAC1C590-5604-43A7-984F-3D486C5996DF>.<1>"

), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <AAC1C590-5604-43A7-984F-3D486C5996DF>.<1>, NSUnderlyingError=0x60000129bde0 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 "(null)"}}

问题就是由于 App Transport Security (ATS) 默认限制了非 HTTPS 请求。

2.现在需要这样设置

bash 复制代码
<key>NSAppTransportSecurity</key>
<dict>
      <key>NSAllowsArbitraryLoads</key> 
      <false/>
       <key>NSExceptionDomains</key>
       <dict>
            <key>example.com</key> <!--Include your domain at this line -->
            <dict>
                <key>NSIncludesSubdomains</key>
                <true/>
                <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
                <true/>
                <key>NSTemporaryExceptionMinimumTLSVersion</key>
                <string>TLSv1.1</string>
            </dict>
       </dict>
</dict>

这里NSAllowsArbitraryLoads必须是false,因为它不允许所有不安全的连接,但例外列表允许连接到一些没有 HTTPS 的域。

这样模拟器上就能正常请求http接口了。

相关推荐
HarderCoder1 天前
我们真的需要 typealias 吗?——一次 Swift 抽象成本的深度剖析
swift
HarderCoder1 天前
ByAI-Swift 6 全览:一份面向实战开发者的新特性速查手册
swift
rainFFrain1 天前
Boost搜索引擎项目(详细思路版)
网络·c++·http·搜索引擎
HarderCoder1 天前
Swift 中 let 与 var 的真正区别:不仅关乎“可变”与否
swift
HarderCoder1 天前
深入理解 Swift 6.2 并发:从默认隔离到@concurrent 的完整指南
swift
大熊猫侯佩1 天前
拒绝羡慕 Cursor!Xcode 自己也能利用 AI 大模型让撸码如虎添翼【超详细配置】
macos·ai编程·xcode
ToTensor1 天前
Paraformer实时语音识别中的碎碎念
人工智能·语音识别·xcode
猿究院--冯磊1 天前
计算机网络--HTTP协议
网络协议·计算机网络·http
让代码飞~2 天前
idea进阶技能掌握, 使用自带HTTP测试工具,完全可替代PostMan
java·http·intellij-idea·postman
麦兜*2 天前
Swift + Xcode 开发环境搭建终极指南
开发语言·ios·swiftui·xcode·swift·苹果vision pro·swift5.6.3