I've an app that capture user location and send this info to my server.
I've started the LocationManager service with:
- (CLLocationManager *)locationManager {
if (_locationManager == nil) {
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
isUpdatingLocation = NO;
}
return _locationManager;
}
-(void) startLookingForLocation{
[self locationManager].desiredAccuracy = kCLLocationAccuracyBest;
[self locationManager].distanceFilter = 250;
if([[self locationManager]respondsToSelector:@selector(setPausesLocationUpdatesAutomatically:)])
[[self locationManager] setPausesLocationUpdatesAutomatically:YES];
if([[self locationManager]respondsToSelector:@selector(setActivityType:) ])
[[self locationManager] setActivityType:CLActivityTypeFitness];
[[self locationManager] startUpdatingLocation];
[[self locationManager] startUpdatingHeading];
isUpdatingLocation = YES;
}
and stopping it with:
-(void) stopLookingForLocation{
[[self locationManager] stopUpdatingLocation];
[[self locationManager] stopUpdatingHeading];
isUpdatingLocation = NO;
}
So, when I detect a change of user location:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
[self setCurrentLocation:newLocation];
BOOL isInBackground = NO;
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
{
isInBackground = YES;
}
if (isInBackground)
{
UIBackgroundTaskIdentifier bgTask = [[UIApplication sharedApplication]
beginBackgroundTaskWithExpirationHandler:
^{
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
}];
// Send user-location to my server
if (bgTask != UIBackgroundTaskInvalid)
{
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
}
else
{
// Send user-location to my server
}
}
and all works correctly. (I suppose).
When app go into background mode, I invoke this method within appDelegate - (void)applicationDidEnterBackground:(UIApplication *)application { [locationManager startMonitoringSignificantLocationChanges]; }
and when app return to foreground:
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[locationManager stopMonitoringSignificantLocationChanges];
}
But I have some doubts. In this way, if app is in closed status, my app continues to comunicate location to server?
How I can send location only when I'm in background or foreground status?
EDIT: I've also set:
UIBackgroundModes location