NSURLConnection 忽略 SSL 证书?

NSURLConnection ignoring SSL Certificate?

我知道这个问题经常被问到,但我已经实施了答案中找到的解决方案,但我没有任何运气。我不是 Swift 开发人员,所以我猜我遗漏了什么。

这是我的 NSURLConnectionDelegate 方法:

func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace) -> Bool {
    return protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust
}

func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge) {
    print("Second attempt resulted in authentication challenge")

    challenge.sender!.useCredential(NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!), forAuthenticationChallenge: challenge)
    challenge.sender!.continueWithoutCredentialForAuthenticationChallenge(challenge)
}

func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {
    print("We got a response.....")
}

func connection(connection: NSURLConnection, didFailWithError error: NSError) {
    print("============ second attempt failed ==============")
    print("\(error)")
}

连接通过不允许 DNS 的 VPN。我们必须使用 IP,这会导致证书无效错误。证书是正确的,只是没有使用 IP。我试图忽略证书错误,但我仍然收到 "An SSL error has occurred and a secure connection to the server cannot be made"

我的理解是

challenge.sender!.useCredential(NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!), forAuthenticationChallenge: challenge)
challenge.sender!.continueWithoutCredentialForAuthenticationChallenge(challenge)

应该可以解决这个问题,但它似乎不起作用。打印行确实 运行,因此正在调用委托方法。

谢谢!

正如 Breek 所建议的那样,info.plist 中的 NSAppTransportSecurity 对 iOS 9.

起到了作用