当应用程序处于后台时获取用户位置。 IOS
问题描述:
我正在开发一个在后台工作的应用程序来获取用户的位置并使用http请求将其发送到服务器。我的第一个意图是每隔n分钟获取一次用户的位置,但经过大量研究和试用后,我放弃了,因为ios在3分钟后杀死了我的后台任务。当应用程序处于后台时获取用户位置。 IOS
然后我尝试了一下MonitoringSignificantLocationChanges,但是由于手机信号塔的使用,它的位置更新不准确,导致我的应用程序失效。
的溶液到以下任一非常感谢:
- 获取在背景用户的位置每n分钟无限。
- 以高准确度(使用gps)获取用户的位置在后台显着位置更改
- 任何其他具有高精度结果的后台解决方案。
答
获取用户的位置在后台以高准确度SignificantLocationChanges(使用GPS)
执行以下操作:
在的info.plist添加以下
<key>NSLocationAlwaysUsageDescription</key>
<string>{your app name} requests your location coordinates.</string>
<key>UIBackgroundModes</key>
<array>
<string>location</string>
</array>
在代码中使用LoctionManager来获取位置更新,(它会在前台和后台工作)
@interface MyViewController <CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;
@end
@implementation MyViewController
-(void)startLocationUpdates {
// Create the location manager if this object does not
// already have one.
if (self.locationManager == nil) {
self.locationManager = [[CLLocationManager alloc] init];
}
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
self.locationManager.activityType = CLActivityTypeFitness;
// Movement threshold for new events.
self.locationManager.distanceFilter = 25; // meters
if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
[self.locationManager requestAlwaysAuthorization];
}
[self.locationManager startUpdatingLocation];
}
- (void)stopLocationUpdates {
[self.locationManager stopUpdatingLocation];
}
#pragma mark CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
// Add your logic here
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
NSLog(@"%@", error);
}
答
这对我来说是什么工作,我用CLLocationManagerDelegate,注册更新上didUpdateLocations和应用程序委托
- (void)applicationDidBecomeActive:(UIApplication *)application {
[_locationManager stopMonitoringSignificantLocationChanges];
[_locationManager startUpdatingLocation];
}
我开始更新位置,对我来说,关键是当应用程序转到后台时,我切换到重要位置更改,以便应用程序不会像这样排空面糊:
- (void)applicationDidEnterBackground:(UIApplication *)application {
[_locationManager startMonitoringSignificantLocationChanges];
}
在didUpdateLocations,你可以检查
BOOL isInBackground = NO;
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground)
{
isInBackground = YES;
}
,并开始一个任务在后台报告的位置,例如
if (isInBackground) {
[self sendBackgroundLocationToServer:self.location];
}
,并开始一个任务,我希望帮助。