理想情况下,如果应用程序处于后台状态或处于前台状态,我希望每5分钟更新一次用户的位置。这是一个非常敏感的位置应用程序,所以知道位置在任何时候都是安静的关键。
有关SO的问题有很多答案,但很多答案都涉及到iOS 6和更早版本。在iOS 7之后,很多后台任务都发生了变化,我很难找到在后台实现周期性位置更新的方法。
发布于 2014-09-23 03:07:18
您需要使用CoreLocation的委托。一旦得到一个坐标,停止CoreLocation,设置一个定时器,在5分钟内再次启动它。
使用iOS 8,您需要为NSLocationWhenInUseUsageDescription和/或NSLocationAlwaysInUseDescription设置一个plist条目。
苹果公司的文档非常清楚如何做到这一点。
-(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];
}
}https://stackoverflow.com/questions/25980778
复制相似问题