Continue countdown timer when app is running in background/suspended

前端 未结 4 888
灰色年华
灰色年华 2021-01-01 04:32

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

4条回答
  •  轮回少年
    2021-01-01 05:01

    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
    }
    

    }

提交回复
热议问题