简体   繁体   English

Swift:如何在后台运行计时器

[英]Swift: How to run timer in background

I have added an observer to my app that listens when the app goes into background mode.我在我的应用程序中添加了一个观察者,它在应用程序进入后台模式时进行监听。 I did that through this command: NotificationCenter.default.addObserver(self, selector: #selector(enterBackground), name: UIApplication.willResignActiveNotification, object: nil)我通过这个命令做到了: NotificationCenter.default.addObserver(self, selector: #selector(enterBackground), name: UIApplication.willResignActiveNotification, object: nil)

Now I want my selector to run a timer.scheduled in the background.现在我希望我的选择器在后台运行 timer.scheduled。 My code Looks like:我的代码看起来像:

   @objc func enterBackground() {
       Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (timer) in
           print(self.secondsCount)
           self.secondsCount -= 1
       }
   }

But the timer doesn´t print my print commands every second.但是计时器不会每秒打印我的打印命令。 Just once.就一次。

Does somebody know how to do that?有人知道该怎么做吗? Warm greetins!热烈的问候!

AND NO!和不! THIS ISN'T A DUPLICATE I READ A LOT OF ANSWERS AND QUESTIONS BUT I DID'T GET ANSWER FOR ME!这不是重复我阅读了很多答案和问题,但我没有得到答案!

The short answer is that you can't have a timer running while your app is in the background.简短的回答是,当您的应用程序在后台时,您不能运行计时器。 Your app gets "suspended" (stops getting CPU time) almost immediately after the user switches to another app.在用户切换到另一个应用程序后,您的应用程序几乎立即“暂停”(停止获取 CPU 时间)。 Apple does this both to conserve battery and to make the front-most app more responsive. Apple 这样做既是为了节省电池电量,也是为了让最前面的应用程序更具响应性。 Only a limited number of app types are allowed to run in the background for more than a few minutes (eg music players, turn-by-turn navigation apps, VoIP apps.)仅允许有限数量的应用程序类型在后台运行超过几分钟(例如音乐播放器、逐向导航应用程序、VoIP 应用程序。)

If you need to track the amount of time elapsed since some event, you should save the Date at the time the event occurs.如果您需要跟踪某个事件后经过的时间量,您应该保存事件发生时的日期。 While your app is in the foreground, run a timer and when it goes off, subtract the current Date from the saved Date to get elapsed time.当您的应用程序处于前台时,运行一个计时器,当它关闭时,从保存的Date中减去当前Date以获得经过的时间。

When you get notified that you are going to the background, stop your timer.当您收到通知您要进入后台时,请停止计时器。

When you return to the foreground, restart your timer so that it recalculates the amount of time elapsed.当您返回前台时,重新启动计时器,以便它重新计算经过的时间量。

PS This is a duplicate. PS这重复的。 The answer to this and all other "how can I run a timer while I'm in the background" questions is "You can't."这个问题和所有其他“我如何在后台运行计时器”问题的答案是“你不能”。 I provided an individual answer rather than just closing it as a duplicate in order to explain why you can't solve your problem the way you are attempting to我提供了一个单独的答案,而不是仅仅将其作为副本关闭,以解释为什么您无法以您尝试的方式解决问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM