使用Timer时程序退入后台停止计时解决方法

2017-11-01  本文已影响0人  李子哈哈

最近在弄计时器,发现程序进入后台后,计时器停止计时,再次进入程序后,界面的时间更新对不上号。
刚开始以为是系统问题,因为最近坑爹滴ios11出来鸟。。。但是细心滴测试小伙伴发现并不是,泪奔~~~
在网上查阅资料后终于找到解决方法:得到程序处于后台的时间,当程序进入前台后,根据这个时间对timer的处理操作做相应的处理,啦啦啦~
在这里,记录下本宝宝在网上找到滴方法代码伐:

  1. 在用到计时器的类里面添加通知
    //这里是封装好了的添加通知的方法,直接在block里面返回处于后台的时间
    [LZHandlerEnterBackground addObserverUsingBlock:^(NSNotification * _Nonnull note, NSTimeInterval stayBackgroundTime) {
        //stayBackgroundTime就是程序处于后台的时间
        
    }];
  1. 当然还要在- dealloc方法里面移除通知,不然会出现内存泄漏
- (void)dealloc {
    [LZHandlerEnterBackground removeNotificationObserver:self];
}

在上面的添加通知、移除通知,我都是封装在LZHandlerEnterBackground这个工具类里面,可以很方便的调用。
在这里贴出这个工具类的代码:

#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
#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
上一篇下一篇

猜你喜欢

热点阅读