NSURLConnectionDelegate

NSURLConnectionDelegate

我想在webservice调用中实现SSL。
但有如下错误:
NSURLConnection/CFURLConnection HTTP加载失败(kCFStreamErrorDomainSSL,-9813)
下面是我的代码

func checkNetworkConnection(callback: ((isConnected: Bool) -> Void)!)
{
    var checkNetworkURL: String = “TESTURL”
    var request = NSMutableURLRequest(URL: NSURL(string: checkNetworkURL)!)

    request.HTTPMethod = "POST"
    request.addValue("application/xml", forHTTPHeaderField: "Content-Type")
    request.addValue("application/xml", forHTTPHeaderField: "Accept")
    request.timeoutInterval = 20000.0

    var response: NSURLResponse?
    var error: NSError?
    var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)


        if error == nil{

            if data != nil{

                self.parser.getLoginResultDataDictionary(data!) {(dataDictionary) -> Void in
                    if let dataDict = dataDictionary[self.constants.defaultsKeys.RESPONSE_RESULT] as? Dictionary<String,String>
                    {
                        if let status: AnyObject  = dataDict[self.constants.defaultsKeys.RESPONSE_STATUS] {
                            if status as! String == self.constants.defaultsKeys.RESPONSE_SUCCESS {
                                callback(isConnected:  true)
                            }
                            else{
                                callback(isConnected:  false)
                            }
                        }
                        else{
                            callback(isConnected:  false)
                        }
                    }
                    else{
                        callback(isConnected:  false)
                    }
                }
            }
            else{
                callback(isConnected:  false)
            }
        }
        else{
            callback(isConnected:  false)
        }
    //}
     }

添加的方法
   public func connection(connection: NSURLConnection,  willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge)
{
    challenge.sender.useCredential(NSURLCredential(forTrust: challenge.protectionSpace.serverTrust), forAuthenticationChallenge: challenge)
    challenge.sender.continueWithoutCredentialForAuthenticationChallenge(challenge)
}

添加的委托如下
公共类NetworkUtil:NSObject,NSURLConnectionDelegate{
}
如何在上述代码中配置SSL?
谢谢,

最佳答案

据我所知,唯一的方法是实现NSURLConnectionDelegate方法:

func connection(connection: NSURLConnection, willSendRequestForAuthenticationChallenge challenge: NSURLAuthenticationChallenge)
{
    challenge.sender.useCredential(NSURLCredential(forTrust: challenge.protectionSpace.serverTrust), forAuthenticationChallenge: challenge)
    challenge.sender.continueWithoutCredentialForAuthenticationChallenge(challenge)
}

如果您的目标是较旧的版本,则需要canAuthenticateAgainstProtectionSpace方法,该方法自iOS8以来已被弃用。

08-04 10:31