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?
  • Если да, то как мне справиться с обработчиком завершения?
  • #P5# <блочная цитата> #P6#
  • Что это значит?


person Oliver Koehler    schedule 08.07.2014    source источник


Ответы (1)


Да,

Если вы не реализуете метод NSURLSessionDelegate.didReceiveChallenge, сеанс вместо этого вызывает метод URLSession:task:didReceiveChallenge:completionHandler: своего делегата.

Лучше реализовать оба

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)
    }


}
person Loganathan    schedule 17.07.2014