我正在开发一个在后台运行的应用,以获取用户的位置,并使用http请求将其发送到服务器。我的第一个目的是每隔n分钟到达用户的位置,但经过大量的研究和试验,我放弃了,因为ios在3分钟后杀死了我的后台任务。
然后我尝试使用MonitoringSignificantLocationChanges,但由于手机信号塔的使用导致其位置更新不准确,这会破坏我应用的目的。
非常感谢以下任何一种解决方案:
答案 0 :(得分:1)
这对我有用,我使用 CLLocationManagerDelegate ,注册 didUpdateLocations 的更新以及app Delegate
- (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];
}
开始任务,我希望有所帮助。
答案 1 :(得分:0)
高精度地使用HIGHantLocationChanges获取用户的位置(使用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);
}