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
We calculate the remaining time by the following steps: Subtract "Temporary Real" from 20 min and store as "Time Until Done" This seems like a lot of steps to calculate and display the remaining time in a timer.
NSTimer is toll-free bridged with its Core Foundation counterpart, CFRunLoopTimerRef. See Toll-Free Bridging for more information. You specify whether a timer is repeating or nonrepeating at creation time. A nonrepeating timer fires once and then invalidates itself automatically, thereby preventing the timer from firing again.
A repeating timer always schedules itself based on the scheduled firing time, as opposed to the actual firing time. For example, if a timer is scheduled to fire at a particular time and every 5 seconds after that, the scheduled firing time will always fall on the original 5-second time intervals, even if the actual firing time gets delayed.
A timer that fires after a certain time interval has elapsed, sending a specified message to a target object. Timers work in conjunction with run loops. Run loops maintain strong references to their timers, so you don’t have to maintain your own strong reference to a timer after you have added it to a run loop.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With