GCD 实现你想要的倒计时

前言:最近在做一个项目中有一个邮箱认证的功能,发送短信后,60秒后才能重新再次点击认证,如果在倒计时的过程中,退出了当前页面,过一会再返回来看的时候,需要知道之前的倒计时有没有结束,后来想了想,应该用单例可以解决,于是就动手做了一个demo.


image.png

点击进入下一个需要倒计时的页面


image.png

点击开始倒计时
image.png

然后再倒计时到6秒的时候,点back返回,默念3秒钟再进来当前页面,查看倒计时效果


image.png

大概就是这么个效果了,over
下面贴一下代码,时间紧凑,随便写的两个页面,勿见怪哈...

#import <Foundation/Foundation.h>

typedef NS_ENUM(NSInteger, wherefrom){
    from1 = 1,
    from2 = 2,
    from3 = 3,
};

NS_ASSUME_NONNULL_BEGIN

@interface BMWNSTimer : NSObject
{
    dispatch_source_t _timer;
}
@property (nonatomic,assign)__block int timeLeft;
@property (nonatomic,assign) wherefrom from;  //用于区别哪个倒计时

+ (id)sharedTimerManager;
- (void)countDown;
@end

NS_ASSUME_NONNULL_END
#import "BMWNSTimer.h"

@implementation BMWNSTimer
+ (id)sharedTimerManager{
    static BMWNSTimer *manager =nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (manager ==nil) {
            manager = [[self alloc] init];
        }
    });
    return manager;
}

- (void)countDown{
    
    if (_timeLeft >0) {
        if (_timer) {
            dispatch_source_cancel(_timer);
        }
        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(_timeLeft<=0){//倒计时结束,关闭
                dispatch_source_cancel(_timer);
            }else{
                _timeLeft--;
            }
        });
        dispatch_resume(_timer);
    }
}
@end

然后主要是用计时器的那个页面的代码:

#import "VC2.h"
#import "BMWNSTimer.h"
@interface VC2 ()
@property (nonatomic,strong) UIButton *timeBtn;
@property (nonatomic,assign) int timeout;
@property (nonatomic,strong) dispatch_source_t timer;
@end

@implementation VC2

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    _timeBtn = [[UIButton alloc]initWithFrame:CGRectMake(100, 100, 100, 40)];
    [_timeBtn addTarget:self action:@selector(cutdown) forControlEvents:UIControlEventTouchUpInside];
    [_timeBtn setTitle:@"开始倒计时" forState:UIControlStateNormal];
    [_timeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _timeBtn.backgroundColor = [UIColor redColor];
    [self.view addSubview:_timeBtn];
}


-(void)cutdown{
    _timeout = 10;
    _timeBtn.userInteractionEnabled=NO;
    [self startTime];
}

-(void)startTime{
    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_TIME_NOW, 1.0 * NSEC_PER_SEC, 1.0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(_timer, ^{
        if (self->_timeout <= 0) {
            dispatch_source_cancel(self->_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self->_timeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
                self->_timeBtn.userInteractionEnabled = YES;
                self->_timeBtn.backgroundColor = [UIColor blueColor];
            });
        }else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self->_timeBtn setTitle:[NSString stringWithFormat:@"%d秒",self->_timeout] forState:UIControlStateNormal];
                self->_timeBtn.enabled = YES;
                self->_timeBtn.backgroundColor = [UIColor lightGrayColor];
            });
            self->_timeout--;
            NSLog(@"%d",self->_timeout);
        }
    });
    dispatch_resume(_timer);
}


- (void)viewWillDisappear:(BOOL)animated
{
    if (_timeout > 0) {
        BMWNSTimer *timer = [BMWNSTimer sharedTimerManager];
        timer.timeLeft = _timeout;
        timer.from = from1;
        [timer countDown];
    }
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    BMWNSTimer *timer = [BMWNSTimer sharedTimerManager];
    int time = timer.timeLeft;
    if (time >0 && (timer.from == from1)) {
        _timeout = time;
        _timeBtn.userInteractionEnabled=NO;
        [self startTime];
    } else {
        _timeBtn.enabled=YES;
    }
}
@end

大概就是这些了,这里面需要用到GCD计时器的知识,之前也没用过,看到别人这么用,就自己亲自试了一下,模仿是学习的第一步.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.NSTimer不准时的原因:(1).RunLoop循环处理时间,每次循环是固定时间,只有在这段时间才会去查看N...
    稻春阅读 1,280评论 0 3
  • 我们在开发应用的过程中,往往在很多地方需要倒计时,比如说轮播图,验证码,活动倒计时等等。而在实现这些功能的时候,我...
    伯陽阅读 3,055评论 3 22
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,144评论 1 32
  • 今天是周一,早上上班后。有两件事要说一下。 第一件事,先是李跟我说,九点要谈话,部门正职,左来办公室先后两次,只言...
    大道至简3阅读 172评论 0 0
  • 敬爱的老师,智慧的班主任,亲爱的学兄们:大家好!我是来自广饶亨通农机马云芹,今天是我的日精进行动第197天,给大家...
    云_300a阅读 93评论 0 0