WatchOS2 - NSTimer in background

Hello,


I'm running into an issue where I cant keep the timer running on background (ie when the watch goes in stand-by etc)


On simulator:

The behaviour is as expect, the timer continues in the background and everything is textbook perfect


On Apple Watch:

This is based on feedback and demonstrations. The timer freezes and continues when app is in foreground.


So I'm wondering why the discrepency and how can I ensure the timer runs when the watch goes to sleep?

Hi all - bear with me, this is my first post 😝 Anyway, I was able to get an NSTimer running in the background on watchOS because I enabled a hkworkoutsession, but it seems that the timer was not firing regularly - I had a print statement in the function that the timer scheduled to be called, and the prints visibly got slower in the console when the app went to the background. I came here, but saw no answer that helped me - and then I had the idea to do this:


private func customTimer(){

if (timerRunning){

DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + .milliseconds(16)) {

self.customTimer()

}

<CODE_TO_RUN>

}

}


This recursively acts as a timer - customTimer() schedules for itself to be called again using .asyncAfter(), and then the appropriate code is executed. This therefore acts as the equivalent to a timer, but for whatever reason this, compared to an NSTimer, did not slow down even in the background - this fired as expected at all times. Therefore, when I would have otherwise scheduled an NSTimer I just call "customTimer()", and when I wanted to "invalidate" this timer, I just set "timerRunning = false", and that then ended the scheduling-chain.


Any thoughts on this solution are appreciated - and I hope that this helps someone else!

WatchOS2 - NSTimer in background
 
 
Q