gpt4 book ai didi

swift - NSURLConnection 此服务器的证书无效

转载 作者:太空宇宙 更新时间:2023-11-03 14:11:18 24 4
gpt4 key购买 nike

最近我一直在尝试使用 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(请求)
并保留委托(delegate)方法......做到了:)

关于swift - NSURLConnection 此服务器的证书无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29869115/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com