2

我是iOS应用程序开发的新手。我需要访问从远程 XML 文件加载的不同 url,其中一些 url 需要 http 基本身份验证。

使用 NSURLCredential 进行身份验证,它可以正常工作。现在,我想要求用户输入他们的凭据。当连接失败时,我使用 setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput 可视化界面登录 UIAlertView。

此时,我使用 textFieldAtIndex: 0 和 1 验证用户输入的对应用户名和密码,但我可以将它们用于与 NSURLConnection 的新连接尝试。

有人能帮我吗?

这是我的代码:

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    if ([challenge previousFailureCount] == 0)
    {
        NSLog(@"received authentication challenge");

        NSURLCredential *newCredential;
        newCredential=[NSURLCredential credentialWithUser:@""
                                                 password:@""
                                              persistence:NSURLCredentialPersistenceForSession];


        NSLog(@"credential created");

        [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];

        NSLog(@"responded to authentication challenge");

    }
    else
    {
        NSLog(@"previous authentication failure");

        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Login"
                                                          message:@"Enter your username & password"
                                                         delegate:self
                                                cancelButtonTitle:@"Cancel"
                                                otherButtonTitles:@"Login", nil];

        [message setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];

        [message show];
    }
}

- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
    NSString *inputText = [[alertView textFieldAtIndex:0] text];
    if( [inputText length] >= 1 )
    {
        return YES;
    }
    else
    {
        return NO;
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
    if([title isEqualToString:@"Login"])
    {
        UITextField *username = [alertView textFieldAtIndex:0];
        UITextField *password = [alertView textFieldAtIndex:1];
        NSLog(@"Username: %@\npassword: %@", username.text, password.text);
        if ([username.text isEqualToString:@"myname"] && [password.text isEqualToString:@"1234"])
        NSLog(@"Success");
    }
    [xmlDataBuffer setLength:0];
}
4

0 回答 0