Implementation of GCD countdown for ios development

       Today, a friend asked me that the iOS implementation of the timer switch to the background cannot be executed, and the countdown timer does not execute. So I searched for a lot of information. In the end practice solved the problem, I pasted the core code below:

   __block int timeout= 60 ; // 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_async(dispatch_get_main_queue(), ^{

               // The button display of the setting interface is set according to your own needs

            // [ _sendButton setTitle : @" Send verification code " forState : UIControlStateNormal ];

            //  _sendButton.userInteractionEnabled = YES;

                 });

              }else{

               int seconds = timeout % 60;

               NSString *strTime = [NSStringstringWithFormat:@"%.2d", seconds];

               dispatch_async(dispatch_get_main_queue(), ^{

            // The button display of the setting interface is set according to your own needs

              //[ _sendButton setTitle :[ NSString stringWithFormat : @" Resend (%@)" ,strTime] forState : UIControlStateNormal ];

               //_sendButton.userInteractionEnabled = NO;

                                

              });

               timeout--;

               }

               });

                dispatch_resume(_timer);

               }



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325525201&siteId=291194637
gcd