Question

I have an app that has a feature of a countdown (counts down 6 hours until it reaches 0). When the user moves the app to the background, the counter stops and resumes only when the app is coming back to the foreground. When the app is terminated the counter resets itself.

Is there a way to keep it running no matter what? There is a similar feature on the Apple Clock app when firing the stopwatch, its still working even after terminating the app and relaunching it.

Thanks a lot!!

Was it helpful?

Solution

Since you're counting down a time, you don't actually want to count ticks since that's unreliable.

Instead, remember the start time. Then, with each tick, calculate the time that has passed since the start time.

As you've found out, timers are stopped when the app is in the background. But when you know the start time that doesn't matter: when your app comes back into foreground you simply calculate the elapsed time again and if your desired time span has passed you do your action.

To make this work when your app has been killed you'd need to remember the time via NSUserDefaults. The next time your app starts you read the date from the NSUserDefaults and you then check whether the time has already elapsed. If so, do your action. If not, start your timer.

Once you do your action, clear the date from the NSUserDefaults.

Last but not least, you may also want to look into local notifications which can be scheduled to fire at a certain time. You can use them to alert your user when your app is in background or not running.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top