Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

updating location in background on a timer/periodically in iOS 8

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.

like image 697
initWithQuestion Avatar asked Oct 31 '22 16:10

initWithQuestion


1 Answers

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];
    }
}
like image 171
VaporwareWolf Avatar answered Nov 08 '22 06:11

VaporwareWolf