
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)
任何想法?
谢谢!!!
我在项目中使用的是NSURLSessionDelegate的委托方法.坚持那个协议,然后添加这个方法:
func URLSession(session: NSURLSession,dIDReceiveChallenge challenge: NSURLAuthenticationChallenge,completionHandler: (NSURLSessionAuthChallengedisposition,NSURLCredential!) -> VoID) { completionHandler(NSURLSessionAuthChallengedisposition.UseCredential,NSURLCredential(forTrust: challenge.protectionSpace.serverTrust))} 然后,当您使用委派设置为self时,初始化NSURLSession.例如:
var session = NSURLSession(configuration: configuration,delegate: self,delegateQueue:NSOperationQueue.mainQueue())
然后使用该会话实例调用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 7的NSURLSession接受自签名SSL证书全部内容,希望文章能够帮你解决如何使用iOS 7的NSURLSession接受自签名SSL证书所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)