0

我正在编写一个询问用户名和密码的警报视图,但是,我想在从传入的 NSURLAuthenticationChallenge* 中使用这些凭据

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

有什么方法可以调用 UIAlertview 并将挑战变量临时保存在其中,以便以后在调用 UIAlertView 的委托方法时可以使用它?使用属性或实例变量似乎不优雅。

这是我的代码:

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
{
    NSLog(@"got authorization challange");

    if ([challenge previousFailureCount] == 0) {

        UIAlertView * loginAlert = [[UIAlertView alloc] initWithTitle:@"Login" message:@"Enter your Username and Password" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Sign In", nil];
        loginAlert.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
        [loginAlert show];
    } else {
        [[challenge sender] cancelAuthenticationChallenge:challenge];
        [[[UIAlertView alloc] initWithTitle:@"Invalid username/PW" message:@"Please try again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil] show];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if([alertView.title isEqualToString:@"Login"] &&
                        buttonIndex == 1)
    {
    /*want to use the challenge variable here to log in the user over the secure connection*/
        [[challenge sender] useCredential:[NSURLCredential credentialWithUser:[alertView textFieldAtIndex:0].text password:[alertView textFieldAtIndex:1].text persistence:NSURLCredentialPersistencePermanent] forAuthenticationChallenge:challenge];
    }
}
4

1 回答 1

1

实例变量 (ivars) 以及属性的扩展的目的是维护对象状态。

跟踪 ivar 中的挑战变量是非常合适的。该类UIAlertView不支持关联任意数据的方法,因此使用 ivar 就可以了。

您可以使用 Objective-C 的关联对象,但在这种情况下,几乎没有理由不使用 ivar 来维护这种状态。

于 2013-08-05T21:15:41.820 回答