Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

ios - Run timer in 'background' when app is closed

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...