您好,登錄后才能下訂單哦!
要配置NSURLSession以接受自簽名證書,您需要創(chuàng)建一個NSURLProtectionSpace對象,并將其傳遞給NSURLSessionConfiguration的TLSMinimumSupportedProtocol和TLSMaximumSupportedProtocol屬性。以下是一個示例代碼片段,展示了如何配置NSURLSession以接受自簽名證書:
// 創(chuàng)建NSURLProtectionSpace對象
let host = "yourhost.com"
let port = 443
let protocol = "https"
let realm = "Your Realm"
let space = URLProtectionSpace(host: host, port: port, protocol: protocol, realm: realm, authenticationMethod: NSURLAuthenticationMethodServerTrust)
// 創(chuàng)建NSURLSessionConfiguration對象
let config = URLSessionConfiguration.default
// 設(shè)置TLSMinimumSupportedProtocol和TLSMaximumSupportedProtocol屬性
config.TLSMinimumSupportedProtocol = .tlsProtocol12
config.TLSMaximumSupportedProtocol = .tlsProtocol12
// 創(chuàng)建NSURLSession對象
let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
// 實現(xiàn)NSURLSessionDelegate協(xié)議方法
extension YourViewController: URLSessionDelegate {
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if challenge.protectionSpace == space {
// 驗證自簽名證書
let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
completionHandler(.useCredential, credential)
} else {
completionHandler(.performDefaultHandling, nil)
}
}
}
在這個示例中,我們創(chuàng)建了一個NSURLProtectionSpace對象,用于指定要接受自簽名證書的主機、端口和協(xié)議。然后,我們創(chuàng)建了一個NSURLSessionConfiguration對象,并設(shè)置了TLSMinimumSupportedProtocol和TLSMaximumSupportedProtocol屬性,以指定支持的TLS協(xié)議版本。最后,我們創(chuàng)建了一個NSURLSession對象,并實現(xiàn)了URLSessionDelegate協(xié)議方法,以驗證自簽名證書并使用URLCredential對象進行身份驗證。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。