iOS常用技术 —获取验证码 倒计时 实现

来源:互联网 发布:新网域名管理后台 编辑:程序博客网 时间:2024/05/14 15:54

在用户登录界面,通常都会设置一个获取验证码Button,用户点击时,客户端需要改变button的显示样式。主要是三件事:

  1. 显示倒计时
  2. 取消button的用户响应
  3. 倒计时结束,恢复事件响应

主要实现如下:

  • 在Button的点击事件中,实例化一个NSTimer计时器
#definte Countdown 60  // 每一秒调用  NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self  selector:@selector(changeButtonText) userInfo:nil repeats:YES];
  • 实现计时器方法
  //当点击获取验证码后调用此方法,先改变按钮状态  -(void)changeButtonText{  //默认开始的时间为60秒    if(number == 0){  //倒计时结束,恢复button的第一响应        number = Countdown;        _isOneClick = NO; //使用自定义的标识,判断button当前点击状态。倒计时结束,可点击,置为no        // 使timer无效        [timer invalidate];        // 开启与用户的交互        self.timeBtn.userInteractionEnabled = YES;  //恢复第一响应者状态        self.timeBtn.enabled = YES;          [self.timeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];  //设置标题       // self.timeBtn.backgroundColor = CodeColor; //设置颜色    }else{        //当倒计时未结束时,每次过一秒钟,界面显示的数字减少一秒        number --; //从60开始倒计时        // 关闭与用户的交互        self.timeBtn.userInteractionEnabled = NO;        [self.timeBtnsetTitle:[NSStringstringWithFormat:@"重新获取(%d秒)",number] forState:UIControlStateNormal];  //将number时间设置成 timebtn的标题        [self.timeBtnsetBackgroundColor:[UIColorgrayColor]];     }   }

第一次实现,比较复杂,后期有待优化。。

在后期测试时,发现NSTimer的倒计时,在后台运行时,会暂停。实际应该是继续计时。通过查找资料,并实验后,发现了以下方法,可以解决 App后台运行时倒计时失效问题 。

在 application: applicationDieEnterBackground 中添加 以下代码:

// App进入后台- (void)applicationDidEnterBackground:(UIApplication *)application {    //进入后台倒计时    UIApplication*   app = [UIApplication sharedApplication];    __block    UIBackgroundTaskIdentifier bgTask;    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{        dispatch_async(dispatch_get_main_queue(), ^{            if (bgTask != UIBackgroundTaskInvalid)            {                bgTask = UIBackgroundTaskInvalid;            }        });    }];    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{        dispatch_async(dispatch_get_main_queue(), ^{            if (bgTask != UIBackgroundTaskInvalid)            {                bgTask = UIBackgroundTaskInvalid;            }        });    });}

再测试,发现即使进入后台,倒计时也能继续了。

0 0
原创粉丝点击