解決了App進(jìn)入后臺暫停倒計(jì)時(shí)的問題
- (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); // 每秒執(zhí)行一次
NSTimeInterval seconds = 30.f;
NSDate *endTime = [NSDate dateWithTimeIntervalSinceNow:seconds]; // 最后期限
dispatch_source_set_event_handler(_timer, ^{
int interval = [endTime timeIntervalSinceNow];
if (interval > 0) { // 更新倒計(jì)時(shí)
NSString *timeStr = [NSString stringWithFormat:@"剩余(%d)秒", interval];
dispatch_async(dispatch_get_main_queue(), ^{
self.sendSecurityCodeBtn.enabled = NO;
[self.sendSecurityCodeBtn setTitle:timeStr forState:UIControlStateNormal];
});
} else { // 倒計(jì)時(shí)結(jié)束签夭,關(guān)閉
dispatch_source_cancel(_timer);
dispatch_async(dispatch_get_main_queue(), ^{
self.sendSecurityCodeBtn.enabled = YES;
[self.sendSecurityCodeBtn setTitle:@"獲取驗(yàn)證碼" forState:UIControlStateNormal];
});
}
});
dispatch_resume(_timer);
}