【发布时间】:2014-09-22 18:25:54
【问题描述】:
如果应用程序处于后台状态或前台状态,我希望每 5 分钟更新一次用户的位置。这是一个对位置非常敏感的应用程序,因此随时了解位置至关重要。
在 SO 上有很多与这个问题相关的答案,但其中很多都是针对 iOS 6 及更早版本的。在 iOS 7 之后,很多后台任务都发生了变化,我很难找到在后台实现定期位置更新的方法。
【问题讨论】:
标签: ios core-location
如果应用程序处于后台状态或前台状态,我希望每 5 分钟更新一次用户的位置。这是一个对位置非常敏感的应用程序,因此随时了解位置至关重要。
在 SO 上有很多与这个问题相关的答案,但其中很多都是针对 iOS 6 及更早版本的。在 iOS 7 之后,很多后台任务都发生了变化,我很难找到在后台实现定期位置更新的方法。
【问题讨论】:
标签: ios core-location
您需要使用 CoreLocation 的委托。获得坐标后,立即停止 CoreLocation,设置一个计时器以在 5 分钟内重新启动它。
在 iOS 8 中,您需要为 NSLocationWhenInUseUsageDescription 和/或 NSLocationAlwaysInUseDescription 设置一个 plist 条目。
Apple 文档非常清楚地说明了如何执行所有这些操作。
-(void)startUpdating{
self.locationManager = [[CLLocationManager alloc]init];
self.locationManager.delegate = self;
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[self.locationManager startUpdatingLocation];
}
-(void)timerFired{
[self.timer invalidate];
_timer = nil;
[self.locationManager startUpdatingLocation];
}
// CLLocationDelegate
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations{
if(locations.count){
// Optional: check error for desired accuracy
self.location = locations[0];
[self.locationManager stopUpdatingLocation];
self.timer = [NSTimer scheduledTimerWithTimeInterval:60 * 5 target:self selector:@selector(timerFired) userInfo:nil repeats:NO];
}
}
【讨论】:
[self.locationManager stopUpdatingLocation] 出现了两次,timerFired 方法应该是[self.locationManager startUpdatingLocation] 吗?我相信self.location = [locations lastObject] 更合适,因为最后一个对象总是最新的。最后,你能解释一下为什么会调用定时器失效逻辑吗?
apple documentation 上有很多关于此的信息。
此外,还有一些额外的答案 here 和 here 以及来自 stackoverflow 的先前答案。里面似乎有足够的信息可以帮助你!
【讨论】: