Reputation: 169
Let's say I have a variable named number
var number: Int = 100
If I have an NSTimer that takes one of the number variable every second, and the user closes the app for... 20 seconds, when the user comes back onto the app, how am I able to get the new number variable after it has been running in the background for 20 seconds?
Upvotes: 0
Views: 76
Reputation: 100652
Just base it on the absolute time, not on a local recounting. If you need the ticks (e.g. to update an on-screen counter) then:
var timer: NSTimer?
var timerStartTime: NSTimeInterval = 0.0
func startTimer() {
timer = NSTimer(... to call myself every second ...)
timerStartTime = NSDate.timeIntervalSinceReferenceDate()
}
func timerCallback(timer: NSTimer!) {
let timeSinceTimerBegan = NSDate.timeIntervalSinceReferenceDate() - timerStartTime
print("It has now been \(timeSinceTimerBegan) seconds since timing began;
counter should be at \(100 - timeSinceTimerBegan)")
}
Upvotes: 1