Search code examples
swiftnstimernstimeinterval

How do I find the time interval remaining from NSTimer


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


Solution

  • 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)