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

标签 ios ssl swift3

我正在使用 swift 3 并第一次访问网络服务。我的 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.

所以我想做的是在测试时接受所有证书,但在生产中不接受。

我找到了几个网站,例如:

http://www.byteblocks.com/Post/Use-self-signed-SSL-certificate-in-iOS-application https://github.com/socketio/socket.io-client-swift/issues/326

但这些似乎早于 swift 3。

我该如何解决这个问题?

最佳答案

经过大量研究,我了解了委托(delegate)如何在 swift 3 中使用 URLSession 对象。发布链接的内容太多了,但最后,这是最有帮助的:https://gist.github.com/stinger/420107a71a02995c312036eb7919e9f9

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

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!))
    }
}

isTesting() 调用确定我是否在使用测试服务器,然后如果我们处于测试模式,我们将接受所有证书。

关于ios - 此服务器的证书对于 swift 3 上的自签名证书无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42939099/

相关文章:

swift - 具有自定义 NSView 的 OS X NSMenuItem 不会突出显示 swift

arrays - 如何正确解析字典数组

ios - 临时应用程序构建中的错误记录和检索?

android - 适用于 IOS 和 Android 的支付网关

ios - 标题下方 NavigationBar 上的 UiSegmentedControl

internet-explorer - POODLE 漏洞、JBoss 和 IE

redirect - Nginx:将 http://example.com 和 http://*.example.com 重定向到 https://example.com

ios - 调度组不阻止代码运行

docker - 反向代理无法加载 ssl 证书

ios - 如何在转到另一个 View Controller 时停止后台调用?