Search code examples
swiftsslnsurlconnection

NSURLConnection ignoring SSL Certificate?


I know this question is asked often, but I have implemented the solution found in the answers and I'm not having any luck. I am not a Swift developer, so I'm guessing I'm missing something.

Here is my NSURLConnectionDelegate methods:

func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace) -> Bool {
    return protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust
}

func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge) {
    print("Second attempt resulted in authentication challenge")

    challenge.sender!.useCredential(NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!), forAuthenticationChallenge: challenge)
    challenge.sender!.continueWithoutCredentialForAuthenticationChallenge(challenge)
}

func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {
    print("We got a response.....")
}

func connection(connection: NSURLConnection, didFailWithError error: NSError) {
    print("============ second attempt failed ==============")
    print("\(error)")
}

The connection goes through a VPN that doesn't allow for DNS. We have to use the IP, which results in an invalid cert error. The Cert is correct, just not using the IP. I am trying to ignore the cert error but I am still getting "An SSL error has occurred and a secure connection to the server cannot be made"

My understanding is that

challenge.sender!.useCredential(NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!), forAuthenticationChallenge: challenge)
challenge.sender!.continueWithoutCredentialForAuthenticationChallenge(challenge)

Should resolve this, but it doesn't seem to be working. The print line does run, so the delegate method is being called.

Thanks!


Solution

  • As Breek suggested, NSAppTransportSecurity in info.plist did the trick for iOS 9.