错误域= NSURLErrorDomain代码= -999“已取消”的Xcode

时间:2018-12-11 11:44:12

标签: swift xcode ssl

我正在尝试向服务器发送请求,该服务器是https但没有SSL

我尝试在下面的代码中忽略ssl证书验证:

func loadInfoAny(parameters: parameters, url: "https://domain/WebApiMobileGateway/api/MobileGatewayApi/PreActivation", completionHandler:@escaping (Bool, [[String: Any]]?) -> ()) {
    let headers: HTTPHeaders = [
        "Content-Type": "application/json"
    ]


    let sessionManager = SessionManager()
    sessionManager.delegate.taskDidReceiveChallengeWithCompletion = { (_, _, challenge, completionHandler) -> Void in
        // Pass test server with self signed certificate
        if challenge.protectionSpace.host == url {
            completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
        } else {
            completionHandler(.performDefaultHandling, nil)
        }
    }

    sessionManager.request(url, method:.post, parameters: parameters, headers : headers)
        .validate()
        .responseJSON { response in

            switch response.result {

            case let .success(value):

                 print(value)

            case let .failure(error):
                print(error)
                completionHandler(false, nil)
            }
    }

}

但是我得到这个错误:

  

Error Domain = NSURLErrorDomain代码= -999“已取消”   UserInfo = {NSErrorFailingURLStringKey = https://domain/WebApiMobileGateway/api/MobileGatewayApi/PreActivation,NSLocalizedDescription =已取消,   NSErrorFailingURLKey = https://domain/WebApiMobileGateway/api/MobileGatewayApi/PreActivation}。

我尝试将域添加到NSAppTransportSecurity中的Info.plist中,但这没有用。开启NSAllowsArbitraryLoads也不起作用。

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

问题是您正在将主机与URL进行比较。

更改条件如下

 if challenge.protectionSpace.host == "41.230.10.77" {
     completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
 } else {
     completionHandler(.performDefaultHandling, nil)
 }