iOS Running a timer within your code in the background

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 06:58:41

问题


So I've read that in iOS, all timers will pause when your app is running in the background. I've also read that you can run tasks in the bg using beginBackgroundTaskWithExpirationHandler (like so).

What I am trying to achieve is to call a method once every 3 minutes, and another method a fixed-amount of time before the first one. I have managed to do this within one NSTimer which repeats in a way that lets me do this. It works fine but is obviously disabled (or paused) when the app is in the background - I can only assume because of the reason described above.

Does anyone know if there's a way to run a timer or at least call something after a specific amount of time so I can do this?


回答1:


Basically if you want to continue running active in the background you have to meet one of the following requirements. From the Apple docs:

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

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.

http://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html#//apple_ref/doc/uid/TP40007072-CH4-SW24



来源:https://stackoverflow.com/questions/11652834/ios-running-a-timer-within-your-code-in-the-background

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