当用户向上滑动并关闭视图时,如何在Today扩展中继续计时器?每当我关闭视图时,我的标签都会重置为五分钟。当视图消失时,计时器不一定必须设置动画,但是当视图再次加载时,我希望动画显示在视图消失时通过的更新时间平滑且快速。我怎样才能让它在后台倒计时?这样做的最有效和最合理的方法是什么?谢谢。
到目前为止,这是我的代码:
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
}
}