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!