ios 倒计时 (离开界面再回来继续)
#import <Foundation/Foundation.h>
typedef NS_ENUM(NSInteger, wherefrom){
from1 = 1,
from2 = 2,
from3 = 3,
};
@interface cutDownManager : NSObject
{
dispatch_source_t _timer;
}
@property (nonatomic,assign)__block int timeLeft;
@property (nonatomic,assign) wherefrom from; //用于区别哪个倒计时
+ (id)sharedTimerManager;
- (void)countDown;
@end
#import "cutDownManager.h"
@implementation cutDownManager
+ (id)sharedTimerManager{
static cutDownManager *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--;
DLog(@"----lefttime ======%d",_timeLeft);
}
});
dispatch_resume(_timer);
}
}
@end
应用
//获取短信验证码
- (IBAction)getMsgCode{
timeout = 60; //倒计时时间
[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_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(), ^{
//设置界面的按钮显示 根据自己需求设置
_getMsglabel.text = @"重新获取";
_getMsgBtn.userInteractionEnabled = YES;
});
}else{
int seconds = timeout % 120;
NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
dispatch_async(dispatch_get_main_queue(), ^{
//设置界面的按钮显示 根据自己需求设置
_getMsglabel.text = [NSString stringWithFormat:@"%@s",strTime];
_getMsgBtn.userInteractionEnabled = NO;
});
timeout--;
DLog(@"---------%d",timeout);
}
});
//启动
dispatch_resume(_timer);
}
-(void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
//掐掉倒计时
// if (_timer && timeout > 0) {
// dispatch_source_cancel(_timer);
// }
if (timeout >0) {
cutDownManager *manager = [cutDownManager sharedTimerManager];
manager.timeLeft = timeout;
manager.from = from1;
[manager countDown];
timeout = 0;//置为0,释放controller
}
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
cutDownManager *manager = [cutDownManager sharedTimerManager];
int temp = manager.timeLeft;
if (temp > 0 && (manager.from == from1)) {
timeout = temp;//倒计时时间
_getMsgBtn.enabled =NO;
[self startTime];
}else{
_getMsgBtn.enabled =YES;
}
}