Search code examples
iosxcodesecurityswift5

Not allowed to make request to local host - swift


I am unable to post to a server in swift 5, XCode Version 11.6 (11E708), and iOS 13.6. I am receiving this error:

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

I have followed this question How can I delete derived data in Xcode 8? and updated my info.plist

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

Note I don't care about security at this point. Additionally, I've tried a clean build and then deleted my derived data folder, but still I cannot post to the server. In another project I set this key in Info.plist and everything was fine. Any suggestions?


Solution

  • If you edit info.plist from as source code, to allow all domains, change the values like:

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

    Then it should look like below as Property List:

    enter image description here

    or

    For a better way, you can disable it by default and add exceptions for specific domains like below.

    <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