如果应用程序处于后台状态或处于前台状态,我希望每5分钟更新一次用户的位置.这是一个非常敏感的应用程序,所以在任何时候都知道位置是至关重要的.
关于这个问题有很多关于SO的答案,但是很多都是针对iOS 6及更早版本的.在iOS 7之后,许多后台任务已经改变,我很难找到在后台实现定期位置更新的方法.
您将需要使用 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];
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2388 次 |
| 最近记录: |