使用Timer時程序退入后臺停止計時解決方法

最近在弄計時器,發現程序進入后臺后,計時器停止計時,再次進入程序后,界面的時間更新對不上號。
剛開始以為是系統問題,因為最近坑爹滴ios11出來鳥。。。但是細心滴測試小伙伴發現并不是,淚奔~~~
在網上查閱資料后終于找到解決方法:得到程序處于后臺的時間,當程序進入前臺后,根據這個時間對timer的處理操作做相應的處理,啦啦啦~
在這里,記錄下本寶寶在網上找到滴方法代碼伐:

  1. 在用到計時器的類里面添加通知
    //這里是封裝好了的添加通知的方法,直接在block里面返回處于后臺的時間
    [LZHandlerEnterBackground addObserverUsingBlock:^(NSNotification * _Nonnull note, NSTimeInterval stayBackgroundTime) {
        //stayBackgroundTime就是程序處于后臺的時間
        
    }];
  1. 當然還要在- 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
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容