我知道这类问题已被问过很多次,但似乎有答案,但我无法让它发挥作用。
在我的环境中,生产环境是我唯一拥有有效 SSL 证书的地方。在我针对生产构建的 iOS 应用程序中使用 Alamofire 效果很好。我不想针对生产进行开发/测试,我们现在无法为任何其他环境获得有效的 SSL 证书。
我找到了 this因此,来自 Alamofire 开发人员的回答提出了一种解决此问题的方法,但它对我不起作用。当我针对非生产环境运行我的应用程序时,我看到的失败意味着它使用的是 NSURLConnection 而不是建议的解决方案所依赖的 NSURLSession。
NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
如果有人可以就此分享他们的解决方案(也许是要点?),我会很高兴。
最佳答案
我终于明白了。我引用的 SO 答案中有一个小但重要的错误。我提交了修改,但会在此处发布工作代码:
let manager = Alamofire.Manager.sharedInstance
manager.delegate.sessionDidReceiveChallenge = { session, challenge in
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
disposition = NSURLSessionAuthChallengeDisposition.UseCredential
credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
} else {
if challenge.previousFailureCount > 0 {
disposition = .CancelAuthenticationChallenge
} else {
credential = manager.session.configuration.URLCredentialStorage?.defaultCredentialForProtectionSpace(challenge.protectionSpace)
if credential != nil {
disposition = .UseCredential
}
}
}
return (disposition, credential)
}
问题是它没有使用 Alamofire.Manager
的单例实例。相反,它正在创建一个从未被 Alamofire 框架使用的全新实例。
关于swift - Alamofire SSL 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30671029/