Timer Not Firing Every Second on Watchkit

Timer not firing every second on WatchKit

Consider using a WKInterfaceTimer label in place of the label that you are using to show the timing:

A WKInterfaceTimer object is a special type of label that displays a
countdown or count-up timer. Use a timer object to configure the
amount of time and the appearance of the timer text. When you start
the timer, WatchKit updates the displayed text automatically on the
user’s Apple Watch without further interactions from your extension.
Apple Docs.

WatchOS will then take responsibility for keeping this up-to-date. The OS handles the label for you, but you have to keep track of the elapsed time: you just need to set an NSDate to do that (see example below).

Sample Code.

In your WKInterfaceController subclass:


// Hook up a reference to the timer.
@IBOutlet var workoutTimer: WKInterfaceTimer!

// Keep track of the time the workout started.
var workoutStartTime: NSDate?

func startWorkout() {
// To count up use 0.0 or less, otherwise the timer counts down.
workoutTimer.setDate(NSDate(timeIntervalSinceNow: 0.0))
workoutTimer.start()
self.workoutStartTime = NSDate()
}

func stopWorkout() {
workoutTimer.stop()
}

func workoutSecondsElapsed() -> NSTimeInterval? {
// If the timer hasn't been started then return nil
guard let startTime = self.workoutStartTime else {
return nil
}
// Time intervals from past dates are negative, so
// multiply by -1 to get the elapsed time.
return -1.0 * self.startTime.timeIntervalSinceNow
}

Comprehensive blog entry: here.

SwiftUI, Timer: Timer not firing

I forgot the add .autoconnect() to line 3:

let timer = Timer.publish(every: 0.2, on: .main, in: .default).autoconnect()

Watch OS2 NSTimer problems

My problem is solved with Watch OS 2.1. The problem was related to a quickly movement of the wrist: with the latest update of WatchOS all the timer are correctly restore after a quick move and all works fine



Related Topics



Leave a reply



Submit