項(xiàng)目中有一個(gè)支付時(shí)間倒計(jì)時(shí)的需求,類似于美團(tuán)外賣的支付倒計(jì)時(shí)窘问。我也從網(wǎng)上搜到一些實(shí)現(xiàn)的方法烛芬,以下是我總結(jié)的一些隧期。
倒計(jì)時(shí)有三種實(shí)現(xiàn)的方法:
- 通過定時(shí)器NSTimer,屬于比較簡(jiǎn)單的寫法赘娄;
- 通過GCD仆潮;
第一種:
_seconds = 60;//60秒倒計(jì)時(shí)
_countDownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];
-(void)timeFireMethod{
_seconds--;
if(_seconds ==0){
[_countDownTimer invalidate];
}
}
第二種:
__block int timeout=60; //倒計(jì)時(shí)時(shí)間
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
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){ //倒計(jì)時(shí)結(jié)束,關(guān)閉
dispatch_source_cancel(_timer);
dispatch_release(_timer);
dispatch_async(dispatch_get_main_queue(), ^{
//設(shè)置界面的按鈕顯示 根據(jù)自己需求設(shè)置
遣臼。性置。。揍堰。鹏浅。。屏歹。隐砸。
});
}else{
int minutes = timeout / 60;
int seconds = timeout % 60;
NSString *strTime = [NSString stringWithFormat:@"%d分%.2d秒后重新獲取驗(yàn)證碼",minutes, seconds];
dispatch_async(dispatch_get_main_queue(), ^{
//設(shè)置界面的按鈕顯示 根據(jù)自己需求設(shè)置
。蝙眶。季希。。幽纷。式塌。。友浸。
});
timeout--;
}
});
dispatch_resume(_timer);
我的項(xiàng)目中運(yùn)用的是通過GCD來實(shí)現(xiàn)倒計(jì)時(shí)峰尝。原理就是:使用GCD創(chuàng)建定時(shí)器并設(shè)置定時(shí)器的間隔時(shí)間為1秒,然后在定時(shí)器的響應(yīng)事件方法中將倒計(jì)時(shí)的總時(shí)間依次減1收恢,由于定時(shí)器響應(yīng)事件是在block中武学,所有控件的修改需要使用__weak來修飾,避免循環(huán)調(diào)用派诬。以下是我的代碼:
在HCCountdown.h文件中
/**
* 用時(shí)間戳倒計(jì)時(shí)
* starTimeStamp 開始的時(shí)間戳
* finishTimeStamp 結(jié)束的時(shí)間戳
* day 倒計(jì)時(shí)開始后的剩余的天數(shù)
* hour 倒計(jì)時(shí)開始后的剩余的小時(shí)
* minute 倒計(jì)時(shí)開始后的剩余的分鐘
* second 倒計(jì)時(shí)開始后的剩余的秒數(shù)
*/
-(void)countDownWithStratTimeStamp:(long)starTimeStamp finishTimeStamp:(long)finishTimeStamp completeBlock:(void (^)(NSInteger day,NSInteger hour,NSInteger minute,NSInteger second))completeBlock;
在HCCountdown.m文件中
#import "HCCountdown.h"
@interface HCCountdown ()
@property(nonatomic,retain) dispatch_source_t timer;
@property(nonatomic,retain) NSDateFormatter *dateFormatter;
@end
-(void)countDownWithStratTimeStamp:(long)starTimeStamp finishTimeStamp:(long)finishTimeStamp completeBlock:(void (^)(NSInteger day,NSInteger hour,NSInteger minute,NSInteger second))completeBlock{
if (_timer==nil) {
NSDate *finishDate = [self dateWithLong:finishTimeStamp]; //時(shí)間戳轉(zhuǎn)時(shí)間
NSDate *startDate = [self dateWithLong:starTimeStamp];
NSTimeInterval timeInterval =[finishDate timeIntervalSinceDate:startDate]; //獲取兩個(gè)時(shí)間的間隔時(shí)間段
__block int timeout = timeInterval; //倒計(jì)時(shí)時(shí)間
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); //每秒執(zhí)行
dispatch_source_set_event_handler(_timer, ^{
if(timeout<=0){ //倒計(jì)時(shí)結(jié)束劳淆,關(guān)閉
dispatch_source_cancel(_timer);
_timer = nil;
dispatch_async(dispatch_get_main_queue(), ^{
completeBlock(0,0,0,0);
});
}else{
int days = (int)(timeout/(3600*24));
int hours = (int)((timeout-days*24*3600)/3600);
int minute = (int)(timeout-days*24*3600-hours*3600)/60;
int second = timeout-days*24*3600-hours*3600-minute*60;
dispatch_async(dispatch_get_main_queue(), ^{
completeBlock(days,hours,minute,second);
});
timeout--;
}
});
dispatch_resume(_timer);
}
}
}
在ViewController.m 文件中
@property (nonatomic, strong) HCCountdown *countdown;
- 首先獲取開始時(shí)間的時(shí)間戳
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// ----------設(shè)置你想要的格式,hh與HH的區(qū)別:分別表示12小時(shí)制,24小時(shí)制
[formatter setDateFormat:@"YYYY年MM月dd日HH:mm:ss"];
//現(xiàn)在時(shí)間,你可以輸出來看下是什么格式
NSDate *datenow = [NSDate date];
//----------將nsdate按formatter格式轉(zhuǎn)成NSString
NSString *currentTimeString_1 = [formatter stringFromDate:datenow];
NSDate *applyTimeString_1 = [formatter dateFromString:currentTimeString_1];
_nowTimeSp = (long)[applyTimeString_1 timeIntervalSince1970];
- 獲取5分鐘后的時(shí)間(也就是倒計(jì)時(shí)結(jié)束后的時(shí)間)
NSTimeInterval time = 5 * 60;//5分鐘后的秒數(shù)
NSDate *lastTwoHour = [datenow dateByAddingTimeInterval:time];
NSString *currentTimeString_2 = [formatter stringFromDate:lastTwoHour];
NSDate *applyTimeString_2 = [formatter dateFromString:currentTimeString_2];
_fiveMinuteSp = (long)[applyTimeString_2 timeIntervalSince1970];
- 啟動(dòng)倒計(jì)時(shí)
[_countdown countDownWithStratTimeStamp:strtL finishTimeStamp:finishL completeBlock:^(NSInteger day, NSInteger hour, NSInteger minute, NSInteger second) {
//這里可以實(shí)現(xiàn)你想要實(shí)現(xiàn)的UI界面
[weakSelf refreshUIDay:day hour:hour minute:minute second:second];
}];
注意:在控制器釋放的時(shí)候一點(diǎn)要停止計(jì)時(shí)器链沼,以免再次進(jìn)入發(fā)生錯(cuò)誤
- (void)dealloc {
[_countdown destoryTimer];
}
在我寫著需求的時(shí)候默赂,發(fā)現(xiàn)這樣的倒計(jì)時(shí)在真機(jī)上app退到后臺(tái)后,倒計(jì)時(shí)會(huì)停止括勺。
所以我想了一個(gè)簡(jiǎn)單的方法缆八,但是這個(gè)方法的弊端在于:如果用戶更改手機(jī)本地的時(shí)間曲掰,這里的倒計(jì)時(shí)就會(huì)出現(xiàn)問題。各位大神如有解決辦法奈辰,請(qǐng)告知栏妖,謝謝!
以下是我的方法:
首先注冊(cè)兩個(gè)通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didInBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];//app進(jìn)入后臺(tái)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterForground:) name:UIApplicationWillEnterForegroundNotification object:nil];//app進(jìn)入前臺(tái)
實(shí)現(xiàn)這兩個(gè)通知方法:
- (void) didInBackground: (NSNotification *)notification {
NSLog(@"倒計(jì)時(shí)進(jìn)入后臺(tái)");
[_countdown destoryTimer];//倒計(jì)時(shí)停止
}
- (void) willEnterForground: (NSNotification *)notification {
NSLog(@"倒計(jì)時(shí)進(jìn)入前臺(tái)");
[self getNowTimeSP:@""]; //進(jìn)入前臺(tái)重新獲取當(dāng)前的時(shí)間戳奖恰,在進(jìn)行倒計(jì)時(shí)吊趾, 主要是為了解決app退到后臺(tái)倒計(jì)時(shí)停止的問題,缺點(diǎn)就是不能防止用戶更改本地時(shí)間造成的倒計(jì)時(shí)錯(cuò)誤
}
同樣瑟啃,注冊(cè)一個(gè)通知后就要移除,可以在 dealloc 方法中寫
[[NSNotificationCenter defaultCenter] removeObserver:self];
下面附上我寫的 倒計(jì)時(shí)Demo