Scheduled NSTimer when app is in background?

2019-01-03 08:55发布

How do people deal with a scheduled NSTimer when an app is in the background?

Let's say I update something in my app every hour.

updateTimer = [NSTimer scheduledTimerWithTimeInterval:60.0*60.0 
target:self 
selector:@selector(updateStuff) 
userInfo:nil 
repeats:YES];

When in the background, this timer obviously doesn't fire(?). What should happen when the user comes back to the app..? Is the timer still running, with the same times?

And what would would happen if the user comes back in over an hour. Will it trigger for all the times that it missed, or will it wait till the next update time?

What I would like it to do is update immediately after the app comes into the foreground, if the date it should have fired is in the past. Is that possible?

9条回答
Summer. ? 凉城
2楼-- · 2019-01-03 09:24

create Global uibackground task identifier.

UIBackgroundTaskIdentifier bgRideTimerTask;

now create your timer and add BGTaskIdentifier With it, Dont forget to remove old BGTaskIdentifier while creating new Timer Object.

 [timerForRideTime invalidate];
 timerForRideTime = nil;

 bgRideTimerTask = UIBackgroundTaskInvalid;

 UIApplication *sharedApp = [UIApplication sharedApplication];       
 bgRideTimerTask = [sharedApp beginBackgroundTaskWithExpirationHandler:^{

                            }];
 timerForRideTime =  [NSTimer scheduledTimerWithTimeInterval:1.0
                                                                                 target:self
                                                                               selector:@selector(timerTicked:)
                                                                               userInfo:nil
                                                                                repeats:YES]; 
                                                   [[NSRunLoop currentRunLoop]addTimer:timerForRideTime forMode: UITrackingRunLoopMode];

Here this will work for me even when app goes in background.ask me if you found new problems.

查看更多
Viruses.
3楼-- · 2019-01-03 09:31

You need to add your timer in current run loop.

[[NSRunLoop currentRunLoop] addTimer:myTimer forMode:NSRunLoopCommonModes];
查看更多
Evening l夕情丶
4楼-- · 2019-01-03 09:33

When in the background, this timer obviously doesn't fire

This post suggests that things aren't quite as clear as that. You should invalidate your timers as your app goes into the background and restart them when it comes back to foreground. Running stuff while in the background might be possible but then again it might get you killed...

You can find good documentation about the iOS multitasking approach here.

查看更多
登录 后发表回答