根据时间数组和cell id数组 获取每个cell的倒计时时间 并在cell显示时赋值
- (void)getTimeStrWith:(NSArray *)timeStrArr and:(NSArray *)cellIdArr{
dispatch_queue_t queue = dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT);
for (int i = 0; i< timeStrArr.count; i++) {
__block int timeout=[timeStrArr[i] intValue]; //倒计时时间
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); //每秒执行
dispatch_source_set_event_handler(_timer, ^{
if(timeout<=0){ //倒计时结束,关闭
dispatch_source_cancel(_timer);
dispatch_async(dispatch_get_main_queue(), ^{
[_dataDic setObject:@"停止秒杀" forKey:cellIdArr[i]];
[_myTableView reloadData];
});
}else{
int minutes = timeout / 60;
int seconds = timeout % 60;
NSString *strTime = [NSString stringWithFormat:@"%d分%.2d秒后停止秒杀",minutes, seconds];
dispatch_async(dispatch_get_main_queue(), ^{
[_dataDic setObject:strTime forKey:cellIdArr[i]];
[_myTableView reloadData];
});
timeout--;
}
});
dispatch_resume(_timer);
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
JQTableViewCell *cell = [JQTableViewCell initWith:tableView];
cell.cellID = _cellidArr[indexPath.row];
cell.timeLineLabel.text = [_dataDic objectForKey:cell.cellID];
return cell;
}
鉴于真机测试会发生后台timer不运行的情况,增加一个程序进入后台通知,延长后台任务执行
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForegroundNotification) name:UIApplicationDidEnterBackgroundNotification object:nil];
- (void) appWillEnterForegroundNotification{
UIApplication* app = [UIApplication sharedApplication];
__block UIBackgroundTaskIdentifier bgTask;
//申请一个后台执行的任务 大概10分钟 如果时间更长的话需要借助默认音频等
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid)
{
bgTask = UIBackgroundTaskInvalid;
}
});
}];
}
Demo地址 欢迎Star
网友评论