how can I run the iOS4 app in the background?


I'm developing an app for iOS4. The application is made of two main components, one that is supposed to run in the background and one that is constantly displayed on screen and takes data from the first one. Here's the problem: the first component works just fine until it is put in the background. At that point it stops sending data. Why is that? Is there any workaround?

Thank you.

If you're not using VoIP, Audio or GPS you can only use the task completion mode (which is limited to 10 minutes in background). To do that you have to tell the OS you want to start a task with:

UIApplication*    app = [UIApplication sharedApplication];

UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
    [app endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;

and when you're done, you can end it with:

[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;

Remember that if your running longer than 10 minutes, the OS will kill your app.

In applicationDidEnterBackground: you have the problem that your code still blocks the main thread, which is why it's killed when you exit the app.

If you want to start executing code in applicationDidEnterBackground: you should begin the background task and dispatch whatever it is you want to do with dispatch_async(queue, block_with_your_code);

You can read more on it here