gpt4 book ai didi

ios - 倒计时器如何在后台工作

转载 作者:行者123 更新时间:2023-11-29 05:41:29 25 4
gpt4 key购买 nike

我想在应用程序进入后台并重新打开时更新计数器。

首先,我在 viewWillAppear 中添加了两个观察者,如下所示

    NotificationCenter.default.addObserver(self, selector: #selector(pauseApp1), name: UIApplication.didEnterBackgroundNotification, object: nil)

NotificationCenter.default.addObserver(self, selector: #selector(startApp1), name: UIApplication.didBecomeActiveNotification, object: nil)

但是当应用程序第一次打开时,倒计时器立即计数为-1、-2。除此之外,我无法按照我想要的方式更新标签。

 @IBOutlet weak var timeDurationLabel: UILabel!

var timer = Timer()
var audioPlayer = AVAudioPlayer()

var remainder: Int = 0
var timeDuration: Int = 0
var countdownInterval: TimeInterval = 0.0

var currentBackgroundDate = Date()

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(pauseApp1), name: UIApplication.didEnterBackgroundNotification, object: nil)

NotificationCenter.default.addObserver(self, selector: #selector(startApp1), name: UIApplication.didBecomeActiveNotification, object: nil)
}

@objc func pauseApp1() {
timer.invalidate()
currentBackgroundDate = Date()
}

@objc func startApp1() {
let difference = self.currentBackgroundDate.timeIntervalSince(Date())
timeDuration = timeDuration + Int(difference)
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCountdown), userInfo: nil, repeats: true)

}

@IBAction func startButtonTapped(_ sender: UIButton) {
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCountdown), userInfo: nil, repeats: true)

self.timeDuration = Int(self.countdownInterval) - (self.remainder % 60)

self.startButton.initActionBtn(colorType: .gray, title: "START")
self.coundownPickerButton.isEnabled = false

self.circularProgress.animate(fromAngle: 0, toAngle: 360, duration: TimeInterval(timeDuration)) {
completed in
if completed {
print("animation stopped, completed")
}
else {
print("animation stopped, was interrupted")
}
}
}

@objc func updateCountdown() {
self.timeDuration -= 1
self.timeDurationLabel.text = timeFormatted(timeDuration)

if timeDuration == 0 {
timer.invalidate()

self.audioPlayer.play()

self.startButton.initActionBtn(colorType: .green, title: "START")
}
}

最佳答案

当你说:

let difference = self.currentBackgroundDate.timeIntervalSince(Date())

这将产生一个负值,因为您要求的是从现在到设置当前背景日期的时间间隔。如果您想要一个正数,您应该使用:

let difference = Date().timeIntervalSince(self.currentBackgroundDate)

关于ios - 倒计时器如何在后台工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56509940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com