Вы можете использовать приведенный ниже код для запросов SSL, используя URLSessionRequest,
fileprivate func SSLCertificateCreateTrustResult(_ serverTrust: SecTrust)->SecTrustResultType {
let certificate: SecCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0)!
let remoteCertificateData = CFBridgingRetain(SecCertificateCopyData(certificate))!
var certName = "certName"
let cerPath: String = Bundle.main.path(forResource: certName, ofType: "der")!
let localCertificateData = NSData(contentsOfFile:cerPath)!
let certDataRef = localCertificateData as CFData
let cert = (SecCertificateCreateWithData(nil, certDataRef))
let certArrayRef = [cert] as CFArray
SecTrustSetAnchorCertificates(serverTrust, certArrayRef)
SecTrustSetAnchorCertificatesOnly(serverTrust, false)
let trustResult: SecTrustResultType = SecTrustResultType.invalid
return trustResult
}
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if challenge.protectionSpace.authenticationMethod == (NSURLAuthenticationMethodServerTrust) {
let serverTrust:SecTrust = challenge.protectionSpace.serverTrust!
var localCertificateTrust = SSLCertificateCreateTrustResult(serverTrust)
SecTrustEvaluate(serverTrust, &localCertificateTrust)
if localCertificateTrust == SecTrustResultType.unspecified || localCertificateTrust == SecTrustResultType.proceed || localCertificateTrust == SecTrustResultType.recoverableTrustFailure
{
let credential:URLCredential = URLCredential(trust: serverTrust)
challenge.sender?.use(credential, for: challenge)
completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
} else {
let properties = SecTrustCopyProperties(serverTrust)
completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
}
}
else
{
completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil);
}
}
В состоянии
if localCertificateTrust == SecTrustResultType.unspecified || localCertificateTrust == SecTrustResultType.proceed || localCertificateTrust == SecTrustResultType.recoverableTrustFailure
ниже приведены типы для действительных сертификатов
SecTrustResultType.unspecified , SecTrustResultType.proceed
дляНеверный сертификат SecTrustResultType.recoverableTrustFailure
Я добавил все три в состоянии ||
, поэтому для работы с действительным и недействительным сертификатом, если вы хотите удалить любой, вы можете удалить другие типы