Oliver Koehler
Oliver Koehler

Reputation: 721

Swift NSURLSession and authentication

I am currently trying to change my code from using NSURLConnection to NSURLSession. One thing that is confusing me is authentication.

My service that I am trying to connect is basic authenticated.

In my former code I had the following method by implementing protocol 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)
   }
}

Now I am stuck.

Upvotes: 10

Views: 13935

Answers (1)

Loganathan
Loganathan

Reputation: 1777

Yes,

If you do not implement NSURLSessionDelegate.didReceiveChallenge method, the session calls its delegate’s URLSession:task:didReceiveChallenge:completionHandler: method instead.

Better to implement both

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


}

Upvotes: 9

Related Questions