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
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"];
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.
精彩评论