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);
阅读 8.8k
7 个回答
新手上路,请多包涵

离开当前页面的时候把线程终结,然后初始化倒计时为60

计时器需要运行在Runloop中

你到后台之后,如果你不是申明为可后台运行的程序的话,NSTimer应该是不走的。
如果是我的话:
1.进后台前停止Timer,再在appdelegate的applicationDidEnterBackground中记录一下时间,进前台时再对比一下时间,计算差值,刷新验证码数值显示,再启动Timer。
2.进后台前停止Timer,或者,用backgroundTask在后台每隔几秒将验证码的数字减一下,回前台,再启动Timer。(这种好无聊。。。)
3.把你的App申明为可后台运行的程序。
我会选第一种。。。

我的方案是这样的:

  1. 记录开始时间。

  2. 每秒钟更新界面上的显示,用 当前时间 - 开始时间 得到秒数显示在界面上

  3. 我使用的是 GCD Timer, 不需要额外处理进入后台再返回前台时的情况,用其它的当然也没问题,处理好这边的东西就可以了。

可以试试下面的方案。

  __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;
  });

GreedTimer可以解决你说的问题。使用的时候GRTimertimeInBackground设置为YES

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题