NSTimer在背景之后延迟了

时间:2014-03-04 19:44:55

标签: ios objective-c background nstimer

timer = [NSTimer bk_timerWithTimeInterval:60 block:^(NSTimer *timer) { ....} repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];


+ (id)bk_timerWithTimeInterval:(NSTimeInterval)inTimeInterval block:(void (^)(NSTimer *timer))block repeats:(BOOL)inRepeats
{
    NSParameterAssert(block != nil);
    return [self timerWithTimeInterval:inTimeInterval target:self selector:@selector(bk_executeBlockFromTimer:) userInfo:[block copy] repeats:inRepeats];
}

+ (void)bk_executeBlockFromTimer:(NSTimer *)aTimer {
    void (^block)(NSTimer *) = [aTimer userInfo];
    if (block) block(aTimer);
}

如果我在几分钟后折叠并展开应用程序,几乎总是计时器立即开火,有时会延迟开火。 为什么计时器并不总是立即起作用?

1 个答案:

答案 0 :(得分:-1)

尝试在Appdelegate中的“didFinishLaunchingWithOptions”中添加此内容

__block UIBackgroundTaskIdentifier locationUpdater =[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{

        [[UIApplication sharedApplication] endBackgroundTask:locationUpdater];

        locationUpdater=UIBackgroundTaskInvalid;

    } ];