gpt4 book ai didi

ios - 如何使用 iOS 7 的 NSURLSession 接受自签名 SSL 证书

转载 作者:IT王子 更新时间:2023-10-29 05:19:00 25 4
gpt4 key购买 nike

我有以下代码(快速实现):

func connection(connection: NSURLConnection, canAuthenticateAgainstProtectionSpace protectionSpace: NSURLProtectionSpace) -> Bool
{
return protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust
}

func connection(connection: NSURLConnection, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge)
{
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust
{

if challenge.protectionSpace.host == "myDomain"
{
let credentials = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
challenge.sender.useCredential(credentials, forAuthenticationChallenge: challenge)
}
}

challenge.sender.continueWithoutCredentialForAuthenticationChallenge(challenge)

}

它在 iOS 8.x 中完美运行,但不适用于 iOS 7.x在 iOS 7.x 中我有错误:

NSURLConnection/CFURLConnection HTTP 加载失败(kCFStreamErrorDomainSSL,-9813)

有什么想法吗?谢谢你!!!

最佳答案

无论如何,connection:canAuthenticateAgainstProtectionSpace:connection:didReceiveAuthenticationChallenge: 在 iOS 8 中已被弃用,因此您应该使用其他方法。

我在项目中使用的是 NSURLSessionDelegate 的委托(delegate)方法。遵守该协议(protocol),然后添加此方法:

func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) {
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust: challenge.protectionSpace.serverTrust))
}

然后,当您使用初始化 NSURLSession 并将委托(delegate)设置为 self 时。例如:

var session = NSURLSession(configuration: configuration, delegate: self, delegateQueue:NSOperationQueue.mainQueue())

然后使用该 session 实例调用 dataTaskWithRequest 方法:

var task = session.dataTaskWithRequest(request){
(data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if error != nil {
callback("", error.localizedDescription)
} else {
var result = NSString(data: data, encoding:
NSASCIIStringEncoding)!
}
}
task.resume()

可以找到完整的工作示例 here .

出于安全原因,如果您使用自签名证书,我建议还实现公钥固定 (https://gist.github.com/edwardmp/df8517aa9f1752e73353)

关于ios - 如何使用 iOS 7 的 NSURLSession 接受自签名 SSL 证书,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30739149/

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