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

问题描述

我无法在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)"},NSLocalizedDescription=The resource Could not be loaded because the App Transport Security policy requires the use of a secure connection.}

我关注了这个问题How can I delete derived data in Xcode 8?,并更新了我的info.plist

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

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

解决方法

如果您将info.plist作为源代码进行编辑,要允许所有域,请更改以下值:

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

然后它应该像下面的属性列表一样:

enter image description here

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

<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>

enter image description here