NSURLConnection 此服务器的证书无效

NSURLConnection The certificate for this server is invalid

最近我一直在尝试使用 NSURLSession.sharedSession().dataTaskWithRequest()

使用自签名 SSL 证书连接到我的测试服务器

现在我得到这个错误:

The certificate for this server is invalid. You might be connecting to a server that is pretending to be “...” which could put your confidential information at risk.

我一直在网上搜索如何解决它。 他们都建议使用其中之一:

func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace) -> Bool

func connection(connection: NSURLConnection, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge)

func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge)  

func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)

现在,当我 运行 我的应用程序时,我注意到只有

func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge) 

运行.

这是我的代码:

func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge)
{
    // Trusting and not trusting connection to host: Self-signed certificate
    challenge.sender.useCredential(NSURLCredential(forTrust: challenge.protectionSpace.serverTrust), forAuthenticationChallenge: challenge)
    challenge.sender.continueWithoutCredentialForAuthenticationChallenge(challenge)

    if(challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust)
    {
        let trust = challenge.protectionSpace.serverTrust
        let cred = NSURLCredential(forTrust: trust)

        challenge.sender.useCredential(cred, forAuthenticationChallenge: challenge)
    }
}

但我一直收到 NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)

啊哈!显然我之前有过 let urlConnection = NSURLConnection(request: request, delegate: self) 一点我没有注意到...

然后我改变了NSURLSession.sharedSession().dataTaskWithRequest()
let task = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: self, delegateQueue: NSOperationQueue.mainQueue()).dataTaskWithRequest(request) 并保留委托方法......做到了:)