需求:
Cell中倒計時顯示兴猩,到期刷新接口箫措,超時數(shù)據(jù)消失垮卓。后端提供訂單生成時間戳createdTime傻工。
計算:
到期時間 = 訂單生成時間+后端訂單預(yù)留時間
剩余時間 = 到期時間 - 現(xiàn)在時間
剩余時間的年,月,日,時,分,秒都小于等于0時即為超時失效挑格。
工具使用:CountDown
//導(dǎo)入文件咙冗,鏈接文章末尾
#import "CountDown.h"
@property (nonatomic , strong) CountDown *countDown;
//輪詢初始化
self.countDown = [[CountDown alloc] init];
__weak __typeof(self) weakSelf= self;
[self.countDown countDownWithPER_SECBlock:^{
[weakSelf updateTimeInVisibleCells];
}];
//輪詢并對Cell進行賦值
- (void)updateTimeInVisibleCells{
NSArray *cells = self.tableView.visibleCells; //取出屏幕可見ceLl
for (OpenCardWriteCell *cell in cells) {
OpenCardFailedModel *model = self.dataArray[cell.tag];
[cell.readBtn setTitle:[self getNowTimeWithString:validateString(model.createdTime)] forState:UIControlStateNormal];
}
}
//計算時間差
- (NSString *)getNowTimeWithString:(NSString *)aTimeString{
NSDate *nowDate = [NSDate dateWithTimeIntervalSinceNow:0];//獲取當前時間0秒后的時間
//30分鐘后
NSString *startStr = validateString(aTimeString);
NSTimeInterval startTime = [startStr doubleValue]*0.001+1800;
NSDate *detaildate = [NSDate dateWithTimeIntervalSince1970:startTime];
//對比得到差值
NSTimeInterval timeInterval = [detaildate timeIntervalSinceDate:nowDate];
int days = (int)(timeInterval/(3600*24));
int hours = (int)((timeInterval-days*24*3600)/3600);
int minutes = (int)(timeInterval-days*24*3600-hours*3600)/60;
int seconds = timeInterval-days*24*3600-hours*3600-minutes*60;
//以下按自己需要使用
NSString *dayStr;NSString *hoursStr;NSString *minutesStr;NSString *secondsStr;
dayStr = [NSString stringWithFormat:@"%d",days];
hoursStr = [NSString stringWithFormat:@"%d",hours];
if(minutes<10)
minutesStr = [NSString stringWithFormat:@"0%d",minutes];
else
minutesStr = [NSString stringWithFormat:@"%d",minutes];
if(seconds < 10)
secondsStr = [NSString stringWithFormat:@"0%d", seconds];
else
secondsStr = [NSString stringWithFormat:@"%d",seconds];
if (hours<=0&&minutes<=0&&seconds<=0) {
[self queryOrderDataMethod];
return @"已超時";
}
if (days) {
return [NSString stringWithFormat:@"剩余時間 %@天%@:%@:%@", dayStr,hoursStr, minutesStr,secondsStr];
} else if(hours){
return [NSString stringWithFormat:@"剩余時間 %@:%@:%@", hoursStr,minutesStr,secondsStr];
}else
return [NSString stringWithFormat:@"剩余時間 %@:%@", minutesStr,secondsStr];
}
//銷毀
- (void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
[_countDown destoryTimer];
}
感謝文明大佬的技術(shù)支持:CountDown
參考文章:
https://blog.csdn.net/minjing_lin/article/details/51783163
https://blog.csdn.net/m372897500/article/details/46443699
https://blog.csdn.net/bitcser/article/details/52240587