objective-c - ios开发验证码倒计时60s,真机测试退到后台,再次打开发现秒数没有变化,怎么办?
PHPz
PHPz 2017-04-17 17:51:26
0
7
346

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

学习是最好的投资!

Antworte allen(7)
Peter_Zhu

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

伊谢尔伦

计时器需要运行在Runloop中

刘奇

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

洪涛

我的方案是这样的:

  1. 记录开始时间。

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

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

PHPzhong

可以试试下面的方案。

  __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可以解决你说的问题。使用的时候GRTimer的timeInBackground设置为YES

左手右手慢动作

前面说的方法都不行啊,我找到一个简单可行的。

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

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!