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
Saving Coredata to a Web Server with Swift 3.0
Solving System of Equations in Swift
How to Make a Segue to Second Item of Tab Bar
Error "No Such Module" When Installed Framework with Pod in Swift 3
Swift:Pause and Resume Nstimer
JSONserialization.JSONobject Performance in Swift
How to Cancel Firebase Setvalue While Pending for Completion (When Offline)
Color Keying Video with Gpuimage on a Scnplane in Arkit
Loading Multiple Google Interstitial Ads Makes App Crash
Appdelegate Segue Alternative Pass Data
Best Way to Structure My Firebase Database
Get Current Url from Browser in MACos
Create a Loading Image/ Activity Indicator, Until the Image Is Shown in the Screen in Swift
Sharing Highscore with Social Media
How to Use the "Handler" of Uialertaction to Call Another Uialertaction