Running a Timer in the background

好久不见. 提交于 2021-02-15 06:48:31

问题


I'm writing an app in Swift where a timer counts down, much like a countdown clock. To do this I am using this code in my main logics class:

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

Now every time I close the app, the timer stops and I get this error:

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

Is there any way to continue the timer running in the background? Or do you have any other, possibly more elegant, way to solve my problem? I have searched all over stackoverflow for this for hours now, but I can't seem to find an answer.


回答1:


Apple will not allow you to run processes for long periods of time after your app has been backgrounded. From the docs:

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.

With that said, if you're really just trying to update a "countdown clock," I would simply store the current system time (perhaps in UserDefaults) at the time the app is backgrounded. Then, when the app is brought back to the foreground, compare the stored time to the current time and perform the necessary calculations to determine what time your clock should display.



来源:https://stackoverflow.com/questions/59735217/running-a-timer-in-the-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!