GCD Dispatched Operation Not Running When App is Placed in Background

与世无争的帅哥 提交于 2019-12-10 19:47:46

问题


I launch a method that is, essentially, an endless loop using dispatch_queue_create and then dispatch_async (and then the code-loop is inside the dispatched block).

The loop runs perfectly. However, when the application gets backgrounded, it pauses. Then it restarts when the app takes the foreground.

How can I prevent this from happening? I've been looking here but it seems that the priority is not one of the things I can choose.


回答1:


Use the -[UIApplication beginBackgroundTaskWithExpirationHandler:] method to start a background task. The OS will give you ten minutes and call the expirationHandler block when it ends.

This method will return UIBackgroundTaskInvalid if the device can't run code in background or the task id that you must use to end it otherwise.

You can (and should) end it sooner by calling -[UIApplication endBackgroundTask];

You can probably start a task in the beginning of your block and end it when it ends, if it is a endless loop just start a task in the applicationWillResignActive method and end it on applicationDidBecomeActive. But remember, you only have ten minutes, to have more time your app would have to use location, audio, or voip.



来源:https://stackoverflow.com/questions/9812104/gcd-dispatched-operation-not-running-when-app-is-placed-in-background

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