iOS 開發 簡單的倒計時實現

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

界面展示.png

倒計時有三種實現的方法:

  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); //每秒執行 
 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;

  1. 首先獲取開始時間的時間戳
    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];
  1. 獲取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];
  1. 啟動倒計時
[_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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,923評論 18 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,284評論 25 708
  • 今天嘗試了一個類似舞蹈動作的腰腹運動,十七分鐘汗嘩嘩的流,我覺得是對了的! 明天周五!加油??!
    只一點閱讀 185評論 0 0
  • 每天該工作的時候,該學習的時候,都在一次一次玩手機,到了下班的點發現自己什么都沒干,心里會有點慌,但是大腦馬...
    Blusdan閱讀 537評論 0 1
  • 所有的關于年的兇猛 都在暗暗地準備反擊 你看 小年夜的火苗已經點燃 第一串鞭炮聲 那些年在一起集結 密謀趕過來 很...
    禾葉兄弟閱讀 370評論 1 3