Two Ways to Realize Countdown in ios
- 2021-10-24 23:58:53
- OfStack
Method 1: Use NSTimer to implement
The scheduledTimerWithTimeInterval method of NSTimer is mainly used to execute the timeFireMethod function once every 1 second, and timeFireMethod carries out some operations of countdown. When it is completed, timer is given to invalidate and ok is dropped. The code is as follows:
secondsCountDown = 60;//60 Seconds countdown
countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
-(void)timeFireMethod{
secondsCountDown--;
if(secondsCountDown==0){
[countDownTimer invalidate];
}
}
Method 2: Use GCD to implement
The code is as follows:
__block int timeout=300; // Countdown time
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); // Execute per second
dispatch_source_set_event_handler(_timer, ^{
if(timeout<=0){ // End of countdown, close
dispatch_source_cancel(_timer);
dispatch_release(_timer);
dispatch_async(dispatch_get_main_queue(), ^{
// Set the button display of the interface Set according to your own needs
. . . . . . . .
});
}else{
int minutes = timeout / 60;
int seconds = timeout % 60;
NSString *strTime = [NSString stringWithFormat:@"%d Points %.2d Retrieve the verification code after seconds ",minutes, seconds];
dispatch_async(dispatch_get_main_queue(), ^{
// Set the button display of the interface Set according to your own needs
. . . . . . . .
});
timeout--;
}
});
dispatch_resume(_timer);
The above is the site to introduce the ios countdown to you two ways, this site will reply to you in time. Thank you very much for your support to this site!