第一种网页中查的
NSTimeInterval period = 1.0;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
_defaultTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(_defaultTimer, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0);
__block NSInteger duration = defaultDuration;
dispatch_source_set_event_handler(_defaultTimer, ^{
dispatch_async(dispatch_get_main_queue(), ^{
if(duration==0)
{
dispatch_source_cancel(_defaultTimer);
[self remove];
}
duration--;
});
});
dispatch_source_set_cancel_handler(_defaultTimer, ^{
dispatch_release(_defaultTimer);
});
dispatch_resume(_defaultTimer);
第二种项目中的
-(void)getStartTime{
__block int timeout=30;
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 (timeout<=0) {
dispatch_source_cancel(timer);
dispatch_async(dispatch_get_main_queue(), ^{
self.VerificationLbl.backgroundColor = main_Color;
self.VerificationLbl.text = @"获取验证码";
self.VerificationLbl.textColor = [UIColor whiteColor];
self.VerificationLbl.userInteractionEnabled = YES;
});
}else{
if (backDate && frontDate) {
NSTimeInterval backDates = [backDate timeIntervalSinceReferenceDate];
NSTimeInterval frontDates = [frontDate timeIntervalSinceReferenceDate];
int interval = frontDates - backDates;
timeout=timeout-interval;
backDate=nil;
frontDate=nil;
}
dispatch_async(dispatch_get_main_queue(), ^{
DebugLog(@"倒计时---%d",timeout);
self.VerificationLbl.backgroundColor = [UIColor grayColor];
self.VerificationLbl.text = [NSString stringWithFormat:@"%ds",timeout];
self.VerificationLbl.userInteractionEnabled = NO;
});
timeout--;
}
});
dispatch_resume(timer);
}