+ (void)countDownWithBtn:(UIButton *)btn{
__block NSInteger _surplusSecond = 59;
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_queue_t mainQueue = dispatch_get_main_queue();
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, globalQueue);
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0.0 * NSEC_PER_SEC);
dispatch_source_set_event_handler(timer, ^{
if (_surplusSecond <=0) {
dispatch_source_cancel(timer);
dispatch_async(mainQueue, ^{
btn.enabled = YES;
btn.titleLabel.text = @"获取验证码";
[btn setTitle:@"获取验证码" forState:UIControlStateNormal];
_surplusSecond = 59;
});
}else{
_surplusSecond--;
dispatch_async(mainQueue, ^{
NSString *btnInfo = [NSString stringWithFormat:@"%ldS", (long)(_surplusSecond + 1)];
btn.titleLabel.text = btnInfo;
[btn setTitle:btnInfo forState:UIControlStateNormal];
btn.enabled = NO;
});
}
});
dispatch_source_set_cancel_handler(timer, ^{ //计时器取消处理器;调用 dispatch_source_cancel 时执行
NSLog(@"Cancel Handler");
});
dispatch_resume(timer);
}
+ (void)countDownWithLabel:(QFAttributedLabel *)label andTimestamp:(NSString *)time {
__block NSInteger _surplusSecond = [time integerValue]/1000;
// __block NSInteger _surplusSecond = 3600;
dispatch_queue_t globalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_queue_t mainQueue = dispatch_get_main_queue();
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, globalQueue);
dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 60.0 * NSEC_PER_SEC, 0.0 * NSEC_PER_SEC);
dispatch_source_set_event_handler(timer, ^{
if (_surplusSecond <=0) {
dispatch_source_cancel(timer);
dispatch_async(mainQueue, ^{
[[NSNotificationCenter defaultCenter] postNotificationName:@"countDown" object:self userInfo:nil];
});
}else{
_surplusSecond = _surplusSecond-60;
dispatch_async(mainQueue, ^{
NSString *day = [NSString stringWithFormat:@"%ld", _surplusSecond/(3600*24)];
NSString *hour = [NSString stringWithFormat:@"%ld", _surplusSecond%(3600*24)/3600];
NSString *minu = [NSString stringWithFormat:@"%ld", _surplusSecond%(3600*24)%3600/60];
[label setText:[NSString stringWithFormat:@"%@天%@小时%@分",day, hour, minu] WithFont:[UIFont fontWithName:@"" size:12] AndColor:orangeColor];
[label setKeyWordTextArray:@[@"天", @"小时", @"分"] WithFont:[UIFont systemFontOfSize:10] AndColor:UIColorFromRGB(0x19191a)];
});
}
});
dispatch_source_set_cancel_handler(timer, ^{ //计时器取消处理器;调用 dispatch_source_cancel 时执行
NSLog(@"Cancel Handler");
});
dispatch_resume(timer);
}