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

Car*_*oso 15 ssl https self-signed ios swift

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

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)

}
Run Code Online (Sandbox Code Playgroud)

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

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

任何的想法?谢谢!!!

edw*_*dmp 23

双方connection:canAuthenticateAgainstProtectionSpace:connection:didReceiveAuthenticationChallenge:在iOS 8的弃用反正所以你应该使用其他方法.

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

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

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

var session = NSURLSession(configuration: configuration, delegate: self, delegateQueue:NSOperationQueue.mainQueue())
Run Code Online (Sandbox Code Playgroud)

然后使用该会话实例调用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()
Run Code Online (Sandbox Code Playgroud)

完整的工作示例可以在这里找到.

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