APP商城需要倒计时功能,不建议使用定时器,因为定时器会有误差问题,推荐使用GCD
首先声明一个timer
{
dispatch_source_t _time;
}
// 倒计时时间显示标签
@property (nonatomic, strong) UILabel *timeLabel;
// 设置文字颜色
UILabel *timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, [UIScreen mainScreen].bounds.size.width - 50 * 2, 80)]; timeLabel.textColor = [UIColor redColor]; timeLabel.numberOfLines = 0;
[self.view addSubview:timeLabel];
self.timeLabel = timeLabel;
[self activeCountDownAction];
//具体倒计时操作
- (void)activeCountDownAction{
NSString *deadlineStr = @"2018-08-22 12:00:00"; //创建一个结束时间
NSString*now = [self getCurrentTimeyyyymmdd];//获取当前时间
NSIntegersencoddsCountDown = [selfgetDateDifferenceWithNowDateStr:nowdeadlineStr:deadlineStr];//时间比较
__weak typeof (self) weakSelf = self;
if(_time==nil) {
__blockNSIntegertimeout = sencoddsCountDown;// 倒计时时间
if(timeout!=0) {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
_time=dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0,0, queue);
dispatch_source_set_timer(_time, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0); //每秒执行
dispatch_source_set_event_handler(_time, ^{
if(timeout <=0){// 当倒计时结束时做需要的操作: 关闭 活动到期不能提交
dispatch_source_cancel(_time);
_time=nil;
dispatch_async(dispatch_get_main_queue(), ^{
weakSelf.timeLabel.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.timeLabel.text= strTime;
}else{
weakSelf.timeLabel.text= [NSStringstringWithFormat:@"使用GCD来实现活动倒计时 %ld天 %02ld : %02ld : %02ld", days, hours, minute, second];
}
});
timeout--;// 递减 倒计时-1(总时间以秒来计算)
}
});
dispatch_resume(_time);
}
}
}
//获取本地时间
- (NSString*)getCurrentTimeyyyymmdd {
NSDate *now = [NSDate date];
NSDateFormatter *formatDay = [[NSDateFormatter alloc] init];
formatDay.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSString*dayStr = [formatDaystringFromDate:now];
returndayStr;
}
//时间比较
- (NSInteger)getDateDifferenceWithNowDateStr:(NSString*)nowDateStr deadlineStr:(NSString*)deadlineStr {
NSIntegertimeDifference =0;
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formattersetDateFormat:@"yy-MM-dd HH:mm:ss"];
NSDate*nowDate = [formatterdateFromString:nowDateStr];
NSDate*deadline = [formatterdateFromString:deadlineStr];
NSTimeInterval oldTime = [nowDate timeIntervalSince1970];
NSTimeInterval newTime = [deadline timeIntervalSince1970];
timeDifference = newTime - oldTime;
returntimeDifference;
}