Search code examples
iosxcodensurlconnectionnsurlrequest

UIWebview didReceiveAuthenticationChallenge


I'm using webview to load a web site. and I managed to run the apps. But my problem Is that I can't load the web site if I pass a wrong password, it only show a white screen.

If I pass the correct username/password, it will load the web site. is there a way to handle my authenticate username/password is correct or wrong?

I'm using this code.

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodNTLM])
{
    NSURLCredential *credentail = [NSURLCredential
                                   credentialWithUser:@"username" 
                                   password:@"Password"
                                   persistence:NSURLCredentialPersistenceForSession];
    [[challenge sender] useCredential:credentail forAuthenticationChallenge:challenge];
}}

The correct username and password are included in the code above. If I change the username into "user" or password into "pass", I can't load the web site. How can I catch the authentication error?

thanks.


Solution

  • i just found it. just need to add 1 more validation. [[challenge previousFailureCount] == 0. here is the code.

    - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    //receive a authenticate and challenge with the user credential
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodNTLM] &&
        [challenge previousFailureCount] == 0)
    {
        NSURLCredential *credentail = [NSURLCredential 
                                       credentialWithUser:@"username" 
                                       password:@"password"
                                       persistence:NSURLCredentialPersistenceForSession];
    
    
        [[challenge sender] useCredential:credentail forAuthenticationChallenge:challenge];
    }
    else 
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error Message" message:@"Invalid credentails" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
    }
    

    thanks. :)