Right now I have added seconds and min. in my timer. Additionally I need to add Hours month and year in my timer like below image:
Here is the code which I have implemented :
// CountDown Timer
In My view DidLoad I have initialized my variables:
currHour = 1;
currMinute= 3;
currSeconds= 00;
-(void)start {
timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
}
-(void)timerFired {
if((currHour>0 || currHour>=0) && (currMinute>0 || currSeconds>=0) && currMinute>=0) {
if(currSeconds==0) {
currMinute-=1;
currSeconds=59;
}
else if(currSeconds>0) {
currSeconds-=1;
}
if(currMinute>-1)
[self.progress setText:[NSString stringWithFormat:@"%d%@%02d %@",currMinute,@":",currSeconds,@"Sec"]];
}
else {
self.countDownView.hidden = TRUE;
[timer invalidate];
}
}
It's working till Minutes and seconds.
Thanks in advance.
Add to viewDidLoad next code and save target date as property or ivar
NSTimeInterval currentDateSeconds = [[NSDate date] timeIntervalSince1970];
NSTimeInterval targetDateSeconds = currentDateSeconds + [self secondsInDay:0 hour:1 min:3 sec:0];
targetDate = [NSDate dateWithTimeIntervalSince1970:targetDateSeconds];
then add method for convert target date to seconds, e.g. in your example is 1 hour 3 min
- (NSTimeInterval) secondsInDay: (int) day hour:(int)hour min:(int)min sec: (int)sec {
NSTimeInterval secondsInOneDay = 24 * 60 * 60;
return day * secondsInOneDay + hour * 60 * 60 + min * 60 + sec; }
then use next timeFired
method:
-(void)timerFired {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *dateComponents = [calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond) fromDate:[NSDate date] toDate:targetDate options:0];
NSInteger year = dateComponents.year;
NSInteger month = dateComponents.month;
NSInteger day = dateComponents.day;
NSInteger minute = dateComponents.minute;
NSInteger second = dateComponents.second;
if(year == 0 &&
month == 0 &&
day == 0 &&
minute == 0 &&
second == 0) {
NSLog(@"FINISH");
[timer invalidate];
} else {
NSLog(@"%@", [NSString stringWithFormat:@"%d%@%02d %@",minute,@":",second,@"Sec"]);
}}