How do I find the time interval remaining from NSTimer

时间秒杀一切 提交于 2019-12-02 16:23:03

问题


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


回答1:


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)



回答2:


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)



来源:https://stackoverflow.com/questions/33198225/how-do-i-find-the-time-interval-remaining-from-nstimer

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