Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

ios - Running a Timer in the background

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...