I would like to ideally update the user's location every 5 minutes if the application is within a background state, or in the foreground state. This is a very location sensitive app, so knowing the location at all times is quiet crucial.
There have been many answers relating to this question on SO, but a lot of them deal with iOS 6 and earlier. After iOS 7, a lot of background tasks have changed and Im having difficulty in finding a way to implement periodic location updates in the background.
You'll want to use CoreLocation's delegate. As soon as you get a coordinate, stop CoreLocation, set a timer to start it again in 5 minutes.
With iOS 8, you'll need to set a plist entry for NSLocationWhenInUseUsageDescription and/or NSLocationAlwaysInUseDescription.
The Apple documentation is very clear on how to do all of this.
-(void)startUpdating{
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate = self;
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[self.locationManager startUpdatingLocation];
}
-(void)timerFired{
[self.timer invalidate];
_timer = nil;
[self.locationManager startUpdatingLocation];
}
// CLLocationDelegate
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations{
if(locations.count){
// Optional: check error for desired accuracy
self.location = locations[0];
[self.locationManager stopUpdatingLocation];
self.timer = [NSTimer scheduledTimerWithTimeInterval:60 * 5 target:self selector:@selector(timerFired) userInfo:nil repeats:NO];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With