4

I need to run a timer in the background when my app is closed, however I have been reading that this isn't possible. I know that I can run it in the background for ~10 minutes, but I need considerably more than that (up to at least 2 hours).

I was wondering if there is a way to do this by saving the timer value when the app is closed, the current time, retrieving them when it re-opens, and comparing them to the current time to get the difference. I could then restart the timer and add the values together.

Anyone have any suggestions as to how I could do this?

jscs
  • 63,694
  • 13
  • 151
  • 195
user3746428
  • 11,047
  • 20
  • 81
  • 137
  • Can't you store the time as a text file, and then next time open up and compare? A simple time calculator logic like the one used in the link could work: http://www.timeanddate.com/date/timeduration.html (But of course, you have to code out the logic) – hsirkar Jul 26 '15 at 20:51
  • As previously said, the best way is to store it. You tell us about timer but maybe your functionality could be implement another way (notification?...) *I try to find another way but depends what you really need*. – MacKentoch Jul 26 '15 at 21:14

1 Answers1

6

The correct approach is to maintain the illusion that the timer is running, without actually keeping it running. There are two aspects to this:

  1. Before the app leaves the foreground, it should save information about the timer (e.g. either the time the timer started if you're counting up or the time the timer is supposed to stop if you're counting down). You can use a variety of different technologies to save this information (e.g. a plist, keyed archiver, Core Data, etc.) in persistent storage.

    Then when the app starts up again, check the saved time and reconstruct the UI to start the timer again from the appropriate state.

  2. If you're counting down to some time (i.e. you want to let the user know when the particular point in time has been reached, even if the app isn't running), you could use a local notification. See the Local and Remote Notification Programming Guide, focusing on the local notifications.

Community
  • 1
  • 1
Rob
  • 415,655
  • 72
  • 787
  • 1,044