There are two solutions to solve the problem of timer switching between front and background and inaccurate display of countdown stop. 1. Accurate and timely solution: Create an NSTimer timer to monitor the time of front and background notifications and global variable records. Timer open page or component monitoring into the background notice, receive the notice to record the current time, when received into the foreground notice to calculate the current time and record the time difference, with the countdown time minus the time difference on the remaining time, immediately display the countdown time. It's timely and accurate. Users cannot change the system time. Of course, the time difference can be calculated by monitoring the application to enter the background and the server time, and then corrected. This perfect solution requires the cooperation of the background, which can not be handled by just relying on the app. 2. Solution to the problem of delayed refreshing when switching to the background: Start the thread to record the time. -(void)startTimer{ int seconds = 1000; 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_TIME_NOW, 100.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC); NSDate *endTime = [NSDate dateWithTimeIntervalSinceNow:seconds]; dispatch_source_set_event_handler(timer, ^{ int interval = [endTime timeIntervalSinceNow]; if (interval <= 0) { dispatch_source_cancel(timer); dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"0"); }); } else { dispatch_async(dispatch_get_main_queue(), ^{ NSLog(@"%d", interval); }); }}); dispatch_resume(timer); } NSDate *endTime = [NSDate dateWithTimeIntervalSinceNow:seconds]; 1, is to record the time when the timer starts plus the time of the timer (termination time). int interval = [endTime timeIntervalSinceNow]; 1, is to calculate the time difference between the end time and the present time, the unit is: second. This is the timing interval to the update timing interval. There is, of course, a significant problem with this scheme. When the application switches to the background, and then to the foreground, the timer calls back at intervals of 0 to 1. If the timing interval is large, you will still display the previous time when the application is switched to the foreground, and it will take a long time for the error time to be updated. This is the problem of its untimely existence. Of course, its advantages are also obvious: simple code, no need to accept notifications and life global variables to record time, when the timing interval is very small, this delay is very small, the real-time requirements of the scenario is not too high recommended to use this method. Of course, it does not solve the problem of users changing system time alone.Copy the code