认证挑战

时间:2012-06-28 17:32:23

标签: iphone ios authentication webview alertview

我尝试使用webview访问受保护的web文件夹。使用“硬编码”用户并传递它有效,但我的计划是弹出一个alertview进入用户并通过。这是代码的一部分:

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

NSLog(@"Need Authentication");

UIAlertView *webLogin = [[UIAlertView alloc] initWithTitle:@"Authentication" 
                                                   message:@"Enter User and Pass" 
                                                   delegate:self 
                                                   cancelButtonTitle:@"Cancel" 
                                                   otherButtonTitles:@"OK"
                                                   , nil];


webLogin.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
[webLogin show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

user = [[alertView textFieldAtIndex:0]text];
pass = [[alertView textFieldAtIndex:1]text];
NSLog(@"user is %@ and pass is %@",user,pass);

if (buttonIndex == [alertView cancelButtonIndex]) {

    [self dismissModalViewControllerAnimated:YES];
}
else if (buttonIndex != [alertView cancelButtonIndex]) {

    NSLog(@"OK Pressed");
    [self handleAuthentificationOKForChallenge:nil withUser:user password:pass];
}


}

- (void)handleAuthentificationOKForChallenge:(NSURLAuthenticationChallenge *)aChallenge     withUser:(NSString *)userName password:(NSString *)password {

NSURLCredential *credential = [[NSURLCredential alloc]
                               initWithUser:userName password:password
                               persistence:NSURLCredentialPersistenceForSession];
[[aChallenge sender] useCredential:credential forAuthenticationChallenge:aChallenge];

}

任何人都可以告诉我如何调用handleAuthenticationOKForChallenge 我对NSURLAuthenticationChallenge有点困惑....

1 个答案:

答案 0 :(得分:1)

首先,如果他们要比较同一个变量,你不应该一个接一个地使用两个if语句。您的第二个if语句应为else if语句。

您的handleAuthentificationOKForChallenge方法似乎想要接受NSURLAuthenticationChallenge的实例,但您目前只是传递nil

为什么不在头文件中声明NSURLAuthenticationChallenge的实例(让我们称之为myChallenge),在第一种方法中,使用challenge分配并初始化它。你也可以将它设置为等于挑战(如果你想先尝试这个,可能会有效),但你可能会在某些时候失去指针。 然后,您可以将第二种方法中的行更改为:

[self handleAuthentificationOKForChallenge:myChallenge withUser:user password:pass];

让我知道这是否有效......