我尝试在我的Swift 5中的服务器上获取网站的文本,在我看来,它有一个有效的RSA SSL证书(一个为我的子域付费的证书,不是自签名的),但我总是得到错误1202“该服务器的证书无效”。当我从Safari访问该网站时,没有任何问题。Safari说证书是有效的。
public func createRequest(qMes: String, location: String, method: String , completionBlock: @escaping (String) -> Void) -> Void
{
let requestURL = URL(string: location)
var request = URLRequest(url: requestURL!)
request.httpMethod = method
request.httpBody = qMes.data(using: .utf8)
let requestTask = URLSession.shared.dataTask(with: request) {
(data: Data?, response: URLResponse?, error: Error?) in
if(error != nil) {
print("Error: \(error)")
}else
{
let outputStr = String(data: data!, encoding: String.Encoding.utf8) as String?
completionBlock(outputStr!);
}
}
requestTask.resume()
}该函数的用法如下:
createRequest(qMes: "", location: "https://user:password@subdomain.server.com:3452/index.php", method: "GET") { (output) in
print(output)
}我将此添加到我的Info.plist中
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>server.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSExceptionRequiresForwardSecrecy</key>
<false/>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSAllowsLocalNetworking</key>
<true/>
</dict>由于该应用程序仅供私人使用,因此证书验证是否存在问题并不重要,因此我想以某种方式绕过此错误。
我确实在许多帖子中读到,修改Info.plist以禁用证书验证是不够的,但在尝试修改我的代码10个小时后,我放弃了,因为我在Swift中是一个绝对的初学者,我没有让它运行。
奇怪的事实:当在我的独立watchOS应用程序(手表本身和模拟器)中运行此代码时,由于证书验证而失败,但是当在游乐场中运行相同的代码时,没有出现问题。
我也尝试了Alamofire 5,同样的结果。
有人能帮我修改一下我的代码吗?
发布于 2019-12-26 12:59:26
例如,如果您确实想要忽略SSL证书,则可以使用URLSessionDelegate公开的方法忽略它,如下所示:
extension YOURVIEWCONTROLLER: URLSessionDelegate {
public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
//Trust the certificate even if not valid
let urlCredential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
completionHandler(.useCredential, urlCredential)
}
}在代码中创建URLSession时,请记住将委托设置为self。例如,您可以使用以下命令设置它:
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)我希望它能帮上忙
https://stackoverflow.com/questions/59483557
复制相似问题