iOS5: willSendRequestForAuthenticationChallenge method is running recursive

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.

  • Determine orientation of photos in JavaScript?
  • iOS developer program certificate transfer
  • AVCaptureSession and background audio iOS 7
  • UIVisualEffectView renders differently on different devices
  • How do I retrieve a page number or page reference for an Outline destination in a PDF on iOS?
  • Cocoapod: Why Xcode build process try to find the library which has been already removed from my project
  • 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 Solutions Collect From Internet About “iOS5: willSendRequestForAuthenticationChallenge method is running recursive”

    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]; 
            }
    
    }
    

    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];
    }