Skip to content

Instantly share code, notes, and snippets.

@aydin-emre
Created February 3, 2022 10:08
Show Gist options
  • Select an option

  • Save aydin-emre/d6e11e34ab335dced2d96acf691ba505 to your computer and use it in GitHub Desktop.

Select an option

Save aydin-emre/d6e11e34ab335dced2d96acf691ba505 to your computer and use it in GitHub Desktop.
Using URLSessionDelegate
class NSURLSessionPinningDelegate: NSObject, URLSessionDelegate {
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
if let serverTrust = challenge.protectionSpace.serverTrust {
if #available(iOS 12.0, *) {
let isServerTrusted = SecTrustEvaluateWithError(serverTrust, nil)
if(isServerTrusted) {
if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) {
let serverCertificateData = SecCertificateCopyData(serverCertificate)
let data = CFDataGetBytePtr(serverCertificateData)
let size = CFDataGetLength(serverCertificateData)
let cert1 = NSData(bytes: data, length: size)
let file_der = Bundle(for: type(of: self)).path(forResource: "easmart.co", ofType: "der")
if let file = file_der {
if let cert2 = NSData(contentsOfFile: file) {
if cert1.isEqual(to: cert2 as Data) {
completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
return
}
}
}
}
}
}
}
}
completionHandler(.cancelAuthenticationChallenge, nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment