Tuesday, 17 September 2013

How to run iOS Core Location in background forever

How to run iOS Core Location in background forever

I am creating a custom application for our office. I want this app to get
the user's location every 5 minutes and send it to our server via json. I
have it working however it won't run in the background longer than 10
minutes.
I have added "App registers for location updates" in Required background
modes.
My code is in the AppDelegate, like this:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSLog(@"Went to Background");
UIApplication *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
NSLog(@"Became active");
if (!_lastSentUpdateAt) {
_lastSentUpdateAt = [[NSDate date] dateByAddingTimeInterval:-24*60*60];
// Start location services
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = 100.0f;
self.locationManager.delegate = self;
[self.locationManager startUpdatingLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation
*)oldLocation
{
if ([_lastSentUpdateAt timeIntervalSinceNow] < -5 * 60) {
// Get battery level
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
float batteryLevel = [[UIDevice currentDevice] batteryLevel];
// Send data to server
float lat = newLocation.coordinate.latitude;
float lng = newLocation.coordinate.longitude;
// My code to send data to the server is here
// ....
_lastSentUpdateAt = [NSDate date];
}
}
Is there something I'm missing?

No comments:

Post a Comment