How do I find the time interval remaining from NSTimer

不问归期 提交于 2019-12-02 10:41:06

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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!