Is it possible to save the state of a timer in the User Defaults?

此生再无相见时 提交于 2019-12-11 07:06:49

问题


I have a label on which I am showing countdown timer.

Now if I close my app the timer will be off and the label's text also. I know that we can save the label's text value. But how do we show the correct countdown when the app starts again.

Suppose I close at 00:05:35 after 3 minutes when app is launched again the label should show 00:02:35 and the timer should be there for remaining countdown


回答1:


Yes, simply store the time at which your app was closed and the time left to count down in NSUserDefaults. When the app starts again you get the time it was closed from NSUserDefaults and the time left. Using the current time it's simple math calculating the corrected time left on your count down.

Something like this might do the trick, untested of course:

// save state
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSDate *now = [NSDate date];
double countDown = 45.0; // in seconds, get this from your counter
[userDefaults setObject:now forKey:@"timeAtQuit"];
[userDefaults setDouble:countDown forKey:@"countDown"];
[userDefaults synchronize];


// restore state
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
NSDate *timeAtQuit = [userDefaults objectForKey:@"timeAtQuit"];
double timeSinceQuit = [timeAtQuit timeIntervalSinceNow];
double countDown = timeSinceQuit + [userDefaults doubleForKey:@"countDown"];



回答2:


Or you could just calculate the date/time (NSDate) you want it to expire and save that in your defaults. On relaunch compare against that date to know if it has expired or if you need to set a timer to catch the future expiration.



来源:https://stackoverflow.com/questions/1587918/is-it-possible-to-save-the-state-of-a-timer-in-the-user-defaults

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!