iOS短信驗證碼倒計時

- (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);
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容