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

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

界面展示.png

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

  1. 通過定時(shí)器NSTimer,屬于比較簡單的寫法;
  2. 通過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;

  1. 首先獲取開始時(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];
  1. 獲取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];
  1. 啟動(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退到后臺后,倒計(jì)時(shí)會(huì)停止。
所以我想了一個(gè)簡單的方法,但是這個(gè)方法的弊端在于:如果用戶更改手機(jī)本地的時(shí)間,這里的倒計(jì)時(shí)就會(huì)出現(xiàn)問題。各位大神如有解決辦法,請告知,謝謝!

以下是我的方法:

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

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

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

    [[NSNotificationCenter defaultCenter] removeObserver:self];

下面附上我寫的 倒計(jì)時(shí)Demo

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,461評論 6 532
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,538評論 3 417
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,423評論 0 375
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,991評論 1 312
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,761評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,207評論 1 324
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,268評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,419評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,959評論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,782評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,983評論 1 369
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,528評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,222評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,653評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,901評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,678評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,978評論 2 374

推薦閱讀更多精彩內(nèi)容

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