@interface AuthCodeManager : NSObject
+ (void)getValidCode:(UIButton *)sendCodeButton;
@end
#import "AuthCodeManager.h"
@implementation AuthCodeManager
# pragma mark -- 验证码重新发送按钮
+ (void)getValidCode:(UIButton *)sendCodeButton{
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
__block int count= 120;
[sendCodeButton setTitle:[NSString stringWithFormat:@"%d s",count] forState:UIControlStateNormal];
//定时器开始执行的延时时间
NSTimeInterval delayTime = 1.0f;
//定时器的间隔时间
NSTimeInterval timeInterval = 1.0f;
//创建子线程队列
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);
//设置延时的执行时间,delayTime为要延时的秒数
dispatch_time_t startDelayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime*NSEC_PER_SEC));
//设置计时器
dispatch_source_set_timer(_timer, startDelayTime, timeInterval*NSEC_PER_SEC, 0.1*NSEC_PER_SEC);
dispatch_source_set_event_handler(_timer, ^{
//执行事件
/**
* 回主线程更新UI
*/
count--;
dispatch_async(dispatch_get_main_queue(), ^{
if (count==0) {
dispatch_cancel(_timer);//取消定时器
// _timer = nil;
sendCodeButton.enabled = YES;
[sendCodeButton setTitle:@"获取验证码" forState:UIControlStateNormal];
}
else{
sendCodeButton.enabled = NO;
[sendCodeButton.titleLabel setText:[NSString stringWithFormat:@"%d s",count]];
[sendCodeButton setTitle:[NSString stringWithFormat:@"%d s",count] forState:UIControlStateNormal];
}
});
});
//启动计时器
dispatch_resume(_timer);
}
@end