I am trying to enable background location mode in my application. I have enabled 'Location updates' background mode in my plist file. The app contains a timer that is updating every 15 seconds.
When the app is navigating to background, I am doing the following
- (void)applicationDidEnterBackground:(UIApplication *)application {
UIApplication* app = [UIApplication sharedApplication];
self.bgTaskID = [app beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"background task %lu expired", (unsigned long)self.bgTaskID);
[app endBackgroundTask:self.bgTaskID];
self.bgTaskID = UIBackgroundTaskInvalid;
}];
[NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(initializeLocationManager) userInfo:nil repeats:NO];
if(self.timerLocationBackground)
{
[self.timerLocationBackground invalidate];
self.timerLocationBackground = nil;
}
self.timerLocationBackground = [NSTimer scheduledTimerWithTimeInterval:15
target:self
selector:@selector(initializeLocationManager)
userInfo:nil
repeats:YES];}`
The initializeLocationManager is below
-(void)initializeLocationManager
{
if(!self.locationManager)
self.locationManager = [[CLLocationManager alloc] init];
else
[self.locationManager stopUpdatingLocation];
if ((![CLLocationManager locationServicesEnabled])
|| ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusRestricted)
|| ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied))
{
//user has disabled his location
}
else
{
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = kCLDistanceFilterNone;
[self.locationManager setAllowsBackgroundLocationUpdates:YES];
[self.locationManager startUpdatingLocation];
}
}
When I navigate back to the application after 10 minutes for ex, my timer is being stopped at 3 min which is the time for the app to be suspended.
My code when the app get back to foreground is the below:
- (void)applicationWillEnterForeground:(UIApplication *)application {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
//
//Remove the baground task
//
if (self.bgTaskID != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:self.bgTaskID];
self.bgTaskID = UIBackgroundTaskInvalid;
}
[self.locationManager stopUpdatingLocation];
Any help?