Skip to content

Instantly share code, notes, and snippets.

@algal
Last active August 30, 2015 05:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save algal/1e7a7ab9b1c161b1a385 to your computer and use it in GitHub Desktop.
Save algal/1e7a7ab9b1c161b1a385 to your computer and use it in GitHub Desktop.
Configure an NSURLSession so that it will load HTTPS even from servers with invalid TLS certificate
// works as of Swift 1.2, 2015-08-29
// https://developer.apple.com/library/ios/technotes/tn2232/_index.html#//apple_ref/doc/uid/DTS40012884-CH1-SECNSURLSESSION
class NSURLSessionAllowBadCertificateDelegate : NSObject, NSURLSessionDelegate
{
func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)
{
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust
{
let trustObject = challenge.protectionSpace.serverTrust
let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential,credential)
}
else {
completionHandler(NSURLSessionAuthChallengeDisposition.PerformDefaultHandling,nil)
}
}
}
let session = NSURLSession(
configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(),
delegate: NSURLSessionAllowBadCertificateDelegate(),
delegateQueue: nil)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment