NSTimer stops in the background after some time

2020-06-03 18:04发布

问题:

I used NSTimer to call a method after 1 sec when app goes in background and after nearly 17 minutes timer stops working.

When it came back in the foregound it again started working, so please tell me why this is happening and how to resolve the issue.

I also tried using perform selector with delay in recursion for the same purpose, but again giving the same result. Please suggest any solution. Any help will be completely appreciated.

回答1:

Wierd issue- i too had this one, but the following worked for me.

 //Run the timer on the runloop to ensure that it works when app is in background

  [[NSRunLoop currentRunLoop]addTimer:self.timer forMode: NSDefaultRunLoopMode];


回答2:

From Implementing Long-Running Background 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 keep users informed of their location at all times, such as a navigation app
  • Apps that support Voice over Internet Protocol (VoIP)
  • Newsstand apps that need to download and process new content
  • Apps that receive regular updates from external accessories


回答3:

If few minutes isn't enough, you can't make an app run infinite time in backgorund unless it uses:

  • Audio Playback
  • Location Services
  • External Accessory

You can use Background Tasks to get 10 minutes of running time for all other apps, or Local Notifications to notify user.