Skip to content

Instantly share code, notes, and snippets.

@edwardmp
Created June 13, 2015 15:58
Show Gist options
  • Save edwardmp/a0ffb3ace02ce4392b26 to your computer and use it in GitHub Desktop.
Save edwardmp/a0ffb3ace02ce4392b26 to your computer and use it in GitHub Desktop.
Working example of accepting self-signed SSL certificate in Swift
import UIKit
import Foundation
class ViewController: UIViewController, NSURLSessionDelegate {
override func viewDidLoad() {
super.viewDidLoad()
httpGet(NSMutableURLRequest(URL: NSURL(string: "https://example.com")!))
}
func httpGet(request: NSMutableURLRequest!) {
var configuration =
NSURLSessionConfiguration.defaultSessionConfiguration()
var session = NSURLSession(configuration: configuration, delegate: self, delegateQueue:NSOperationQueue.mainQueue())
var task = session.dataTaskWithRequest(request){
(data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if error == nil {
var result = NSString(data: data, encoding:
NSASCIIStringEncoding)!
NSLog("result %@", result)
}
}
task.resume()
}
func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) {
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust: challenge.protectionSpace.serverTrust))
}
}
@mwcs01
Copy link

mwcs01 commented Aug 2, 2017

Updated for Swift 3.1 and setup to test in a swift playground.

import UIKit
import Foundation
import PlaygroundSupport

class ViewController: UIViewController, URLSessionDelegate {
    
    
    func httpGet(request: URLRequest) {
        let configuration = URLSessionConfiguration.default
        
        let session = URLSession(configuration: configuration, delegate: self, delegateQueue:OperationQueue.main)
        let task = session.dataTask(with: request){
            (data, response, error) -> Void in
            if error == nil {
                let result = NSString(data: data!, encoding:
                    String.Encoding.ascii.rawValue)!
                NSLog("result %@", result)
            }
        }
        task.resume()
    }
    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!) )
    }
}

let vc = ViewController()
vc.httpGet(request: URLRequest( url: URL(string: "https://www.abc.net")!))
PlaygroundPage.current.needsIndefiniteExecution = true

@BilalReffas
Copy link

It seems like this will fail. All the time your completionHandler just return URLSession.AuthChallengeDisposition.useCredential. But where is the logic and the whole check? Please don't use this code for production..

@lanephillips
Copy link

It seems like this will fail. All the time your completionHandler just return URLSession.AuthChallengeDisposition.useCredential. But where is the logic and the whole check? Please don't use this code for production..

The argument URLCredential(trust: challenge.protectionSpace.serverTrust!) means "Here's your credential: just trust the server".

I used this code to connect to the web control interface of a piece of hardware which uses a self-signed cert that I do not have the ability to replace. This code works great.

@dreamer2q
Copy link

on iOS17, app built by xcode-beta (Version 15.0 beta 5), the sample code is not working.

I got error as follows:

Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “xxx” which could put your confidential information at risk."

also with code -1200

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment