发送短信成功后需要倒计时一段时间才能够再次发送,在此记录一个比较好的实现方法,如有什么问题欢迎指正.
1.申明一个全局定时器timer
dispatch_source_t _timer;
2.加载页面时候读取存储的时间戳time与当前时间戳比较小于60秒计时
//和当前时间戳比较//取当前时间于保存的时间比较,大于60秒继续计时
NSDate *date = [NSDate date];
NSInteger timeFlag = [self timeIntergerWithDate:date];
NSInteger time = timeFlag;
time = [[NSUserDefaults standardUserDefaults] integerForKey:@"timecount"];
//两者比较,若小于60秒开始计时
if (timeFlag-time < 60) {
[self openCountdownWithTimeCount:60-(timeFlag - time)];
}
3.点击获取验证码按钮时保存时间
NSDate *date = [NSDate date];
NSInteger timeFlag = [self timeIntergerWithDate:date];
[[NSUserDefaults standardUserDefaults] setInteger:timeFlag forKey:@"timecount"];
4.页面关闭时销毁定时器
- (void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
if (_timer) {
dispatch_source_cancel(_timer);
}
}
附1.倒计时方法
// 开启倒计时效果
-(void)openCountdownWithTimeCount:(NSInteger)timeCount{
__block NSInteger time = timeCount; //倒计时时间
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
_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); //每秒执行
dispatch_source_set_event_handler(_timer, ^{
if(time <= 0){ //倒计时结束,关闭
dispatch_source_cancel(_timer);
dispatch_async(dispatch_get_main_queue(), ^{
//设置按钮的样式
[self.authCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
self.authCodeBtn.backgroundColor = [UIColor redColor];
self.authCodeBtn.enabled = YES;
});
}else{
int seconds = time % 60;
dispatch_async(dispatch_get_main_queue(), ^{
//设置按钮显示读秒效果
[self.authCodeBtn setTitle:[NSString stringWithFormat:@"%.2d", seconds] forState:UIControlStateNormal];
self.authCodeBtn.backgroundColor = [UIColor lightGrayColor];
self.authCodeBtn.enabled = NO;
});
time--;
}
});
dispatch_resume(_timer);
}
附2:时间转换时间戳
+ (long)timeIntergerWithDate:(NSDate *)date{
long firstStamp = [date timeIntervalSince1970];
return firstStamp;
}
网友评论