我有一个应用程序可以捕获用户位置并将此信息发送到我的服务器。
我已经启动了 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 中调用此方法 - (void)applicationDidEnterBackground:(UIApplication *)application { [locationManager startMonitoringSignificantLocationChanges]; }
当应用程序返回前台时:
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[locationManager stopMonitoringSignificantLocationChanges];
}
但我有一些疑问。这样,如果应用程序处于关闭状态,我的应用程序会继续与服务器通信位置吗?
仅当我处于后台或前台状态时如何发送位置?
编辑:我还设置了:
UIBackgroundModes 位置