Fire Fist
Fire Fist

Reputation: 7060

Timer Count Down with UIDatePicker in iOS

In my app , i let user to set Count Down timer with UIDatePicker's CountDownTimer.

I have one UILabel to show count time When user choose time from CountDownTimer, i want to show coumt down that user chosen in CoutDownTimer like following pic.

enter image description here

So i retrieve count time that user chosen from CountDownTimer with following code

self.dateFormatter = [[NSDateFormatter alloc] init];
[self.dateFormatter setDateFormat:@"HH:mm:ss"];

self.sleepTimer = [NSTimer timerWithTimeInterval:1.00 target:self selector:@selector(timerFired:) userInfo:nil repeats:NO];

When it reach 00:00 , i want to fire a event.

I don't know how to reduce every second count down.

Thanks you for your help.

Upvotes: 1

Views: 1306

Answers (3)

Mattias
Mattias

Reputation: 2306

Save the countDownDuration property of your UIDatePicker (the value is given in seconds) in an instance variable called something like secondsLeft.

self.sleepTimer = [NSTimer scheduledTimerWithTimeInterval:1.00 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];

That will call your method timerFired: every second. Subtract secondsLeft by 1. Update your UILabel with the time left (format your seconds into hh:mm:ss - See this question on formatting). Validate if there is time left on the count down and take the appropriate action if the count down is complete (secondsLeft <= 0).

Remember to clean up once the countdown is complete;

[self.sleepTimer invalidate];
self.sleepTimer = nil;

Upvotes: 2

Anoop Vaidya
Anoop Vaidya

Reputation: 46543

You can do it by :

[NSTimer timerWithTimeInterval:1.00 target:self selector:@selector(decrementByOne:) userInfo:nil repeats:YES];

Upvotes: 3

Alexander
Alexander

Reputation: 7238

Take your date, save it into a property and take a look at NSDates

– dateByAddingTimeInterval:

So if you do

[self.date dateByAddingTimeInterval:-1];

you will decrement your date by 1 Second. After that, update you UI with the new calculated date.

Further you could package all the code in one function and execute this function by calling:

performSelector:withObject:afterDelay: 

Upvotes: 0

Related Questions