Your first problem is that you are not initializing seconds anything, so it will initially be zero. This is why your warning says "null seconds". The next time the warning is displayed, the seconds will be set by your countDown method.
The second problem is that you are not actually updating the message property of your warning, so you just see the value of seconds when the warning was initially displayed.
Finally, you set mainInt to 20, and then subtract 1 every time the timer fires, so it will never reach 0, it will be 20,19,20,19,20,19 ...
The code below initializes mainInt in the IBAction method, so it does not reset to 20 every time ticks are ticked. It also updates the warning message property and rejects the warning when the timer reaches 0 (it actually does it 1 second after I think it's better to see 2..1 ... 0 ... logout, but you can change it)
@interface ViewController () { int mainInt; NSTimer *timer; UIAlertController *alertController; } - (NSString *)countDownString { return [NSString stringWithFormat:@"%i seconds", mainInt]; } - (void)countDown{ mainInt -= 1; if (mainInt < 0) { [timer invalidate]; [alertController dismissViewControllerAnimated:YES completion:^{ // Whatever you need to do to complete the logout }] } else { alertController.message=[self countDownString]; } } - (IBAction)logout:(id)sender { timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDown) userInfo:nil repeats:YES]; mainInt=20; alertController = [UIAlertController alertControllerWithTitle:nil message:[self countDownString] preferredStyle:UIAlertControllerStyleActionSheet]; UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", @"Cancel action") style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){ [timer invalidate]; NSLog(@"Cancel Log out"); }]; UIAlertAction *okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"log Out", @"Ok action") style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action){ [timer invalidate]; NSLog(@"Loged out"); //Log out code goes here //When time is up, log out automatically }]; [alertController addAction:okAction]; [alertController addAction:cancelAction]; [alertController setModalPresentationStyle:UIModalPresentationPopover]; [self presentViewController:alertController animated:YES completion:nil]; }
source share