[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接口了。

相关推荐
HarderCoder2 天前
Swift 6 并发时代,如何优雅地“抢救”你的单例?
swift
zhangmeng2 天前
FlutterBoost在iOS26真机运行崩溃问题
flutter·app·swift
HarderCoder2 天前
SwiftUI 踩坑记:onAppear / task 不回调?90% 撞上了“空壳视图”!
swift
HarderCoder2 天前
@isolated(any) 深度解析:Swift 并发中的“隔离追踪器”
swift
大熊猫侯佩2 天前
桃花岛 Xcode 构建秘籍:Swift 中的 “Feature Flags” 心法
app·xcode·swift
moonless02222 天前
FastAPI框架,这一小篇就能搞懂精髓。
http·fastapi
悄然林静2 天前
Mac终端执行`brew doctor`报`openssl@1.1`警告
mac·xcode·apple
用户092 天前
SwiftUI Charts 函数绘图完全指南
ios·swiftui·swift
YungFan2 天前
iOS26适配指南之UIColor
ios·swift
HarderCoder2 天前
Swift 6.2 新特性 `@concurrent` 完全导读
swift