我正在编写一个需要高精度和低频率的背景位置更新的应用程序.该解决方案似乎是一个后台NSTimer任务,它启动位置管理器的更新,然后立即关闭.之前已经问过这个问题:
但我还没有得到最起码的例子.在尝试了上述接受的答案的每一个排列后,我总结了一个起点.输入背景:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
self.bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
NSLog(@"ending background task");
[[UIApplication sharedApplication] endBackgroundTask:self.bgTask];
self.bgTask = UIBackgroundTaskInvalid;
}];
self.timer = [NSTimer scheduledTimerWithTimeInterval:60
target:self.locationManager
selector:@selector(startUpdatingLocation)
userInfo:nil
repeats:YES];
}
Run Code Online (Sandbox Code Playgroud)
和委托方法:
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
NSLog(@"%@", newLocation);
NSLog(@"background time: %f", [UIApplication sharedApplication].backgroundTimeRemaining);
[self.locationManager stopUpdatingLocation];
}
Run Code Online (Sandbox Code Playgroud)
当前行为是backgroundTimeRemaining从180秒减少到零(记录位置时),然后执行到期处理程序,不再生成进一步的位置更新.如何修改上述代码以便在后台无限期地接收定期位置更新?
更新:我的目标是iOS 7,似乎有一些证据表明后台任务的行为有所不同:
objective-c core-location ios background-task ios-background-mode
我有更新用户位置的奇怪问题.有时我的应用程序会更新位置,但有时会更新.我不知道问题出在哪里,我的代码(来自AppDelegate.m)如下:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSLog(@"Went to Background");
// Only monitor significant changes
[locationManager startMonitoringSignificantLocationChanges];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Start location services
locationManager = [[CLLocationManager alloc] init];
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// Only report to location manager if the user has traveled 1000 meters
locationManager.distanceFilter = 1000.0f;
locationManager.delegate = self;
locationManager.activityType = CLActivityTypeAutomotiveNavigation;
[locationManager stopMonitoringSignificantLocationChanges];
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
// Check if running in background or not
BOOL isInBackground = NO;
if ([UIApplication sharedApplication].applicationState …Run Code Online (Sandbox Code Playgroud)