Swift NSURLSession和身份验证

时间:2014-07-08 10:52:05

标签: ios swift nsurlsession

我目前正在尝试将我的代码从使用NSURLConnection更改为NSURLSession。 令我困惑的一件事是身份验证。

我尝试连接的服务是基本身份验证的。

在我之前的代码中,我通过实现协议NSURLConnectionDataDelegate:

获得了以下方法
func connection(connection:NSURLConnection!, willSendRequestForAuthenticationChallenge challenge:NSURLAuthenticationChallenge!) {
   if challenge.previousFailureCount > 1 {

   } else {
      let creds = NSURLCredential(user: usernameTextField.text, password: passwordTextField.text, persistence: NSURLCredentialPersistence.None)
      challenge.sender.useCredential(creds, forAuthenticationChallenge: challenge)
   }
}

现在我被卡住了。

  • 我是否必须实施NSURLSessionDelegate.didReceiveChallenge?
  • 如果是,我该如何处理完成处理程序?
  • 在Apple Developer Reference中,我在didReceiveChallenge

    下找到了以下行
      

    如果你没有实现这个方法,那么会话就会调用它的委托的URLSession:task:didReceiveChallenge:completionHandler:method。

  • 这是什么意思?

1 个答案:

答案 0 :(得分:8)

是的,

如果您没有实现NSURLSessionDelegate.didReceiveChallenge方法,会话将调用其委托的URLSession:task:didReceiveChallenge:completionHandler:method。

更好地实施两者

func URLSession(session: NSURLSession!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {

    if challenge.protectionSpace.authenticationMethod.compare(NSURLAuthenticationMethodServerTrust) == 0 {
        if challenge.protectionSpace.host.compare("HOST_NAME") == 0 {
            completionHandler(.UseCredential, NSURLCredential(forTrust: challenge.protectionSpace.serverTrust))
        }

    } else if challenge.protectionSpace.authenticationMethod.compare(NSURLAuthenticationMethodHTTPBasic) == 0 {
        if challenge.previousFailureCount > 0 {
            println("Alert Please check the credential")
            completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil)
        } else {
            var credential = NSURLCredential(user:"username", password:"password", persistence: .ForSession)
            completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential,credential)
        }
    }

}

func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!){

    println("task-didReceiveChallenge")

    if challenge.previousFailureCount > 0 {
        println("Alert Please check the credential")
        completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil)
    } else {
        var credential = NSURLCredential(user:"username", password:"password", persistence: .ForSession)
        completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential,credential)
    }


}