项目里的倒计时进入后台,app会处于挂起状态,线程上的倒计时没办法继续运行。网上搜了几种方法,一种是"App plays audio or streams audio/video using AirPlay"这三种类型的项目,审核能通过的话,计时器是可以在后台进行倒计时的,但是我们的项目不是,第二种就是在
- (void)applicationDidEnterBackground:(UIApplication *)application
监听进入后台的时间
在
- (void)applicationWillEnterForeground:(UIApplication *)application
监听进去前台的时间,判断两个的时间差
第三种是,显示到期时间,通过判断进入的时间
-(void)openCountdown
{
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); // 每秒执行一次
NSTimeInterval seconds = 60.f;
NSDate *endTime = [NSDate dateWithTimeIntervalSinceNow:seconds]; // 最后期限
dispatch_source_set_event_handler(_timer, ^{
int interval = [endTime timeIntervalSinceNow];
if (interval > 0) { // 更新倒计时
NSString *timeStr = [NSString stringWithFormat:@"%d秒后重发", interval];
dispatch_async(dispatch_get_main_queue(), ^{
self.codeBtn.enabled = NO;
[self.codeBtn setTitle:timeStr forState:UIControlStateNormal];
});
} else { // 倒计时结束,关闭
dispatch_source_cancel(_timer);
dispatch_async(dispatch_get_main_queue(), ^{
self.codeBtn.enabled = YES;
[self.codeBtn setTitle:@"再次验证码" forState:UIControlStateNormal];
});
}
});
dispatch_resume(_timer);
}