NSURLConnection忽略SSL证书?

时间:2016-01-22 18:11:07

标签: swift ssl nsurlconnection

我知道这个问题经常被问到,但我已经实现了答案中找到的解决方案,而且我没有运气。我不是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。我试图忽略证书错误,但我仍然得到"发生SSL错误并且无法与服务器建立安全连接"

我的理解是

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

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

谢谢!

1 个答案:

答案 0 :(得分:0)

正如Breek建议的那样,info.plist中的NSAppTransportSecurity为iOS 9做了诀窍。