views:

160

answers:

2

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

+6  A: 

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"];
Jens Utbult
http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/UserDefaults/UserDefaults.html and http://developer.apple.com/mac/library/documentation/Cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html will probably be helpful to read.
Jens Utbult
can you post a sample code
Rahul Vyas
I added some sample code to the answer.
Jens Utbult
thank you so much
Rahul Vyas
+1  A: 

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.

geowar