我有一个应用程序,捕捉用户位置和发送此信息到我的服务器。
我已经开始用的LocationManager服务:
- (CLLocationManager *)locationManager {
if (_locationManager == nil) {
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
isUpdatingLocation = NO;
}
return _locationManager;
}
-(void) startLookingForLocation{
[self locationManager].desiredAccuracy = kCLLocationAccuracyBest;
[self locationManager].distanceFilter = 250;
if([[self locationManager]respondsToSelector:@selector(setPausesLocationUpdatesAutomatically:)])
[[self locationManager] setPausesLocationUpdatesAutomatically:YES];
if([[self locationManager]respondsToSelector:@selector(setActivityType:) ])
[[self locationManager] setActivityType:CLActivityTypeFitness];
[[self locationManager] startUpdatingLocation];
[[self locationManager] startUpdatingHeading];
isUpdatingLocation = YES;
}
与停止它:
-(void) stopLookingForLocation{
[[self locationManager] stopUpdatingLocation];
[[self locationManager] stopUpdatingHeading];
isUpdatingLocation = NO;
}
所以,当我检测用户位置的变化:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
[self setCurrentLocation:newLocation];
BOOL isInBackground = NO;
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
{
isInBackground = YES;
}
if (isInBackground)
{
UIBackgroundTaskIdentifier bgTask = [[UIApplication sharedApplication]
beginBackgroundTaskWithExpirationHandler:
^{
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
}];
// Send user-location to my server
if (bgTask != UIBackgroundTaskInvalid)
{
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}
}
else
{
// Send user-location to my server
}
}
和所有工作正常。 (我想)。
当应用程序进入后台模式,我调用内的appDelegate此方法 - (无效)applicationDidEnterBackground:(UIApplication的*)应用{[的LocationManager startMonitoringSignificantLocationChanges]; }
当应用程序返回前台:
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[locationManager stopMonitoringSignificantLocationChanges];
}
但是我有些疑惑。 这样一来,如果应用程序处于关闭状态,我的应用程序继续comunicate位置服务器?
如何只有当我在后台或前台状态,是我可以发送位置?
编辑:我还设置:
UIBackgroundModes位置