不允许向本地主机发出请求 - swift

Not allowed to make request to local host - swift

我无法 post 到 swift 5、XCode 版本 11.6 (11E708) 和 iOS 13.6 中的服务器。我收到此错误:

2020-08-26 08:20:55.252545-0400 iris[1642:721953] Task <BBB3809B-7BEF-4F60-9685-774027ADA7E6>.<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={NSUnderlyingError=0x2810ad710 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 "(null)"}, NSErrorFailingURLStringKey=http://localhost:8000/searchImage/, NSErrorFailingURLKey=http://localhost:8000/searchImage/, NSLocalizedDescription=The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.}
error=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={NSUnderlyingError=0x2810ad710 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 "(null)"}, NSErrorFailingURLStringKey=http://localhost:8000/searchImage/, NSErrorFailingURLKey=http://localhost:8000/searchImage/, NSLocalizedDescription=The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.}

我关注了这个问题 并更新了我的 info.plist

<key> App Transport Security Settings </key>
<dict>
    <key> Allow Arbitrary Loads </key>
    <true />

请注意,此时我不关心安全问题。此外,我尝试了一个干净的构建,然后删除了我的派生数据文件夹,但我仍然无法 post 到服务器。在另一个项目中,我在 Info.plist 中设置了这个键,一切都很好。有什么建议吗?

如果您从源代码编辑 info.plist,以允许所有域,请更改如下值:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/> 
</dict>

那么它应该如下所示 属性 列表:

为了更好的方法,您可以默认禁用它并为特定域添加例外,如下所示。

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <false/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>yourdomain.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

打开项目目标的 info.plist 文件并添加名为 NSAppTransportSecurity 的密钥作为字典。

将 NSAllowsArbitraryLoads 添加为布尔值,并在 NSAppTransportSecurity 下将其值设置为 YES,如下图 -