22

It is possible to make HTTP async requests to PHP server while the app being in background? The app is a location based one, and should gather current location and send the coordinates to server every 5(or other value) minutes. Can I make the http posts to the server even the app is in background? I read lot of thoughts about this, but some of them told that can be done, others that can't be done.

Thanks,

Alex.

Alexandru Circus
  • 5,478
  • 7
  • 52
  • 89
  • 2
    First off, never try and collect the location on a fixed times. This will drain the battery. Just start listing to major location changes and if these occur then send the new location to the server. If you need a more accurate location start the GPS when the major location change occurs and stop the GPS when you have the location accurate enough for your requirements. Then send the data to the server. – rckoenes Aug 08 '12 at 12:40
  • 3
    This is the way I done it, I start the update locations, get the location, stop location update, send the request to server, start again location update after 5 minutes, get location, stop, etc. The question is am I able to send the request if the app is in background mode? Thank you. – Alexandru Circus Aug 08 '12 at 12:45

2 Answers2

25

It can be done but it is unreliable because you ask the OS for time to send something and it can accept or deny your request. This is what I have (stolen from somewhere on SO):

[...] //we get the new location from CLLocationManager somewhere here    
BOOL isInBackground = NO;
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
{
    isInBackground = YES;
}
if (isInBackground)
{
    [self sendBackgroundLocationToServer:newLocation];
}


- (void) sendBackgroundLocationToServer: (CLLocation *) lc
{
    UIBackgroundTaskIdentifier bgTask = UIBackgroundTaskInvalid;
    bgTask = [[UIApplication sharedApplication]
         beginBackgroundTaskWithExpirationHandler:^{
             [[UIApplication sharedApplication] endBackgroundTask:bgTask];
    }];

    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:2];
    [dictionary setObject:[NSNumber numberWithDouble:lc.coordinate.latitude] forKey:@"floLatitude"];
    [dictionary setObject:[NSNumber numberWithDouble:lc.coordinate.longitude] forKey:@"floLongitude"];
    // send to server with a synchronous request


    // AFTER ALL THE UPDATES, close the task
    if (bgTask != UIBackgroundTaskInvalid)
    {
        [[UIApplication sharedApplication] endBackgroundTask:bgTask];
    }
}
vakio
  • 3,134
  • 1
  • 22
  • 46
4

These links will help you out...

iphone - Connecting to server in background

Community
  • 1
  • 1
alloc_iNit
  • 5,173
  • 2
  • 26
  • 54
  • Thanks, is what vakio suggested, but without code :d . I think beginBackgroundTaskWithExpirationHandler method will solve my problem. – Alexandru Circus Aug 08 '12 at 12:54