i have a uilabel and a uislider on a view. i want to set label's time using slider.range of slider is 00:00:00 to 03:00:00. means 3 hours.and intervel on slider is 0.5 minutes.also how to show.i want the timer runs even if application is closed.
3 Answers
First off, there's no way to keep the timer running after your app is closed. Background apps simply aren't allowed on the iPhone. There are ways to fake it with a timer (save a timestamp when the app exits, and check it against the time when it starts back up), but it won't handle the case where your timer runs out before the app is started back up.
As for updating the UILabel with the countdown, a NSTimer would probably work. Something like this, assuming you have a NSTimer timer, an int secondsLeft, and a UILabel countdownLabel in your class:
Create the timer:
timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];
The updateCountdown method:
-(void) updateCountdown {
int hours, minutes, seconds;
secondsLeft--;
hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}
I do something similar in one of my apps, but don't have the code handy right now.

- 1,986
- 1
- 15
- 16
-
what is the value of secondsLeft. – Rahul Vyas Oct 06 '09 at 15:30
-
That would be the number of seconds you want the timer to run for, most likely setup else where based on the value of the UISlider. – Shawn Craver Oct 06 '09 at 17:41
-
as shawn said, you can't keep the timer running after the app is closed, so make sure to keep track of the start time when your app sends the UIApplicationWillTerminateNotification (i think that's it, i'm rusty). The only workaround to a timer running out when the app isn't running is to use push notification. but that can get pricey. – pxl Oct 06 '09 at 20:39
-
Thanks Shawn! Got a question, how to kill the timer? thanks again. – drexsien Sep 20 '11 at 04:29
-
1If you invalidate the timer, it will stop it. – Shawn Craver Sep 22 '11 at 16:48
-
anyone have any idea how would you apply this with days as well ? – Charlton Provatas Feb 01 '17 at 16:56
This code is wrong.
timer = [NSTimer scheduledTimerWithInterval: 1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];
It should be.
timer = [NSTimer scheduledTimerWithTimeInterval: 1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];

- 281
- 3
- 10
you can keep your timer running when your application did enters background ,
as @shawn craver told u you cant do this but you can do this when application enters into background ("not terminates") which is a different event applicationDidEnterBackground and with that you will need some multithreading GCD(grand central dispatch).
plase refer this link