Created
February 3, 2022 10:08
-
-
Save aydin-emre/d6e11e34ab335dced2d96acf691ba505 to your computer and use it in GitHub Desktop.
Using URLSessionDelegate
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
| 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