简体   繁体   中英

Loop runs only once first time it's called, infinite second time

I've created a loop that runs while waiting for a user to fill out boxes in an alert before the code moves on. I use the same loops elsewhere and it works perfectly.

Here however, it only loops once the first time it's called, subsequently creating another alert and getting called again.

The second time it runs until the user has finished entering their details as it should.

//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];
    }
}

You should not use loops for that! Use the UITextFieldDelegate to get events about what user typed.

Example

To detect changes in the text field use:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

Or UIAlertViewDelegate 's:

- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView

This method is called both when the alert view is first displayed and also each time the user types a character into one of the text fields, making it very easy to perform basic input validation prior to accepting a user's value.

Source:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM