运行 后台计时器

Running a Timer in the background

我正在 Swift 中编写一个应用程序,其中的计时器倒计时,很像倒计时时钟。为此,我在我的主要逻辑中使用了这段代码 class:

func start() {
    self.timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
        self.run()
    }
}

现在每次我关闭应用程序时,计时器都会停止并且我会收到此错误消息:

BackgroundTask: no background task exists with identifier 1 (0x1), or it may have already been ended.

有什么办法可以在后台继续计时运行?或者您有任何其他可能更优雅的方法来解决我的问题吗?我已经在整个 Whosebug 上搜索了几个小时,但我似乎找不到答案。

Apple 不允许您 运行 在您的应用进入后台后的很长一段时间内进行处理。来自文档:

Implementing Long-Running Tasks

For tasks that require more execution time to implement, you must request specific permissions to run them in the background without their being suspended. In iOS, only specific app types are allowed to run in the background:

  • Apps that play audible content to the user while in the background, such as a music player app
  • Apps that record audio content while in the background
  • Apps that keep users informed of their location at all times, such as a navigation app
  • Apps that support Voice over Internet Protocol (VoIP)
  • Apps that need to download and process new content regularly
  • Apps that receive regular updates from external accessories
  • Apps that implement these services must declare the services they support and use system frameworks to implement the relevant aspects of those services.

Declaring the services lets the system know which services you use, but in some cases it is the system frameworks that actually prevent your application from being suspended.

话虽如此,如果您真的只是想更新 "countdown clock,",我会在应用后台运行时简单地存储当前系统时间(可能在 UserDefaults 中)。然后,当应用程序返回前台时,将存储的时间与当前时间进行比较,并执行必要的计算以确定您的时钟应该显示的时间。