Continue Countdown Timer in Today Extension - Swift 3

763 views Asked by At

How can I continue a timer in Today extension when the user swipes back up and closes the view? Every time I close my view, my label resets back to five minutes. The timer doesn't necessarily have to animate while the view is disappeared, but when the view loads again I would like the animation showing the updated time that passed while the view was gone to be smooth and fast. How can I keep it counting down in the background? What's the most efficient and logical way to do this? Thank you.

Here is my code thus far:

class TodayViewController: UIViewController, NCWidgetProviding {


var backgroundTaskIdentifier: UIBackgroundTaskIdentifier?
@IBOutlet weak var timerLabel: UILabel!



var counter = 300
var newCount = Int()
var timer: Timer?


override func viewDidLoad() {
    super.viewDidLoad()


    timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateInfo), userInfo: nil, repeats: true)
    RunLoop.main.add(timer!, forMode: RunLoopMode.commonModes)




}

func updateInfo(){



    let formatter = DateComponentsFormatter()
    formatter.unitsStyle = .positional
    self.timerLabel.text = formatter.string(from: TimeInterval(self.counter))
    counter -= 1
    print(counter)

}

func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {



    completionHandler(NCUpdateResult.newData)
}

override func viewDidDisappear(_ animated: Bool) {


    counter -= 1


}

}

0

There are 0 answers