我有以下代码(swift实现):
I have the following code (swift implementation):
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中我有错误:
It works perfectly in iOS 8.x, but does not work iOS 7.x In iOS 7.x I have error:
NSURLConnection / CFURLConnection HTTP加载失败(kCFStreamError) DomainSSL,-9813)
任何想法? 谢谢!!!
Any idea? thank you!!!
推荐答案两个连接:canAuthenticateAgainstProtectionSpace:和连接:didReceiveAuthenticationChallenge:无论如何都在iOS 8中被弃用,所以你应该使用其他方法。
Both connection:canAuthenticateAgainstProtectionSpace: and connection:didReceiveAuthenticationChallenge: are deprecated in iOS 8 anyway so you should use other methods.
我在项目中使用的是委托方法NSURLSessionDelegate。遵守该协议然后添加此方法:
What I am using in my projects is a delegate method of NSURLSessionDelegate. Adhere to that protocol then add this method:
func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void) { completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)) }然后,当您使用初始化NSURLSession并将委托设置为self时。例如:
Then, when you use initialize NSURLSession with delegate set to self. For example:
var session = NSURLSession(configuration: configuration, delegate: self, delegateQueue:NSOperationQueue.mainQueue())然后使用该会话实例调用dataTaskWithRequest方法:
Then use that session instance to call dataTaskWithRequest method on:
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()完成工作示例可以在此处找到。
Complete working example can be found here.
出于安全原因,如果您使用自签名证书,我建议您还实施公钥固定( https:// gist .github / edwardmp / df8517aa9f1752e73353 )
For security reasons, if you use a self-signed certificate I recommend also implementing public key pinning (gist.github/edwardmp/df8517aa9f1752e73353)
更多推荐
如何使用iOS 7的NSURLSession接受自签名SSL证书
发布评论