http://blog.csdn.net/m13215519957/article/details/51802187
(iOS)移动app很多时候会遇到注册,获取验证码倒计时的时候,按下home键进入后台,倒计时就会停止,这里提供一种方法,来保证时间会正常进行下去。
1:从appDelegate中这两个方法分别发送通知
#define sendNotification(key) [[NSNotificationCenter defaultCenter] postNotificationName:key object:self userInfo:nil]; //发送通知
#define WeakObj(o) autoreleasepool{} __weak typeof(o) o##Weak = o; //引用self
- (void)applicationDidEnterBackground:(UIApplication*)application{
//进入后台时要进行的处理
sendNotification(kRegisterBackgroundNoti)
}
- (void)applicationWillEnterForeground:(UIApplication*)application{
//进入前台时要进行的处理
sendNotification(kRegisterFrontNoti)
}
2:在目标控制器中,接收这两个通知,在各自的通知方法中获取一次当前系统时间,然后就可以计算出从按下home键退出应用到重新进入应用的时间差
@property(nonatomic,assign)NSDate *backDate;//进入后台时的时间
@property(nonatomic,assign)NSDate *frontDate;//重新打开应用时的时间
@property(nonatomic,assign)dispatch_source_t timer;
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setBackgroundTask) name:kRegisterBackgroundNoti object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setFrontTask) name:kRegisterFrontNoti object:nil];
}
-(void)setBackgroundTask{
self.backDate=[NSDate date];
}
-(void)setFrontTask{
self.frontDate=[NSDate date];
}
这里是读秒的方法
-(void)getStartTime{
__block int timeout=60; //倒计时时间
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
self.timer=timer;
dispatch_source_set_timer(timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
@WeakObj(self);
dispatch_source_set_event_handler(timer, ^{
if(timeout<=0){ //倒计时结束,关闭
dispatch_source_cancel(timer);
dispatch_async(dispatch_get_main_queue(), ^{
//设置界面的按钮显示 根据自己需求设置
// NSLog(@"时间到,停止动作");
});
}else{
if (selfWeak.frontDate&&selfWeak.backDate) { //这里面就是判断进出应用两次之间的时间差
NSTimeInterval backDate = [selfWeak.backDate timeIntervalSinceReferenceDate];
NSTimeInterval frontDate = [selfWeak.frontDate timeIntervalSinceReferenceDate];
int interval = frontDate - backDate;
timeout=timeout-interval;
selfWeak.backDate=nil;
selfWeak.frontDate=nil;
}
int seconds = timeout % 61;
NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
dispatch_async(dispatch_get_main_queue(), ^{
//NSLog(@"每秒执行一次");
});
timeout--;
}
});
dispatch_resume(timer);
}
3 注意事项:如果还在读秒时,就执行了返回上一级操作,此时就应该暂停该队列
-(void)viewDidDisappear:(BOOL)animated{
[super viewDidDisappear:animated];
dispatch_suspend(self.timer);//退出界面时,读秒还在进行中,这时候应该暂停该队列
}