如何在iOS中执行不安全的URLSession查询

我正在尝试对我运行的网站执行查询.但是,目前,该网站的证书无效(目前有正当理由).

我试图用这个代码查询它:

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,但是我需要测试代码,现在我们无法获得有效的证书,所以这纯粹是出于开发目的.

最佳答案 首先,将会话的委托设置为符合URLSessionDelegate的类,如:

let session = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue.main)

在您的类中添加didReceiveChallenge方法的实现,该方法符合URLSessionDelegate协议

public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
    completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
}

这将允许通过信任服务器来进行不安全的连接.

警告:请勿在生产应用程序中使用此代码,这是一种潜在的安全风险.

点赞