NSURL 连接 此服务器的证书无效



最近我一直在尝试使用自签名SSL证书连接到我的测试服务器,使用NSURLSession.sharedSession().dataTaskWithRequest()

现在我收到此错误:

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) 并保留了委托方法...那做到了:)

相关内容

最新更新