【发布时间】:2021-10-08 21:16:51
【问题描述】:
我有这个计时器,当 10 分钟结束时,我想在用户处于后台时显示通知。我遇到的问题是当应用程序在后台时,通知在 10 分钟后永远不会被调用。离开应用程序后,我可以让计时器倒计时,但是一旦计时器达到 0,就无法调用通知函数。任何帮助将不胜感激。谢谢!
var timeCount2:TimeInterval = 600 //seconds
var timer: Timer!
override func didMove(to view: SKView) {
backgroundTimer() // timer begins to countdown here
NotificationCenter.default.addObserver(self, selector: #selector(enterForeground), name: UIApplication.didBecomeActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(enterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
}
func backgroundTimer() {
var bgTask = UIBackgroundTaskIdentifier(rawValue: 0)
bgTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
UIApplication.shared.endBackgroundTask(bgTask)
})
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateStopWatch4), userInfo: nil, repeats: true)
RunLoop.current.add(timer, forMode: .default)
}
var fgTime = Int()
var backgroundTime = Int()
@objc func enterForeground(){
///initial time
let foregroundTime = self.currentBackgroundDate.timeIntervalSince(NSDate() as Date)
///turns foreground timer to integer
fgTime = Int(foregroundTime)
///subtracts the bg from fg
let diffrence = backgroundTime - fgTime
///once returned to app the timer will be updated
timeCount2 -= Double(diffrence)
print("This is the seconds off when first leaving app and then entering \(diffrence)")
}
@objc func enterBackground(){
let bgTime = currentBackgroundDate.timeIntervalSinceNow
backgroundTime = Int(bgTime) // turns to integer
print("app is in the background")
}
func timeStringForScore4(_ time:TimeInterval) -> String {
let minutes = Int(time) / 60 % 60
let seconds = Int(time) % 60
return String(format:"%02i %02i", minutes, seconds)
}
@objc func updateStopWatch4() {
self.timeCount2 -= 1
playTimer.text = timeStringForScore4(timeCount2)
if timeCount2 == 0 {
callNotification() //shows notification in background when timer hits 0
}
【问题讨论】:
-
为了让 jnpdx 的回答更清楚一点:你根本不会使用计时器。您只需为您希望它关闭的时间设置一个用户通知。你不需要数秒。您知道何时需要发出警报。
-
好的,谢谢!
-
@RobNapier,您应该发布您的回复作为答案。我打算在回答中说同样的话,但你打败了我。由于您是第一个明确说明的人,因此您应该发布规范的答案。
-
@DuncanC 同意。添加为答案。