NSURLConnection此服务器的证书无效

时间:2015-04-25 18:37:26

标签: swift ssl nsurlconnection nsurlsession

最近,我一直尝试使用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)

1 个答案:

答案 0 :(得分:1)

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

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