ios 開發驗證碼倒計時

Untitled.gif

在上一個項目中有使用到驗證碼倒計時功能,之前同事的做法是直接使用NSTimer,比較嚴重的bug是app計入后臺之后倒計時就暫停,重新進入前臺才有倒計時,在網上看到使用GCD,完美解決bug,自己嘗試做了一個demo,主要代碼如下:

#import "ViewController.h"

@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIButton *codeBtn;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
}
// 開啟倒計時效果
-(void)open{
    
    //倒計時時間(秒)
    __block NSInteger time = 20;
    
    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);
    
    __weak typeof(self) weakself = self;
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒計時結束,關閉
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakself.codeBtn setTitle:@"重新發送" forState:UIControlStateNormal];
                weakself.codeBtn.enabled = YES;
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //設置按鈕顯示讀秒效果
                [weakself.codeBtn setTitle:[NSString stringWithFormat:@"%ds", seconds] forState:UIControlStateNormal];
                weakself.codeBtn.enabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}

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

推薦閱讀更多精彩內容