Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can iphone app woken in background for significant location change do network activity?

I'm working on an app that monitors significant location changes in the background. I've been reading all the answers (well, I think all!) about ios4 and the application lifecycle, but what I can't figure out is whether or not I can do any network access when the app is woken up in the background as a result of a significant location change.

The app currently does network access via TCP sockets. The socket is shutdown when the app is suspended.

Can I re-connect the socket, receive some data, send the new location and then shutdown the socket all while still in the background as a result of receiving the location change event? It's hard to test while stationary in the office! We can assume that the network activity takes less than 10 seconds to complete. Also assume the app isn't registered as a voip app (could/should it be? ...)

Any ideas?

like image 615
Roger Avatar asked Mar 22 '11 16:03

Roger


2 Answers

Yep. You can do your network processing based on significant change events.

When you get woken up into the background state on significant change (from terminated or suspended state), you can make your http request. If you find your app is being terminated before you finish your HTTP request, you can ask for additional background processing time via the beginBackgroundTaskWithExpirationHandler: method on UIApplication.

I spent a fair bit of time on short train trips to test this out. :)

like image 59
RedBlueThing Avatar answered Nov 01 '22 12:11

RedBlueThing


I'd just like to confirm RedBlueThing's answer with some detail.

I now use the following to accomplish this. bgTask is declared as UIBackgroundTaskIdentifier

bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:
           ^{
                 [[UIApplication sharedApplication] endBackgroundTask:bgTask];
            }];

// Now call methods doing network activity
// ...
// WHEN I KNOW THE LAST ACTION HAS COMPLETED USE THIS BLOCK OF CODE

if (bgTask != UIBackgroundTaskInvalid)
{
      [[UIApplication sharedApplication] endBackgroundTask:bgTask];
      bgTask = UIBackgroundTaskInvalid;
}

Hope this helps out since I see quite a few people looking at the question.

like image 26
Roger Avatar answered Nov 01 '22 12:11

Roger