我必须显示从当前Date()到结束Date()的超时。 但是当应用程序处于后台时,计时器不会更新。 我尝试了BackgroundTask方法,但最多只能工作3分钟。 还有其他方法吗?
self.timer = Timer.scheduledTimer(timeInterval: 1.0, target: weakSelf, selector: #selector(self.setTimeLeft), userInfo: nil, repeats: true)
func setTimeLeft() {
let timeNow = Date()
// Only keep counting if timeEnd is bigger than timeNow
if timeEnd.compare(timeNow as Date) == ComparisonResult.orderedDescending {
let calendar = Calendar.current
let components = calendar.dateComponents([.day, .hour, .minute, .second], from: timeNow, to: timeEnd)
guard let day = components.day, let hours = components.hour,let minute = components.minute , let seconds = components.second else { return }
var dayText = String(day) + "d "
var hourText = String(hours) + "h "
// Hide day and hour if they are zero
if day <= 0 {
dayText = ""
if hours <= 0 {
hourText = ""
}
}
self.countDownTimeLabel.text = dayText + hourText + String(minute) + "m " + String(seconds) + "s"
} else {
self.countDownTimeLabel.text = "Game Over!"
}
}
答案 0 :(得分:1)
应用不会在后台持续运行,除非明确允许应用(例如音频播放器或GPS)。此外,如果应用程序在后台,用户也不会看到标签更改。
我建议在计时器间隔结束时安排本地通知。操作系统会在合适的时间将其提供给用户。
此外,将目标时间存储在NSUserDefaults中。当您的应用再次启动时,请将其与当前时间进行比较,以确定是否需要更新标签。