我正在编写一个需要后台位置更新的应用程序高精度、低频率。解决方案似乎是一个后台 NSTimer 任务,它启动位置管理器的更新,然后立即关闭。这个问题之前已经被问过:
如何在我的 iOS 应用程序中每 n 分钟更新一次后台位置? https://stackoverflow.com/questions/6347503/how-do-i-get-a-background-location-update-every-n-minutes-in-my-ios-application
应用程序进入后台后每 n 分钟获取用户位置 https://stackoverflow.com/questions/10235203/getting-user-location-every-n-minutes-after-app-goes-to-background?rq=1
iOS 不是典型的后台位置跟踪计时器问题 https://stackoverflow.com/questions/13377750/ios-not-the-typical-background-location-tracking-timer-issue
iOS 长时间运行的后台计时器,具有“位置”后台模式 https://stackoverflow.com/questions/15650139/ios-long-running-background-timer-with-location-background-mode
基于位置跟踪的iOS全时后台服务 https://stackoverflow.com/questions/10706265/ios-full-time-background-service-based-on-location-tracking
但我还没有得到最小例子在职的。在尝试了上述已接受答案的每种排列之后,我整理了一个起点。进入背景:
- (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];
}
和委托方法:
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
NSLog(@"%@", newLocation);
NSLog(@"background time: %f", [UIApplication sharedApplication].backgroundTimeRemaining);
[self.locationManager stopUpdatingLocation];
}
目前的行为是backgroundTimeRemaining
从 180 秒递减到零(记录位置时),然后执行到期处理程序,并且不会生成进一步的位置更新。如何修改上面的代码才能接收无限期地在后台定期更新位置?
Update:我的目标是 iOS 7,似乎有一些证据表明后台任务的行为有所不同:
从后台任务启动 iOS 7 中的位置管理器 https://stackoverflow.com/questions/18901583/start-location-manager-in-ios-7-from-background-task