需要注意的是:当点击发送验证码,开始跑秒的时候,进行网络请求,如果用户两次点击发送验证码的时间间隔较短时,停止跑秒,让button的文字显示为重新发送,将时间置为0,要不然重复点击解绑按钮时程序会崩溃;如果跑秒的时候,是一闪一闪的是因为button的类型设置错了,应该将button设置为UIButtonTypeCustom类型的
// 发送验证码的点击事件
- (void)sendCodeBtnAction:(UIButton *)button {
// 点击发送验证码请求数据
[self didClickSendCodeAndGetData];
// button跑秒
__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);
self.timerX = _timer;
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(), ^{
[button setTitle:@"重新发送" forState:UIControlStateNormal];
button.userInteractionEnabled = YES;
});
}else{
int seconds = timeout % 60;
__block NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
dispatch_async(dispatch_get_main_queue(), ^{
if (seconds == 0) {
strTime = @"60";
}
[button setTitle:[NSString stringWithFormat:@"%@秒后重发",strTime] forState:UIControlStateNormal];
button.userInteractionEnabled = NO;
});
timeout--;
}
});
dispatch_resume(_timer);
}
@property (nonatomic, assign) dispatch_source_t timerX;
UIButton *button = (UIButton *)[self.view viewWithTag:200];
[button setTitle:@"重新发送" forState:UIControlStateNormal];
button.userInteractionEnabled = YES;
if (self.timerX) {
dispatch_source_cancel(self.timerX);
self.timerX = 0;
}