ios - Swift:计时器在前台/后台运行

标签 ios swift timer countdown background-foreground

我正在学习如何创建一个番茄钟应用程序,并且能够发送通知。但是,我完全不知道如何让我的计时器标签在重新加载应用程序时自行更新。这意味着计时器仅在应用程序打开时工作,而不是在前台/后台时工作。希望找到一个教程来学习或者只是一个快速的答案代码。谢谢!

编辑:为了消除一些误解,我的应用程序的通知与计时器一起工作正常,例如,如果选择 30 分钟,应用程序将在 30 分钟后通知用户。然而,问题是当应用程序重新打开时,它会恢复,例如计时器标签上还剩 29:57 秒,而 30 分钟应该已经过去了。

*Added in AppDelegate*
var seconds = 0 //Timer countdown seconds
var currentDate = NSDate()
var setDate: Int = 0

func pauseApp(){
    viewC.timer.invalidate() //invalidate timer
    UserDefaults.standard.set(seconds, forKey: "current") //error occurs here where "Cannot assign value of type NSDate to type Timer"
    setDate = UserDefaults.standard.integer(forKey: "current")
}
func startApp(){
    let difference = currentDate.timeIntervalSince(NSDate() as Date) as Double
    seconds = Int(Double(setDate) - difference)
    viewC.updateTimer()
}

有人从另一个线程建议取消计时器并在应用程序进入后台时存储 NSDate。他说我们可以使用此通知来检测进入后台的应用程序:

NSNotificationCenter.defaultCenter().addObserver(self, selector: "pauseApp", name: UIApplicationDidEnterBackgroundNotification, object: nil)

然后取消定时器并存储日期:

func pauseApp(){
self.stop() //invalidate timer
self.currentBackgroundDate = NSDate()

} 使用此通知检测用户回来:

 NSNotificationCenter.defaultCenter().addObserver(self, selector: "startApp", name: UIApplicationDidBecomeActiveNotification, object: nil)

然后计算存储日期与当前日期的差异,更新计数器并再次启动计时器:

func startApp(){
let difference = self.currentBackgroundDate.timeIntervalSinceDate(NSDate())
self.handler(difference) //update difference
self.start() //start timer }

但是,作为编程新手,我并不完全理解这段代码(即“处理程序”和我自己的“秒”之间的区别)...希望得到答案或有用的见解。


已解决:我设法通过这个视频自己解决了这个问题 https://www.youtube.com/watch?v=V6ta24iBNBQ 使用 timeDifference 的概念以及 UserDefaults.standard.set.... 我设法使它适应我的个人 app用代码

最佳答案

您可以调用Timer 在 View 加载时运行计时器。

var runTimer : Timer?

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    runTimer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(myFun), userInfo: nil, repeats: true)
}

func myFun(){
 //do your logic
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    runTimer?.invalidate()
}

关于ios - Swift:计时器在前台/后台运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47219760/

相关文章:

ios - 自定义 UITableViewCell 为空白(Swift)

Swift 坐标系 View

swift - 我可以使用 willSet 构造类实例字典条目吗?

javascript - jQuery/Javascript - "is not a function error"但函数已定义

java - 在 JFrame 中创建基本动画

ios - Reminders 应用程序如何知道只在提醒当天跟踪我的位置?

ios - 检测哪个 Controller 已在 Root View 中弹出

iOS:我想将 "."添加到 NSInteger 并将其显示为 NSString

c# - 如何在给定时间处理(动态添加的)项目?

ios - Swift 3.0 使用 write(toFile : atomically:) 写入二进制图像数据