Way*_*eio 6 https xcode ios swift urlsession
我正在尝试对我运行的网站执行查询。然而,目前该网站的证书无效(目前有正当理由)。
\n\n我正在尝试使用以下代码查询它:
\n\nprivate 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}\nRun Code Online (Sandbox Code Playgroud)\n\n但是,我得到:
\n\nNSURLSession/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.\nRun 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>\nRun Code Online (Sandbox Code Playgroud)\n\n是的,我不打算以不安全的访问方式将其发布到应用程序商店,但我需要测试代码,但现在我们无法获得有效的证书,因此这纯粹是出于开发目的。
\n首先,将会话的委托设置为符合以下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)
这将允许通过信任服务器进行不安全的连接。
警告:请勿在生产应用程序中使用此代码,这是潜在的安全风险。
| 归档时间: |
|
| 查看次数: |
1603 次 |
| 最近记录: |