Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/116.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 此服务器的证书对于swift 3上的自签名证书无效_Ios_Ssl_Swift3 - Fatal编程技术网

Ios 此服务器的证书对于swift 3上的自签名证书无效

Ios 此服务器的证书对于swift 3上的自签名证书无效,ios,ssl,swift3,Ios,Ssl,Swift3,我正在使用swift 3,第一次使用web服务。我的web服务在HTTPS上运行,我想用加密进行测试 以下是我目前的代码: let config = URLSessionConfiguration.default // Session Configuration let session = URLSession(configuration: config) // Load configuration into Session let url = URL(string: w

我正在使用swift 3,第一次使用web服务。我的web服务在HTTPS上运行,我想用加密进行测试

以下是我目前的代码:

    let config = URLSessionConfiguration.default // Session Configuration
    let session = URLSession(configuration: config) // Load configuration into Session
    let url = URL(string: webService.getLoginUrl())!

    let task = session.dataTask(with: url, completionHandler: {
        (data, response, error) in

        if error == nil {
            do {
                if let json =
                    try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]{
                    //Implement your logic
                    print(json)
                }
            } catch {
                print("error in JSONSerialization")
            }
        } else {
            print(error!.localizedDescription)
        }

    })
    task.resume()
当我对我的测试服务器(自签名)运行此操作时,我得到:

The certificate for this server is invalid. You might be connecting to a server that is pretending to be “10.0.0.51” which could put your confidential information at risk.
所以我想做的是在测试时接受所有证书,而不是在生产中

我发现了几个网站,如:

但这些似乎早于swift 3


如何解决此问题?

经过大量研究,我了解了学员如何在swift 3中使用URLSession对象。文章太多,无法发布链接,但最终,这是最有用的:

因此,为了解决这个问题,我从URLSessionElegate继承了我的类,然后添加了以下函数:

func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {

    //accept all certs when testing, perform default handling otherwise
    if webService.isTesting() {
        print("Accepting cert as always")
        completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
    }
    else {
        print("Using default handling")
        completionHandler(.performDefaultHandling, URLCredential(trust: challenge.protectionSpace.serverTrust!))
    }
}

ISTest()调用确定我是否在使用测试服务器,然后在测试模式下接受所有证书。

什么是webService?