当用户在我的应用程序后台时计时器达到 0 时,我将如何显示通知?

How would I show a notification when the timer hits 0 while the user is in the background of my app?

我有这个计时器,当 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
}

您根本不会使用计时器。您只需设置一个 user notification 作为您希望它关闭的时间。你不需要数秒。您知道何时需要发出警报。