美文网首页
iOS短信验证码倒计时

iOS短信验证码倒计时

作者: Claire_wu | 来源:发表于2017-07-13 19:26 被阅读77次
    - (IBAction)sendCodeClick:(id)sender {
        
        //1.设置倒计时
        [self sentPhoneCodeTimeMethod];
       //2.发送请求获取验证码
       /*这里写发送请求部分代码*/
    }
    
    //计时器发送验证码
    -(void)sentPhoneCodeTimeMethod{
        //倒计时时间 - 60秒
        __block NSInteger timeOut = 59;
        //执行队列
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        //计时器 -》dispatch_source_set_timer自动生成
        dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
        dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
        dispatch_source_set_event_handler(timer, ^{
            if (timeOut <= 0) {
                dispatch_source_cancel(timer);
                //主线程设置按钮样式-》
                dispatch_async(dispatch_get_main_queue(), ^{
                    [_codeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                    _codeBtn.enabled = YES;
                });
            }else{
                //开始计时
                //剩余秒数 seconds
                NSInteger seconds = timeOut % 60;
                NSString *strTime = [NSString stringWithFormat:@"%.1ld",seconds];
                //主线程设置按钮样式
                dispatch_async(dispatch_get_main_queue(), ^{
                    [UIView beginAnimations:nil context:nil];
                    [UIView setAnimationDuration:1.0];
                    [_codeBtn setTitle:[NSString stringWithFormat:@"(%@S)",strTime] forState:UIControlStateNormal];
                    [UIView commitAnimations];
                    //计时器件不允许点击
                    _codeBtn.enabled = NO;
                });
                timeOut--;
            }
        });
        dispatch_resume(timer);
    }
    

    相关文章

      网友评论

          本文标题:iOS短信验证码倒计时

          本文链接:https://www.haomeiwen.com/subject/kxdghxtx.html