Created
January 23, 2017 10:26
-
-
Save yycking/d30c4eb3c5be5f0715798ea62311ca23 to your computer and use it in GitHub Desktop.
accept a self-signed SSL certificate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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