Swift:如何使用自签名证书请求URL?

jla*_*law 6 ssl json swift

我正在打开一个SSL连接以在Swift中检索JSON,但我正在使用自签名证书对我自己的服务器进行测试.以下是网址请求的摘要:

var urlPath = "https://myhost.com/get_json"
var url: NSURL = NSURL(string: urlPath)
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)        
connection.start()
Run Code Online (Sandbox Code Playgroud)

但是,由于证书,它被拒绝(正确):

Opening connection to https://myhost.com/get_json
2014-06-05 09:37:02.543 AppName[44835:3182593] NSURLConnection/CFURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
Connection failed.The certificate for this server is invalid. You might be connecting to a server that is pretending to be “myhost.com” which could put your confidential information at risk.## Heading ##
Run Code Online (Sandbox Code Playgroud)

Eri*_*rik 5

您将需要以下其他方法NSURLConnectionDelegate:

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 == "www.myhost.com"
        {
            let credentials = NSURLCredential(forTrust: challenge!.protectionSpace.serverTrust)
            challenge!.sender.useCredential(credentials, forAuthenticationChallenge: challenge)
        }
    }

    challenge?.sender.continueWithoutCredentialForAuthenticationChallenge(challenge)
}
Run Code Online (Sandbox Code Playgroud)

注意:这仅在使用异步时才可用NSURLConnection.