4

I am using the below code for authentication of the user with the remote server.If I am giving correct username and password, there is no issue because authentication is happening and I am getting the response from server.

But when I am giving wrong credentials,this method is called in recursive manner, so I am not able to break this.

Please help me, how to break this so that I should be able to show the authentication failed alert message.

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{

    NSURLCredential *credential = [NSURLCredential credentialWithUser:@"username"
                                                             password:@"password"
                                                          persistence:NSURLCredentialPersistenceForSession];
    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];    
}

2 Answers2

5

You need to check the error count and cancel the authentication challenge appropriately:

if ([challenge previousFailureCount]) {
    [[challenge sender] cancelAuthenticationChallenge:challenge];
} else {
    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
Mike Weller
  • 45,401
  • 15
  • 131
  • 151
4

Try this.

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
        {

        if ([challenge previousFailureCount] > 0) {
                // do something may be alert message
            } 
        else
        {

            NSURLCredential *credential = [NSURLCredential credentialWithUser:@"username"
                                                                     password:@"password"
                                                                  persistence:NSURLCredentialPersistenceForSession];
            [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; 
        }

}
User97693321
  • 3,336
  • 7
  • 45
  • 69