根據(jù)時間數(shù)組和cell id數(shù)組 獲取每個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); //每秒執(zhí)行
dispatch_source_set_event_handler(_timer, ^{
if(timeout<=0){ //倒計時結(jié)束受葛,關(guān)閉
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;
}
鑒于真機測試會發(fā)生后臺timer不運行的情況,增加一個程序進入后臺通知,延長后臺任務(wù)執(zhí)行
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForegroundNotification) name:UIApplicationDidEnterBackgroundNotification object:nil];
- (void) appWillEnterForegroundNotification{
UIApplication* app = [UIApplication sharedApplication];
__block UIBackgroundTaskIdentifier bgTask;
//申請一個后臺執(zhí)行的任務(wù) 大概10分鐘 如果時間更長的話需要借助默認音頻等
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
if (bgTask != UIBackgroundTaskInvalid)
{
bgTask = UIBackgroundTaskInvalid;
}
});
}];
}
Demo地址 歡迎Star