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

Way*_*eio 6 https xcode ios swift urlsession

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

\n\n

我正在尝试使用以下代码查询它:

\n\n
private static func performQuery(_ urlString: String) {\n    guard let url = URL(string: urlString) else {\n        return\n    }\n    print(url)\n    URLSession.shared.dataTask(with: url) {\n        (data, response, error) in\n        if error != nil {\n            print(error!.localizedDescription)\n        }\n        guard let data = data else {\n            return\n        }\n        do {\n            let productDetails = try JSONDecoder().decode([ProductDetails].self, from: data)\n            DispatchQueue.main.async {\n                print(productDetails)\n            }\n        } catch let jsonError {\n            print(jsonError)\n        }\n    }.resume()\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

但是,我得到:

\n\n
NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)\nThe certificate for this server is invalid. You might be connecting to a server that is pretending to be \xe2\x80\x9cmydomain.com\xe2\x80\x9d which could put your confidential information at risk.\n
Run Code Online (Sandbox Code Playgroud)\n\n

如何进行不安全的 URLSession 查询(相当于 CURL 中的 -k)?

\n\n

我尝试过设置这些:

\n\n
<key>NSAppTransportSecurity</key>\n<dict>\n    <key>NSAllowsArbitraryLoads</key>\n    <true/>\n    <key>NSExceptionDomains</key>\n    <dict>\n        <key>mydomain.com</key>\n        <dict>\n            <key>NSExceptionAllowsInsecureHTTPLoads</key>\n            <true/>\n            <key>NSIncludesSubdomains</key>\n            <true/>\n            <key>NSTemporaryExceptionRequiresForwardSecrecy</key>\n            <false/>\n            <key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key>\n            <true/>\n        </dict>\n    </dict>\n</dict>\n
Run Code Online (Sandbox Code Playgroud)\n\n

是的,我不打算以不安全的访问方式将其发布到应用程序商店,但我需要测试代码,但现在我们无法获得有效的证书,因此这纯粹是出于开发目的。

\n

Sha*_*y D 5

首先,将会话的委托设置为符合以下URLSessionDelegate条件的类:

let session = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue.main)
Run Code Online (Sandbox Code Playgroud)

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

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

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

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