swiftnsurlsessionapp-transport-securityswift5

Allow Arbitrary Loads not working after Swift 5 conversion


I have an application which interacts with APIs on locally hosted servers with self-signed certificates. I have included code to allow arbitrary loads in the info.plist, and also included the URLSessionDelegate for when we receive a challenge.

I have a print line in the urlsession function, and that line is never getting printed, so I feel like that code is never being called. I am inheriting URLSessionDelegate in my class. This all worked in Swift 4.

func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {

    //accept all certs when testing, perform default handling otherwise
        print("Accepting cert as always")
        completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
}

Here's the errors received:

2019-06-04 09:59:55.604023-0500 The MUT[8866:1617557] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9843)
2019-06-04 09:59:55.604056-0500 The MUT[8866:1617557] Task <F8D75C99-49ED-45BE-B764-942B748942DB>.<1> HTTP load failed (error code: -1202 [3:-9843])
2019-06-04 09:59:55.604150-0500 The MUT[8866:1617558] Task <F8D75C99-49ED-45BE-B764-942B748942DB>.<1> finished with error - code: -1202```

Solution

  • Make sure you've signed your delegate correctly or try signing it in the viewDidLoad of your ViewController.

    This erro: HTTP Load Failed is solved like this:

    NSAppTransportSecurity -> NSAllowsArbitraryLoads = true