首先声明一个全局的 dispatch_source_t _timer;
// 1.计算截止时间与当前时间差值
// 倒计时的时间 测试数据
NSString *deadlineStr = @"2020-08-19 12:00:00";
// 当前时间的时间戳
NSString*nowStr = [YJCommontClassgetCurrentTime];
// 计算时间差值
NSIntegersecondsCountDown = [selfgetDateDifferenceWithNowDateStr:nowStrdeadlineStr:deadlineStr];
// 2.使用GCD来实现倒计时 用GCD这个写有一个好处,跳页不会清零 跳页清零会出现倒计时错误的
__weak __typeof(self) weakSelf = self;
if(_timer==nil) {
__blockNSIntegertimeout = secondsCountDown;// 倒计时时间
if(timeout!=0) {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
_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); //每秒执行
dispatch_source_set_event_handler(_timer, ^{
if(timeout <=0){// 当倒计时结束时做需要的操作: 关闭 活动到期不能提交
dispatch_source_cancel(_timer);
_timer=nil;
dispatch_async(dispatch_get_main_queue(), ^{
weakSelf.createTime.text=@"当前活动已结束";
});
}else{// 倒计时重新计算 时/分/秒
NSIntegerdays = (int)(timeout/(3600*24));
NSIntegerhours = (int)((timeout-days*24*3600)/3600);
NSIntegerminute = (int)(timeout-days*24*3600-hours*3600)/60;
NSIntegersecond = timeout - days*24*3600- hours*3600- minute*60;
NSString*strTime = [NSStringstringWithFormat:@"活动倒计时 %02ld : %02ld : %02ld", hours, minute, second];
dispatch_async(dispatch_get_main_queue(), ^{
if(days ==0) {
weakSelf.createTime.text= strTime;
}else{
weakSelf.createTime.text= [NSStringstringWithFormat:@"使用GCD来实现活动倒计时 %ld天 %02ld : %02ld : %02ld", days, hours, minute, second];
}
});
timeout--;// 递减 倒计时-1(总时间以秒来计算)
}
});
dispatch_resume(_timer);
}
}
网友评论