【问题标题】:How to allow CountDownTimer to continue running by using NSUserDefaults如何使用 NSUserDefaults 让 CountDownTimer 继续运行
【发布时间】:2015-05-01 22:52:14
【问题描述】:

我想倒计时 23 小时。我的代码可以完美地倒计时,但是当我退出应用程序或切换到应用程序中的另一个视图控制器/页面时它不起作用

即使应用程序已关闭并使用 NSUserDefaults 切换到另一个视图控制器,我也希望它运行

请帮忙,如果需要,我可以提供更多代码

-(void) timerRun {


    secondCount = secondCount - 1;
    int hours = (secondCount/ 3600) % 24;
    int minuts = (secondCount / 60) % 60;
    int seconds = secondCount % 60;


    NSString *timerOutput = [NSString stringWithFormat:@"%2d:%.2d:%2d", hours, minuts, seconds];

    countdownLabel.text = timerOutput;

    if (secondCount == 0) {
        [countdownTimer invalidate];
        countdownTimer = nil;

    }

}

-(void) setTimer {

    secondCount = 82800;
    countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerRun) userInfo:nil repeats:YES];



}


- (IBAction)start:(id)sender {



    [self setTimer];





}

【问题讨论】:

    标签: objective-c nstimer countdown countdowntimer


    【解决方案1】:

    尝试在runloop中添加countdownTimer:

    -(void) setTimer 
    {
        secondCount = 82800;
        countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self
        selector:@selector(timerRun) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:countdownTimer forMode:NSRunLoopCommonModes];
    }
    
    • 如果您手动关闭该应用程序,您的主运行循环将停止运行,您的计时器也将停止运行。
    • 如果应用程序在后台,它将工作大约 10 分钟,除非您启用了某些后台模式。 (地点)
    • 请注意以防您的选择器被调用并且您的视图控制器目标已被破坏。

    【讨论】:

    • 感谢您的回答。它在后台工作,但我也需要它在转到另一个视图控制器后工作
    • @Katie 如果你回到同一个实例,它应该在你从另一个控制器回来后继续工作。
    • 你是否在 viewwillappear 中初始化定时器?
    • 另外,在“-(void) dealloc”中设置一个断点,并在转到另一个视图控制器时检查视图控制器是否已被破坏。
    • 没有。我没有 viewwillappear 和 -(void) dealloc。请告诉我该怎么做。
    【解决方案2】:

    您应该存储倒计时结束时间而不是秒数。您可以通过计算当前日期加上秒数来获得结束时间。

    将结束时间存储在 NSUserDefaults 中。

    您的视图控制器可以加载此值并重置计时器以更新标签。

    此外,通过将结束时间存储在 NSUserDefaults 中,您将在应用再次启动时获得此值。您还可以设置 UILocalNotification 让用户知道倒计时已经结束。

    【讨论】:

    • 非常明确的答案,您能否提供我的代码,因为我是新手?
    • 你能给我提供代码吗? @bbarnhart
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 2019-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多