Run timer in 'background' when app is clos

2019-01-20 04:28发布

问题:

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?

回答1:

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.



标签: ios nstimer