I have a functional countdown timer.
The problem is that I need to continue the countdown when the user puts the app in the background. Or suspends the app? I am no
Try this instead.. this code updates the time when app comes back from background/suspend and in active state..
class ProgressV: UIView {
var timer: NSTimer!
var expirationDate = NSDate()
//Set the time that you want to decrease..
var numSeconds: NSTimeInterval = 36000.0 // Ex:10:00 hrs
func startTimer()
{
// then set time interval to expirationDate…
expirationDate = NSDate(timeIntervalSinceNow: numSeconds)
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(updateUI(_:)), userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(timer, forMode: NSRunLoopCommonModes)
}
func updateUI(timer: NSTimer)
{
// Call the currentTimeString method which can decrease the time..
let timeString = currentTimeString()
labelName.text = timeString
}
func currentTimeString() -> String {
let unitFlags: NSCalendarUnit = [.Hour, .Minute, .Second]
let countdown: NSDateComponents = NSCalendar.currentCalendar().components(unitFlags, fromDate: NSDate(), toDate: expirationDate, options: [])
var timeRemaining: String
if countdown.hour > 0
{
timeRemaining = String(format: "%02d:%02d:%02d", countdown.hour, countdown.minute, countdown.second)
}
else {
timeRemaining = String(format: "%02d:%02d:%02d", countdown.hour, countdown.minute, countdown.second)
}
return timeRemaining
}
}