iOS 開發(fā) 簡單的倒計時實現(xiàn)

項目中有一個支付時間倒計時的需求,類似于美團外賣的支付倒計時。我也從網(wǎng)上搜到一些實現(xiàn)的方法,以下是我總結(jié)的一些。

界面展示.png

倒計時有三種實現(xiàn)的方法:

  1. 通過定時器NSTimer,屬于比較簡單的寫法;
  2. 通過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); //每秒執(zhí)行 
 dispatch_source_set_event_handler(_timer, ^{ 
   if(timeout<=0){ //倒計時結(jié)束,關(guān)閉 
     dispatch_source_cancel(_timer); 
     dispatch_release(_timer); 
     dispatch_async(dispatch_get_main_queue(), ^{ 
//設置界面的按鈕顯示 根據(jù)自己需求設置 
       。。。。。。。。 
     }); 
   }else{ 
     int minutes = timeout / 60; 
     int seconds = timeout % 60; 
     NSString *strTime = [NSString stringWithFormat:@"%d分%.2d秒后重新獲取驗證碼",minutes, seconds]; 
     dispatch_async(dispatch_get_main_queue(), ^{ 
       //設置界面的按鈕顯示 根據(jù)自己需求設置 
。。。。。。。。 
     }); 
     timeout--; 
   } 
 }); 
 dispatch_resume(_timer);

我的項目中運用的是通過GCD來實現(xiàn)倒計時。原理就是:使用GCD創(chuàng)建定時器并設置定時器的間隔時間為1秒,然后在定時器的響應事件方法中將倒計時的總時間依次減1,由于定時器響應事件是在block中,所有控件的修改需要使用__weak來修飾,避免循環(huán)調(diào)用。以下是我的代碼:

在HCCountdown.h文件中

/**
 * 用時間戳倒計時
 * starTimeStamp            開始的時間戳
 * finishTimeStamp          結(jié)束的時間戳
 * day                      倒計時開始后的剩余的天數(shù)
 * hour                     倒計時開始后的剩余的小時
 * minute                   倒計時開始后的剩余的分鐘
 * second                   倒計時開始后的剩余的秒數(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]; //時間戳轉(zhuǎn)時間
        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); //每秒執(zhí)行
            dispatch_source_set_event_handler(_timer, ^{
                if(timeout<=0){ //倒計時結(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;

  1. 首先獲取開始時間的時間戳
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // ----------設置你想要的格式,hh與HH的區(qū)別:分別表示12小時制,24小時制
    [formatter setDateFormat:@"YYYY年MM月dd日HH:mm:ss"];
    
    //現(xiàn)在時間,你可以輸出來看下是什么格式
    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];
  1. 獲取5分鐘后的時間(也就是倒計時結(jié)束后的時間)
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];
  1. 啟動倒計時
[_countdown countDownWithStratTimeStamp:strtL finishTimeStamp:finishL completeBlock:^(NSInteger day, NSInteger hour, NSInteger minute, NSInteger second) {
        //這里可以實現(xiàn)你想要實現(xiàn)的UI界面
        [weakSelf refreshUIDay:day hour:hour minute:minute second:second];
    }];
注意:在控制器釋放的時候一點要停止計時器,以免再次進入發(fā)生錯誤
- (void)dealloc {
    [_countdown destoryTimer];  
}

在我寫著需求的時候,發(fā)現(xiàn)這樣的倒計時在真機上app退到后臺后,倒計時會停止。
所以我想了一個簡單的方法,但是這個方法的弊端在于:如果用戶更改手機本地的時間,這里的倒計時就會出現(xiàn)問題。各位大神如有解決辦法,請告知,謝謝!

以下是我的方法:

首先注冊兩個通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didInBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];//app進入后臺
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterForground:) name:UIApplicationWillEnterForegroundNotification object:nil];//app進入前臺
實現(xiàn)這兩個通知方法:
- (void) didInBackground: (NSNotification *)notification {
    
    NSLog(@"倒計時進入后臺");
    [_countdown destoryTimer];//倒計時停止
    
}

- (void) willEnterForground: (NSNotification *)notification {
    
    NSLog(@"倒計時進入前臺");
    [self getNowTimeSP:@""];  //進入前臺重新獲取當前的時間戳,在進行倒計時, 主要是為了解決app退到后臺倒計時停止的問題,缺點就是不能防止用戶更改本地時間造成的倒計時錯誤
    
}

同樣,注冊一個通知后就要移除,可以在 dealloc 方法中寫

    [[NSNotificationCenter defaultCenter] removeObserver:self];

下面附上我寫的 倒計時Demo

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,562評論 19 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,040評論 25 709
  • 每天該工作的時候,該學習的時候,都在一次一次玩手機,到了下班的點發(fā)現(xiàn)自己什么都沒干,心里會有點慌,但是大腦馬...
    Blusdan閱讀 626評論 0 1
  • 所有的關(guān)于年的兇猛 都在暗暗地準備反擊 你看 小年夜的火苗已經(jīng)點燃 第一串鞭炮聲 那些年在一起集結(jié) 密謀趕過來 很...
    禾葉兄弟閱讀 392評論 1 3
  • 我要加油加油加油?。?! 趕緊更新?。?! 靈感!你快來?。。。?! 太完美主義了,我要為難自己?。?!
    蘇瑞旻閱讀 119評論 0 0

友情鏈接更多精彩內(nèi)容