This is pretty much a Swift version of Mohd Iftekhar Qurashi's answer here:
http://stackoverflow.com/questions/21197834/the-certificate-for-this-server-is-invalid

The reason this is useful is whenever you are connecting to a server that might not be trusted by the browser. For instance, a lot of my staging servers are set up to be secure (using 'https') but haven't got a certificate yet!

If you try going to your site and your browser stops you and you get something like this:

Error image

... then this code pretty much has your app allow this connection. So it's important to note that for security reasons, you may not want this function in the final build of your app.

Here is the code:

    func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) {

        let protectionSpace = challenge.protectionSpace

        let theSender = challenge.sender

        if protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {

            if let theTrust = protectionSpace.serverTrust{

                let theCredential = NSURLCredential(trust: theTrust)

                theSender.useCredential(theCredential, forAuthenticationChallenge: challenge)

                return
            }
        }

        theSender.performDefaultHandlingForAuthenticationChallenge!(challenge)

        return
    }

I like to use this inside a helper class that incorporates the NSURLSessionDelegate funcitons to make it easy to apply this function!

    import Foundation

    class SessionDelegator : NSObject, NSURLSessionDelegate {

    func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {
        LoggingController.logString("didBecomeInvalidWithError: \(error)")
    }

    func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) {

        let protectionSpace = challenge.protectionSpace

        let theSender = challenge.sender

        if protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {

            if let theTrust = protectionSpace.serverTrust{

                let theCredential = NSURLCredential(trust: theTrust)

                theSender.useCredential(theCredential, forAuthenticationChallenge: challenge)

                return
            }
        }

        theSender.performDefaultHandlingForAuthenticationChallenge!(challenge)

        return
    }

    func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession) {
        LoggingController.logString("URLSessionDidFinishEventsForBackgroundURLSession: \(session)")
    }
}