我创建了一个循环,该循环在代码继续运行之前等待用户填写警报中的框时运行。我在其他地方使用了相同的循环,并且效果很好。
然而,在这里,它只在第一次被调用时循环一次,随后创建另一个警报并再次被调用。
它第二次运行,直到用户按应有的方式完成输入他们的详细信息。
//Method waiting for users credentials
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
{
NSLog(@"got auth challange");
_didChallenge = YES;
// Ask user for their credentials
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Login" message:@"Please enter username and password:" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
[alertView setTag:1];
alertView.alertViewStyle = UIAlertViewStyleLoginAndPasswordInput;
[alertView show];
[self performSelectorOnMainThread:@selector(WaitForCredentialDialog) withObject:nil waitUntilDone:YES];
//... Code to deal with credentials is here.
}
//Here dialogResult is a variable which will make while loop run until its value is -1 and reset its value to 1 or 0 when AlertView's Button is clicked
- (void) WaitForCredentialDialog{
NSDate* LoopUntil;
LoopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1];
while ((dialogResult==-1) && ([[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode beforeDate:LoopUntil]))
{
LoopUntil = [NSDate dateWithTimeIntervalSinceNow:0.1];
}
}
最佳答案
你不应该为此使用循环!使用 UITextFieldDelegate
获取有关用户键入内容的事件。
例子
要检测文本字段中的变化,请使用:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
或者 UIAlertViewDelegate
的:
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
当首次显示警报 View 时以及每次用户在其中一个文本字段中键入字符时都会调用此方法,这使得在接受用户值之前执行基本输入验证变得非常容易。
来源:
关于ios - 循环在第一次被调用时只运行一次,第二次无限次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25061522/