69 lines
1.7 KiB
Objective-C
69 lines
1.7 KiB
Objective-C
//
|
|
// CountDownHelper.m
|
|
// YUMI
|
|
//
|
|
// Created by YUMI on 2021/9/15.
|
|
//
|
|
|
|
#import "CountDownHelper.h"
|
|
|
|
@interface CountDownHelper ()
|
|
@property (strong, nonatomic) dispatch_source_t timer;
|
|
@end
|
|
|
|
@implementation CountDownHelper
|
|
|
|
+ (instancetype)shareHelper {
|
|
static dispatch_once_t onceToken;
|
|
static CountDownHelper * helper = nil;
|
|
dispatch_once(&onceToken, ^{
|
|
helper = [[CountDownHelper alloc] init];
|
|
});
|
|
return helper;
|
|
}
|
|
|
|
// 停止倒计时
|
|
- (void)stopCountDown {
|
|
if (self.timer != nil) {
|
|
dispatch_source_cancel(self.timer);
|
|
self.timer = nil;
|
|
}
|
|
}
|
|
|
|
// 开始倒计时
|
|
- (void)openCountdownWithTime:(int)totalTime{
|
|
if (time <= 0) {
|
|
return;
|
|
}
|
|
__block int time = totalTime; //倒计时时间
|
|
if (self.timer != nil) {
|
|
dispatch_source_cancel(self.timer);
|
|
}
|
|
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
|
|
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
|
|
dispatch_source_set_timer(self.timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
|
|
__weak typeof(self) weakself = self;
|
|
dispatch_source_set_event_handler(self.timer, ^{
|
|
__strong typeof(weakself) self = weakself;
|
|
if(time <= 0){ //倒计时结束,关闭
|
|
dispatch_source_cancel(self.timer);
|
|
dispatch_async(dispatch_get_main_queue(), ^{
|
|
if (self.delegate && [self.delegate respondsToSelector:@selector(onCountdownFinish)]) {
|
|
[self.delegate onCountdownFinish];
|
|
}
|
|
});
|
|
}else{
|
|
time--;
|
|
dispatch_async(dispatch_get_main_queue(), ^{
|
|
//设置按钮显示读秒效果
|
|
if (self.delegate && [self.delegate respondsToSelector:@selector(onCountdownOpen:)]) {
|
|
[self.delegate onCountdownOpen:time];
|
|
}
|
|
});
|
|
|
|
}
|
|
});
|
|
dispatch_resume(self.timer);
|
|
}
|
|
@end
|