Skip to content

Instantly share code, notes, and snippets.

@yycking
Created January 23, 2017 10:26
Show Gist options
  • Save yycking/d30c4eb3c5be5f0715798ea62311ca23 to your computer and use it in GitHub Desktop.
Save yycking/d30c4eb3c5be5f0715798ea62311ca23 to your computer and use it in GitHub Desktop.
accept a self-signed SSL certificate
import UIKit
class NSURLSessionPinningDelegate: NSObject, URLSessionDelegate {
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) {
if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
if let trust = challenge.protectionSpace.serverTrust,
let pem = Bundle.main.path(forResource: "https", ofType: "cer"),
let data = NSData(contentsOfFile: pem),
let cert = SecCertificateCreateWithData(nil, data) {
let certs = [cert]
SecTrustSetAnchorCertificates(trust, certs as CFArray)
completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: trust))
return
}
}
// Pinning failed
completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
}
}
var url = URL(string: "https://test.com/")
let operationQueue = OperationQueue()
let config = URLSessionConfiguration.ephemeral
let session = URLSession(configuration: config, delegate: NSURLSessionPinningDelegate(), delegateQueue: operationQueue)
session.dataTask(with: url!) { (data, urlResponse, error) in
if let error = error {
print(error)
}
if let urlResponse = urlResponse {
print(urlResponse)
}
}.resume()
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment