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.

  1. Study the example from raywenderlich.com. The sample code works perfectly, but unfortunately there’s no timer during background location. This will run indefinitely.
  2. 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];
    }
    
  3. Just don’t forget to add “App registers for location updates” in info.plist.

Leave a Comment