Getting user location every n minutes after app goes to background
To anyone else having a nightmare of a time trying to figure this one out, I have a simple solution.
- Study the example from raywenderlich.com. The sample code works perfectly, but unfortunately there's no timer during background location. This will run indefinitely.
Add timer by using this code snippet:
-(void)applicationDidEnterBackground { [self.locationManager stopUpdatingLocation]; UIApplication* app = [UIApplication sharedApplication]; bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ [app endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }]; self.timer = [NSTimer scheduledTimerWithTimeInterval:intervalBackgroundUpdate target:self.locationManager selector:@selector(startUpdatingLocation) userInfo:nil repeats:YES];}
Just don't forget to add "App registers for location updates" in info.plist.
After some days trying all possible solutions I was finally able to make it work. Here is what was wrong in my solution:
- I need to setup 2 UIBackgroundTaskIdentifiers, one for the timer, and another one for the locationManager
On my solution, just add:
UIApplication *app = [UIApplication sharedApplication];bgTask2 = [app beginBackgroundTaskWithExpirationHandler:^{ [app endBackgroundTask:bgTask2]; bgTask2 = UIBackgroundTaskInvalid; }];self.locationManager.delegate = self; [self.locationManager startUpdatingLocation];
Once you're in the background you can only have 10 minutes of additional time. There is no way to extend that. You should use the location background services instead.