最近在弄計時器,發現程序進入后臺后,計時器停止計時,再次進入程序后,界面的時間更新對不上號。
剛開始以為是系統問題,因為最近坑爹滴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