180 Sekunden (3 Minuten) aufzurufen und die Standortaktualisierungen durch Aufruf von stopLocationDelayBy10Seconds< zu stoppen /strong> nach 10 Sekunden, um den Akku zu schonen.
Code: Select all
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
//some business logic goes here....
if (sendLocation) {
//send location to server
}
UIApplication* application = [UIApplication sharedApplication];
__block UIBackgroundTaskIdentifier bgTaskId = UIBackgroundTaskInvalid;
if ([application respondsToSelector:@selector(beginBackgroundTaskWithExpirationHandler:)]) {
bgTaskId = [application beginBackgroundTaskWithExpirationHandler:^{
[application endBackgroundTask:bgTaskId];
bgTaskId = UIBackgroundTaskInvalid;
}];
//using a timer to schedule a method call
self.bgtimer = [NSTimer scheduledTimerWithTimeInterval:180 target:self
selector:@selector(restartLocationUpdates)
userInfo:nil
repeats:NO];
//stopping the locatioupdates after 10 seconds to save battery
self.delayTimer = [NSTimer scheduledTimerWithTimeInterval:10 target:self
selector:@selector(stopLocationDelayBy10Seconds)
userInfo:nil
repeats:NO];
}
- (void) restartLocationUpdates {
counter++;
if(counter == 5){
sendLocation = YES;
counter=0;
}else{
sendLocation = NO;
}
//invalidating the bgtimer before creating and scheduling it again.
if (self.bgtimer) {
[self.bgtimer invalidate];
self.bgtimer = nil;
}
//configuring location manager and then starting location updates
//.....
[locationManager startUpdatingLocation];
}
-(void)stopLocationDelayBy10Seconds{
[locationManager stopUpdatingLocation];
}
Imp: Die Berechtigung für Ortungsdienste ist auf „Immer“ eingestellt und der Hintergrundmodus ist aktiviert Standortaktualisierungen und Hintergrundabruf