Method 1: Use NSTimer to implement
The main use is the scheduledTimerWithTimeInterval method of NSTimer to execute the timeFireMethod function every 1 second. The timeFireMethod performs some countdown operations. When the time is completed, it will be OK to invalidate the timer. 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 it
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 every second dispatch_source_set_event_handler(_timer, ^{ if(timeout<=0){ //Countdown ends, close dispatch_source_cancel(_timer); dispatch_release(_timer); dispatch_async(dispatch_get_main_queue(), ^{ //The button display of the setting interface is set according to your needs 。。。。。。。。 }); }else{ int minutes = timeout / 60; int seconds = timeout % 60; NSString *strTime = [NSString stringWithFormat:@"%d minute %. 2d seconds to re-get the verification code",minutes, seconds]; dispatch_async(dispatch_get_main_queue(), ^{ //The button display of the setting interface is set according to your needs。。。。。。。。 }); timeout--; } }); dispatch_resume(_timer);
The above are the two ways to implement the countdown of iOS that the editor introduced to you. The editor will reply to you in time. Thank you very much for your support for my website!