Connect to a Server with Invalid Certificate using NSURLSession (swift2,xcode7,ios9) Connect to a Server with Invalid Certificate using NSURLSession (swift2,xcode7,ios9) xcode xcode

Connect to a Server with Invalid Certificate using NSURLSession (swift2,xcode7,ios9)


Take a look at this article.Shipping an App With App Transport Security particularly the sections about self-signed certificates.

You'll most likely need the delegate method of the form,

func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {    completionHandler(        .UseCredential,         NSURLCredential(trust: challenge.protectionSpace.serverTrust!)    )}

Adding this to my own comms class that uses NSURLSession fixed the issue.


When creating the URL Session, use the initializer, that sets the delegate along with the configuration, like below:

let urlSession = URLSession(configuration: urlSessionConfiguration, delegate: self, delegateQueue: nil)

Then, implement the following delegate method, it should work.

func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {    let urlCredential = URLCredential(trust: challenge.protectionSpace.serverTrust!)    completionHandler(.useCredential, urlCredential)}

However, it is very important to note, that this is a security issue, and we should not be trying to connect to servers with invalid certificates.


Many of the answers are almost there, but not quite. So here is what worked for me on Xcode 12.4

In my Requesting Class

    let session: URLSession    let sessionDelegate: HTTPRequestDelegate    private  init() {        let configuration = URLSessionConfiguration.default        // Some more configuration settings        // ...        sessionDelegate = HTTPRequestDelegate()        session = URLSession(configuration: configuration,                                 delegate:  sessionDelegate,                                 delegateQueue: nil)    }

Where:

public class HTTPRequestDelegate: NSObject, URLSessionDelegate{    // Get Challenged twice, 2nd time challenge.protectionSpace.serverTrust is nil, but works!    public func urlSession(_ session: URLSession,                    didReceive challenge: URLAuthenticationChallenge,                    completionHandler: (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {        print("In invalid certificate completion handler")        if challenge.protectionSpace.serverTrust != nil {            completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))        } else {            completionHandler(.useCredential, nil)        }    }}