搜尋

首頁  >  問答  >  主體

objective-c - ios开发验证码倒计时60s,真机测试退到后台,再次打开发现秒数没有变化,怎么办?

__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_async(dispatch_get_main_queue(), ^{
            
            [self.validBtn setTitle:@"获取短信验证码" forState:UIControlStateNormal];
            //self.validBtn.backgroundColor=RGB(120, 0, 103);
            [self.validBtn setBackgroundImage:[UIImage imageNamed:@"获取验证码"] forState:UIControlStateNormal];
            self.validBtn.userInteractionEnabled = YES;
        });
    }else{
        int seconds = timeout;
        NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self.validBtn setTitle:[NSString stringWithFormat:@"%@秒",strTime] forState:UIControlStateNormal];
            //self.validBtn.backgroundColor=RGB(207, 207, 207);
            [self.validBtn setBackgroundImage:[UIImage imageNamed:@"获取验证码-不可点击"] forState:UIControlStateNormal];
            self.validBtn.userInteractionEnabled = NO;
        });
        timeout--;
    }
});
dispatch_resume(_timer);
PHPzPHPz2889 天前421

全部回覆(7)我來回復

  • 天蓬老师

    天蓬老师2017-04-17 17:53:26

    離開目前頁面的時候把執行緒終結,然後初始化倒數計時為60

    回覆
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 17:53:26

    計時器需要運行在Runloop中

    回覆
    0
  • 怪我咯

    怪我咯2017-04-17 17:53:26

    你到後台之後,如果你不是申明為可後台運行的程式的話,NSTimer應該是不走的。
    如果是我的話:
    1.進後台前停止Timer,再在appdelegate的applicationDidEnterBackground中記錄一下時間,進前台時再對比一下時間,計算差值,刷新驗證碼數值顯示,再啟動Timer。
    2.進後台前停止Timer,或者,用backgroundTask在後台每隔幾秒將驗證碼的數字減一下,回前台,再啟動Timer。 (這種好無聊。。。)
    3.把你的App申明為可後台運行的程式。
    我會選第一種。 。 。

    回覆
    0
  • PHP中文网

    PHP中文网2017-04-17 17:53:26

    我的方案是這樣的:

    1. 記錄開始時間。

    2. 每秒鐘更新介面上的顯示,用 當前時間 - 開始時間 得到秒數顯示在介面上当前时间 - 开始时间 得到秒数显示在界面上

    3. 我使用的是 GCD Timer

    我使用的是 GCD Timer, 不需要額外處理進入後台再返回前台時的情況,用其它的當然也沒問題,處理好這邊的東西就可以了。 🎜🎜 🎜

    回覆
    0
  • PHPz

    PHPz2017-04-17 17:53:26

    可以試試下面的方案。

      __block long totalComplete = 0;
      dispatch_source_set_event_handler(source, ^{
        long value = dispatch_source_get_data(source);
        totalComplete += value;
        self.progressView.progress = (CGFloat)totalComplete/100.0f;
      });
    

    回覆
    0
  • 大家讲道理

    大家讲道理2017-04-17 17:53:26

    GreedTimer可以解決你說的問題。使用的時候GRTimer的timeInBackground设置为YES

    回覆
    0
  • ringa_lee

    ringa_lee2017-04-17 17:53:26

    前面說的方法都不行啊,我找到一個簡單可行的。

    http://www.jianshu.com/p/8e61...

    回覆
    0
  • 取消回覆