Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS HTTP request while in background

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.

like image 276
Alexandru Circus Avatar asked Aug 08 '12 12:08

Alexandru Circus


2 Answers

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];
    }
}
like image 126
vakio Avatar answered Oct 12 '22 02:10

vakio


These links will help you out...

iphone - Connecting to server in background

like image 39
alloc_iNit Avatar answered Oct 12 '22 04:10

alloc_iNit