項目中有一個支付時間倒計時的需求,類似于美團外賣的支付倒計時。我也從網上搜到一些實現的方法,以下是我總結的一些。
界面展示.png
倒計時有三種實現的方法:
- 通過定時器NSTimer,屬于比較簡單的寫法;
- 通過GCD;
第一種:
_seconds = 60;//60秒倒計時
_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; //倒計時時間
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); //每秒執行
dispatch_source_set_event_handler(_timer, ^{
if(timeout<=0){ //倒計時結束,關閉
dispatch_source_cancel(_timer);
dispatch_release(_timer);
dispatch_async(dispatch_get_main_queue(), ^{
//設置界面的按鈕顯示 根據自己需求設置
。。。。。。。。
});
}else{
int minutes = timeout / 60;
int seconds = timeout % 60;
NSString *strTime = [NSString stringWithFormat:@"%d分%.2d秒后重新獲取驗證碼",minutes, seconds];
dispatch_async(dispatch_get_main_queue(), ^{
//設置界面的按鈕顯示 根據自己需求設置
。。。。。。。。
});
timeout--;
}
});
dispatch_resume(_timer);
我的項目中運用的是通過GCD來實現倒計時。原理就是:使用GCD創建定時器并設置定時器的間隔時間為1秒,然后在定時器的響應事件方法中將倒計時的總時間依次減1,由于定時器響應事件是在block中,所有控件的修改需要使用__weak來修飾,避免循環調用。以下是我的代碼:
在HCCountdown.h文件中
/**
* 用時間戳倒計時
* starTimeStamp 開始的時間戳
* finishTimeStamp 結束的時間戳
* day 倒計時開始后的剩余的天數
* hour 倒計時開始后的剩余的小時
* minute 倒計時開始后的剩余的分鐘
* second 倒計時開始后的剩余的秒數
*/
-(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]; //時間戳轉時間
NSDate *startDate = [self dateWithLong:starTimeStamp];
NSTimeInterval timeInterval =[finishDate timeIntervalSinceDate:startDate]; //獲取兩個時間的間隔時間段
__block int timeout = timeInterval; //倒計時時間
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(_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;
- 首先獲取開始時間的時間戳
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
// ----------設置你想要的格式,hh與HH的區別:分別表示12小時制,24小時制
[formatter setDateFormat:@"YYYY年MM月dd日HH:mm:ss"];
//現在時間,你可以輸出來看下是什么格式
NSDate *datenow = [NSDate date];
//----------將nsdate按formatter格式轉成NSString
NSString *currentTimeString_1 = [formatter stringFromDate:datenow];
NSDate *applyTimeString_1 = [formatter dateFromString:currentTimeString_1];
_nowTimeSp = (long)[applyTimeString_1 timeIntervalSince1970];
- 獲取5分鐘后的時間(也就是倒計時結束后的時間)
NSTimeInterval time = 5 * 60;//5分鐘后的秒數
NSDate *lastTwoHour = [datenow dateByAddingTimeInterval:time];
NSString *currentTimeString_2 = [formatter stringFromDate:lastTwoHour];
NSDate *applyTimeString_2 = [formatter dateFromString:currentTimeString_2];
_fiveMinuteSp = (long)[applyTimeString_2 timeIntervalSince1970];
- 啟動倒計時
[_countdown countDownWithStratTimeStamp:strtL finishTimeStamp:finishL completeBlock:^(NSInteger day, NSInteger hour, NSInteger minute, NSInteger second) {
//這里可以實現你想要實現的UI界面
[weakSelf refreshUIDay:day hour:hour minute:minute second:second];
}];
注意:在控制器釋放的時候一點要停止計時器,以免再次進入發生錯誤
- (void)dealloc {
[_countdown destoryTimer];
}
在我寫著需求的時候,發現這樣的倒計時在真機上app退到后臺后,倒計時會停止。
所以我想了一個簡單的方法,但是這個方法的弊端在于:如果用戶更改手機本地的時間,這里的倒計時就會出現問題。各位大神如有解決辦法,請告知,謝謝!
以下是我的方法:
首先注冊兩個通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didInBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];//app進入后臺
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterForground:) name:UIApplicationWillEnterForegroundNotification object:nil];//app進入前臺
實現這兩個通知方法:
- (void) didInBackground: (NSNotification *)notification {
NSLog(@"倒計時進入后臺");
[_countdown destoryTimer];//倒計時停止
}
- (void) willEnterForground: (NSNotification *)notification {
NSLog(@"倒計時進入前臺");
[self getNowTimeSP:@""]; //進入前臺重新獲取當前的時間戳,在進行倒計時, 主要是為了解決app退到后臺倒計時停止的問題,缺點就是不能防止用戶更改本地時間造成的倒計時錯誤
}
同樣,注冊一個通知后就要移除,可以在 dealloc 方法中寫
[[NSNotificationCenter defaultCenter] removeObserver:self];
下面附上我寫的 倒計時Demo