How to continue the countdown timer after closing ViewController

拥有回忆 提交于 2019-12-12 06:14:51

问题


I use UIDatePicker to implement a countdown timer.After loading viewdatePickerMode set CountDownTimer:

- (void)viewDidLoad {
[super viewDidLoad];
self.countDownTimer.datePickerMode=UIDatePickerModeCountDownTimer;
}

First,set the countdown time in UIDatePicker,then press the button to start the countdown:

- (IBAction)StartCountdown:(id)sender {
    [sender setTitle:@"Cancel" forState:UIControlStateNormal];
    countDownInterval = (NSTimeInterval)countDownTimer.countDownDuration;
    remainder = countDownInterval;
    afterRemainder = countDownInterval - remainder % 60 ;
    //call updateCountDown()
    timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateCountDown) userInfo:nil repeats:YES];
}

call updateCountDown():

-(void)updateCountDown{
    afterRemainder --;
    int hours = (int)(afterRemainder/(60*60));
    int mins = (int)(((int)afterRemainder/60)-(hours * 60));
    int secs = (int)(((int)afterRemainder - (60 * mins) - (60 * hours *60)));
    NSString *displayText = [[NSString alloc]initWithFormat:@"%02u : %02u : %02u",hours,mins,secs];
    self.displayLabel.text = displayText;
}

Action can execute properly, but when I jump out of this view and will not perform timer is zero, how do I operate the timer can be sustained after the jump view?


回答1:


I think you can do:

  1. When you jump out the view, let save state at this time to NSUserDefaults
    • The remain time, maybe in seconds
    • The current system time at that time, exam: 13:20:15
  2. When you open the view again:
    • Get current system time, sub it with saved system time (A)
    • Sub saved remain time (in seconds) with (A) and continue to countdown.

Just a idea, but hope it helps




回答2:


  1. The best and clean way to create a singleton class and declare your timer inside as a property inside it . so there is only one instance of the timer object throughout the application .

  2. Another way is to declare timer in the app delegate class which also holds the object throughout the application



来源:https://stackoverflow.com/questions/31200859/how-to-continue-the-countdown-timer-after-closing-viewcontroller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!