I have set a NSTimer.scheduledTimerWithTimeInterval
method which has an interval every 20 minutes. I want to be able to find out how much time is left when the the app goes into background mode. How do I find out how much time is left from the interval?
Thanks
You have access to a NSTimer's fireDate
, which tells you when the timer is going to fire again.
The difference between now and the fireDate
is an interval you can calculate using NSDate's timeIntervalSinceDate
API.
E.G. something like:
let fireDate = yourTimer.fireDate
let nowDate = NSDate()
let remainingTimeInterval = nowDate.timeIntervalSinceDate(fireDate)
When using the Solution of @Michael Dautermann with normal Swift type Timer
and Date
I have noticed, that his solution will give you a negative value e.g.:
let fireDate = yourTimer.fireDate
let nowDate = Date()
let remainingTimeInterval = nowDate.timeIntervalSinceDate(fireDate)
//above value is negative e.g. when the timers interval was 2 sec. and you
//check it after 0.5 secs this was -1,5 sec.
When you insert a negative value in the Timer.scheduledTimer(timeInterval:,target:,selector:,userInfo:,repeats:)
function it would lead to a timer set to 0.1 milliseconds as the Documentation of the Timer
mentions it.
So in my case I had to use the negative value of the nowDate.timeIntervalSinceDate(fireDate)
result: -nowDate.timeIntervalSinceDate(fireDate)