我正在尝试对我运行的网站进行查询。但是,当前,此网站的证书无效(出于当前有效的原因)。
我正在尝试使用以下代码对其进行查询:
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,但是我需要对代码进行测试,并且现在我们无法获得有效的证书,因此,这纯粹是出于开发目的。 / p>
答案 0 :(得分:1)
首先,将会话的代表设置为符合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!))
}
这将通过信任服务器允许不安全的连接。
警告:请勿在生产应用中使用此代码,这有潜在的安全风险。
答案 1 :(得分:0)
尝试以下例外情况:
.TextBody = "Here is your data:" & vbrLf & vbCrLf & RangeToTable(activesheet.usedRange)