The timer does not work every second on WatchKit

This timer does not fire every second, when I check the log and user interface, it seems to fire every 3-4 seconds.

func startTimer() {
    print("start timer")
    timer = Timer.scheduledTimer(timeInterval: 1,
                                 target: self,
                                 selector: #selector(timerDidFire),
                                 userInfo: nil,
                                 repeats: true)
}

func timerDidFire(timer: Timer) {
    print("timer")
    updateLabels()
}

Is this something that will happen on Watch due to lack of features, or is something wrong in my code?

Here is the log, if necessary :

0.0396000146865845
3.99404102563858
7.97501903772354
11.9065310359001

EDIT:

And to clarify that I update every second, this is a workout timer, so it needs to be updated every second that is ticking.

+4
source share
2 answers

Consider using the WKInterfaceTimer label instead of the label you use to display time:

WKInterfaceTimer - , . . , WatchKit Apple Watch . Apple Docs.

WatchOS . , : NSDate (. ).

.

WKInterfaceController:

    // 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
    }

: .

+1

- , , , , :

, . , 5 , 5 , . , , ; .

(, ) (, ).

  • , , , .

  • , , , .

+3

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


All Articles