3

My goal is to run a repeating timer every five seconds if and only if the application is running in the background. I've tried a couple of ideas, but they don't seem to work.

Idea 1: Doesn't run even once.

- (void)applicationDidEnterBackground:(UIApplication *)application {

    [NSTimer scheduledTimerWithTimeInterval:(5.0/5.0) target:self selector:@selector(check_expiry) userInfo:nil repeats:YES];

}

Idea 2: Runs every five seconds, but I can't seem to stop the loop.

- (void)applicationDidEnterBackground:(UIApplication *)application {
    counter = YES;
    while (counter) {
        sleep(5);
        [self check_expiry];
    }
    // Counter is set to NO in willEnterForeground and didBecomeActive, but this loop continues to run due the sleep();
}

How can I get this loop to run properly?

Thanks!

drfranks3
  • 667
  • 8
  • 21

2 Answers2

4

When an application "enters the background" in iOS, that's not like normal operating systems, where it continues to run. The application enters a suspended state. It doesn't keep running; only application state is preserved, and even that's not guaranteed - if the device is running low on memory, iOS will happily terminate your application to give the memory to the active application. If you attempt to block in applicationDidEnterBackground:, like you are doing with sleep(), iOS will simply terminate your application for not returning from that method promptly.

Your application is woken up periodically if it's configured for background processing GPS events, VOIP, etc., but abusing those just to get your app to run will stop you from getting App Store approval.

This is all covered in The iOS Application Programming Guide.

Jim
  • 72,985
  • 14
  • 101
  • 108
0

For anyone looking for a workaround, I merely created a system that schedules timers at a later date when the applicationDidEnterBackground: and changed/cancelled them when they were edited/deleted. Information on timer scheduling was stored in a local dictionary.

drfranks3
  • 667
  • 8
  • 21