我正在尝试对我运行的网站执行查询。但是,目前,该网站的证书无效(出于正当理由)。
我正在尝试使用以下代码查询它:
private static func performQuery(_ urlString: String) {
guard let url = URL(string: urlString) else {
return
}
print(url)
URLSession.shared.dataTask(with: url) {
(data, response, error) in
if error != nil {
print(error!.localizedDescription)
}
guard let data = data else {
return
}
do {
let productDetails = try JSONDecoder().decode([ProductDetails].self, from: data)
DispatchQueue.main.async {
print(productDetails)
}
} catch let jsonError {
print(jsonError)
}
}.resume()
}
但是,我得到:
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
The certificate for this server is invalid. You might be connecting to a server that is pretending to be “mydomain.com” which could put your confidential information at risk.
如何进行不安全的 URLSession 查询(相当于 CURL 中的 -k)?
我试过设置这些:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>mydomain.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSTemporaryExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
是的,我不打算以不安全的访问方式将其发布到 App Store,但我需要对代码进行测试,而现在我们无法获得有效的证书,因此这纯粹是出于开发目的。
最佳答案
首先,将 session 的委托(delegate)设置为符合 URLSessionDelegate
的类,例如:
let session = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue.main)
在你的类中添加符合
didReceiveChallenge
协议(protocol)的 URLSessionDelegate
方法的实现public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
}
这将允许通过信任服务器进行不安全的连接。
警告 :请勿在生产应用程序中使用此代码,这是潜在的安全风险。