最近在弄计时器,发现程序进入后台后,计时器停止计时,再次进入程序后,界面的时间更新对不上号。
刚开始以为是系统问题,因为最近坑爹滴ios11出来鸟。。。但是细心滴测试小伙伴发现并不是,泪奔~~~
在网上查阅资料后终于找到解决方法:得到程序处于后台的时间,当程序进入前台后,根据这个时间对timer的处理操作做相应的处理,啦啦啦~
在这里,记录下本宝宝在网上找到滴方法代码伐:
- 在用到计时器的类里面添加通知
//这里是封装好了的添加通知的方法,直接在block里面返回处于后台的时间
[LZHandlerEnterBackground addObserverUsingBlock:^(NSNotification * _Nonnull note, NSTimeInterval stayBackgroundTime) {
//stayBackgroundTime就是程序处于后台的时间
}];
- 当然还要在
- dealloc
方法里面移除通知,不然会出现内存泄漏
- (void)dealloc {
[LZHandlerEnterBackground removeNotificationObserver:self];
}
在上面的添加通知、移除通知,我都是封装在LZHandlerEnterBackground
这个工具类里面,可以很方便的调用。
在这里贴出这个工具类的代码:
- 在
LZHandlerEnterBackground.h
文件中
#import <Foundation/Foundation.h>
typedef void(^YTHandlerEnterBackgroundBlock)(NSNotification * _Nonnull note, NSTimeInterval stayBackgroundTime);
@interface LZHandlerEnterBackground : NSObject
+ (void)removeNotificationObserver:(nullable id)observer;
+ (void)addObserverUsingBlock:(nullable YTHandlerEnterBackgroundBlock)block;
@end
- 在
LZHandlerEnterBackground.m
文件中
#import "LZHandlerEnterBackground.h"
@implementation LZHandlerEnterBackground
+ (void)removeNotificationObserver:(id)observer {
if (!observer) {
return;
}
[[NSNotificationCenter defaultCenter]removeObserver:observer name:UIApplicationDidEnterBackgroundNotification object:nil];
[[NSNotificationCenter defaultCenter]removeObserver:observer name:UIApplicationWillEnterForegroundNotification object:nil];
}
+ (void)addObserverUsingBlock:(YTHandlerEnterBackgroundBlock)block {
__block CFAbsoluteTime enterBackgroundTime;
[[NSNotificationCenter defaultCenter]addObserverForName:UIApplicationDidEnterBackgroundNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
if (![note.object isKindOfClass:[UIApplication class]]) {
enterBackgroundTime = CFAbsoluteTimeGetCurrent();
}
}];
__block CFAbsoluteTime enterForegroundTime;
[[NSNotificationCenter defaultCenter]addObserverForName:UIApplicationWillEnterForegroundNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
if (![note.object isKindOfClass:[UIApplication class]]) {
enterForegroundTime = CFAbsoluteTimeGetCurrent();
CFAbsoluteTime timeInterval = enterForegroundTime-enterBackgroundTime;
block? block(note, timeInterval): nil;
}
}];
}
@end
网友评论