如何在iOS上设置长时间运行的计时器



我想创建一个计时器,应该每小时触发一次。但根据我的研究,一个应用程序在后台运行10分钟后就会暂停。在屏幕被锁定后,应用程序似乎也会暂停。

我想每1小时触发一次这个定时器。当应用程序进入后台时,我将使计时器失效,并在应用程序前台时重新启动它。所以我有几个问题:

  1. 当用户退出应用程序并返回它时,计时器是否会立即触发,如果它已经超过1小时?
  2. 如果用户在多个(2+)小时后返回应用程序,计时器会触发多次吗?

是否有任何建议的方法来设置这种长时间运行的计时器,使它们更一致地触发,而不仅仅是一次,当他们被设置?

你可以这样做,而不使用后台定时器。这只是你如何实现你的要求的想法,根据你的要求添加一个或多个小时的条件。

var totalTime = Double()
override func viewDidLoad() {
super.viewDidLoad()
// MARK: - To Reset timer's sec if app is in background and foreground
NotificationCenter.default.addObserver(self, selector: #selector(self.background(_:)), name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.foreground(_:)), name: UIApplication.willEnterForegroundNotification, object: nil)
}
@objc func background(_ notification: Notification) {
if self.totalTime > 0{
user_default.setValue(self.totalTime, forKey: "TotalSecInBackground")
user_default.setValue(Date().timeIntervalSince1970, forKey: "OldTimeStamp")
LogInfo("total seconds left in background: (self.totalTime)")
}
}
@objc func foreground(_ notification: Notification) {
let timerValue: TimeInterval = user_default.value(forKey: "TotalSecInBackground") as? TimeInterval ?? 0
let otpTimeStamp = user_default.value(forKey: "OldTimeStamp") as? TimeInterval ?? 0
let timeDiff = Date().timeIntervalSince1970 - otpTimeStamp
if timerValue > timeDiff{
LogInfo("total second & timeDiff:, (Int(timerValue)),(Int(timeDiff))")
let timeLeft = timerValue - timeDiff
self.totalTime = Int(timeLeft)
LogInfo("timeLeft: (Int(timeLeft))") // <- This is what you need
}}

最新更新