在日常一些项目中,常常用到定时器(一些活动,营销等等),在这里可以设置一下定时器:
.h文件:
@interface ViewController ()
@property (nonatomic, strong) dispatch_source_t timer; // 倒计时
@end
.m文件:
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 计算结束时间 - 现在时间
NSInteger timeInterval = (market_end_time - market_now_time) / 1000;
[self secondsCountDown:timeInterval]; // 单位:秒
}
#pragma mark 25.倒计时 (天 时 分 秒)
- (void)secondsCountDown:(NSInteger)seconds {
__weak __typeof(self) weakSelf = self;
if (_timer == nil) {
__block NSInteger timeout = seconds; // 倒计时时间
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(weakSelf.timer);
weakSelf.timer = nil;
dispatch_async(dispatch_get_main_queue(), ^{
weakSelf.limitedTimeHotView.timeLabel.text = @"当前活动已结束";
});
} else { // 倒计时重新计算 时/分/秒
NSInteger days = (int)(timeout/(3600*24));
NSInteger hours = (int)((timeout-days*24*3600)/3600);
NSInteger minute = (int)(timeout-days*24*3600-hours*3600)/60;
NSInteger second = timeout - days*24*3600 - hours*3600 - minute*60;
NSString *strTime = [NSString stringWithFormat:@"%ld时%ld分%ld", hours, minute, second];
dispatch_async(dispatch_get_main_queue(), ^{
if (days == 0) {
weakSelf.limitedTimeHotView.timeLabel.text = strTime;
} else {
weakSelf.limitedTimeHotView.timeLabel.text = [NSString stringWithFormat:@"%ld天%ld时%ld分%ld", days, hours, minute, second];
}
});
timeout--; // 递减 倒计时-1(总时间以秒来计算)
}
});
dispatch_resume(_timer);
}
}
}
@end
网友评论