public class MyURLSessionDelegate: NSObject, URLSessionDelegate {
public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if challenge.protectionSpace.authenticationMethod
!= NSURLAuthenticationMethodClientCertificate {
completionHandler(.performDefaultHandling, nil)
return
}
guard let file = Bundle(for: HTTPAccessURLSessionDelegate.self).url(forResource: p12Filename, withExtension: "p12"),
let p12Data = try? Data(contentsOf: file) else {
completionHandler(.performDefaultHandling, nil)
return
}
let password = "MyP12Password"
let p12Contents = PKCS12(pkcs12Data: p12Data, password: password)
guard let identity = p12Contents.identity else {
completionHandler(.performDefaultHandling, nil)
return
}
let credential = URLCredential(identity: identity,
certificates: nil,
persistence: .none)
challenge.sender?.use(credential, for: challenge)
completionHandler(.useCredential, credential)
}
}