Search code examples
objective-ctimensdatenstimercountdowntimer

How to set countdownTimer for each day in ios?


I have to check current time of device and set countdownTimer for the remaining time in a day.And reset label time at 12 am everyday (timer get restart as 23:59).

- (void)updateCountdown {   
    NSDate *tomorrow = [[NSUserDefaults standardUserDefaults] valueForKey:@"Date"];  
    NSTimeInterval secondsPerDay = 24 * 60 * 60;  
    NSDate *date = [tomorrow dateByAddingTimeInterval:secondsPerDay];  
    NSDate *startingDate = [NSDate date];  
    NSDate *endingDate = date;  

    NSCalendar *calendar = [NSCalendar currentCalendar];  
    NSUInteger unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;  
    NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:startingDate toDate:endingDate options:0];  

    NSInteger hours    = [dateComponents hour];  
    NSInteger minutes  = [dateComponents minute];  
    NSInteger seconds  = [dateComponents second];  
    NSString *countdownText = [NSString stringWithFormat:@" %ld Hours %ld Minutes %ld Seconds", (long)hours, (long)minutes, (long)seconds];  
    lblRemainigText.text = countdownText;  
    [self performSelector:@selector(updateCountdown) withObject:nil afterDelay:1];  

}

Thanks in Advance.


Solution

  • Why not just use a timer and check the time if it's 00:00? I hope it can help, im new at Obj-C

    //at viewdidload
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0f
                                                 target:self
                                               selector:@selector(checkTime)
                                               userInfo:nil
                                                repeats:YES];
    
    -(void)checkTime
    {
        NSCalendar* calendar = [NSCalendar currentCalendar];
        NSDateComponents* components = [calendar components:NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond fromDate:[NSDate date]]; // Get necessary date components
    
        NSInteger dateinSec = [components hour]*60 + [components minute];
        NSInteger dayEnd = 24*60-1;
        if (dateinSec == dayEnd) {
            [self resetSomething];//update when it reach 23:59:59
        }
    
        //update ur label with this
        NSLog(@"%ld h, %ld m, %ld s till restart", 24-[components hour], 60 - [components minute], 60 - [components second]);
    }