如何在ios中设置每天的倒计时器?

时间:2015-10-14 05:48:01

标签: objective-c time nsdate nstimer countdowntimer

我必须检查设备的当前时间并将countdownTimer设置为一天中的剩余时间。并在每天上午12点重置标签时间(计时器重新启动时间为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];  

}

先谢谢。

1 个答案:

答案 0 :(得分:0)

为什么不使用计时器并检查时间是否为00:00?我希望它可以提供帮助,我是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]);
}