WKInterfaceTimer is used as a timer to start and stop the countdown.

I am trying to create a timer for the countdown of x minutes and y seconds. I calculate the number of seconds and create an InterfaceTimer as follows: timer.setDate (NSDate (timeIntervalSinceNow: Two-local (secondsValue + 1))) timer.stop ()

after that, I continue to stop it and start it again and again, but the values ​​suddenly decrease, because "time (now) does not stop". For example: if the timer shows: 55, I start it for 3 seconds and stop it, it shows: 52, I wait 10 seconds, and then start it again, it starts at: 42.

I cannot save the value currently in WKInterfaceTimer, so that I could start again from the same point. Everything I tried does not work. Has anyone worked with a timer and is it left with the same value after stopping?

+6
source share
1 answer

Yes, the stopwatch timer is a little ... inconvenient ... and definitely not very intuitive. But this is just my opinion

You will need to constantly set the date / timer each time the user decides to resume the timer.

Remember that you will also need an internal NSTimer to keep track of everything, since the current WatchKit timer is simply designed to display any real logic without binding to it.

So maybe something like this ... It's not elegant. But it works

@IBOutlet weak var WKTimer: WKInterfaceTimer! //watchkit timer that the user will see var myTimer : NSTimer? //internal timer to keep track var isPaused = false //flag to determine if it is paused or not var elapsedTime : NSTimeInterval = 0.0 //time that has passed between pause/resume var startTime = NSDate() var duration : NSTimeInterval = 45.0 //arbitrary number. 45 seconds override func willActivate(){ super.willActivate() myTimer = NSTimer.scheduledTimerWithTimeInterval(duration, target: self, selector: Selector("timerDone"), userInfo: nil, repeats: false) WKTimer.setDate(NSDate(timeIntervalSinceNow: duration )) WKTimer.start() } @IBAction func pauseResumePressed() { //timer is paused. so unpause it and resume countdown if isPaused{ isPaused = false myTimer = NSTimer.scheduledTimerWithTimeInterval(duration - elapsedTime, target: self, selector: Selector("timerDone"), userInfo: nil, repeats: false) WKTimer.setDate(NSDate(timeIntervalSinceNow: duration - elapsedTime)) WKTimer.start() startTime = NSDate() pauseResumeButton.setTitle("Pause") } //pause the timer else{ isPaused = true //get how much time has passed before they paused it let paused = NSDate() elapsedTime += paused.timeIntervalSinceDate(startTime) //stop watchkit timer on the screen WKTimer.stop() //stop the ticking of the internal timer myTimer!.invalidate() //do whatever UI changes you need to pauseResumeButton.setTitle("Resume") } } func timerDone(){ //timer done counting down } 
+8
source

Source: https://habr.com/ru/post/985525/


All Articles