Dan Rosenstark
Dan Rosenstark

Reputation: 69777

GCD Dispatched Operation Not Running When App is Placed in Background

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.

Upvotes: 3

Views: 1314

Answers (1)

fbernardo
fbernardo

Reputation: 10124

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.

Upvotes: 5

Related Questions