方法和解释:-我每1分钟重新启动一次位置管理器。DIDUpdateLocations我允许位置管理器从设备中获取10秒的位置,然后关闭它(以节省电池)。以下部分法典:--(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{for(int i=0;i<locations.count;i++){
CLLocation * newLocation = [locations objectAtIndex:i];
CLLocationCoordinate2D theLocation = newLocation.coordinate;
CLLocationAccuracy theAccuracy = newLocation.horizontalAccuracy;
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
if (locationAge > 30.0)
continue;
//Select only valid location and also location with good accuracy
if(newLocation!=nil&&theAccuracy>0
&&theAccuracy<2000
&&(!(theLocation.latitude==0.0&&theLocation.longitude==0.0))){
self.myLastLocation = theLocation;
self.myLastLocationAccuracy= theAccuracy;
NSMutableDictionary * dict = [[NSMutableDictionary alloc]init];
[dict setObject:[NSNumber numberWithFloat:theLocation.latitude] forKey:@"latitude"];
[dict setObject:[NSNumber numberWithFloat:theLocation.longitude] forKey:@"longitude"];
[dict setObject:[NSNumber numberWithFloat:theAccuracy] forKey:@"theAccuracy"];
//Add the vallid location with good accuracy into an array
//Every 1 minute, I will select the best location based on accuracy and send to server
[self.shareModel.myLocationArray addObject:dict];
}}//If the timer still valid, return it (Will not run the code below)if (self.shareModel.timer)
return;self.shareModel.bgTask = [BackgroundTaskManager sharedBackgroundTaskManager];[self.shareModel.bgTask beginNewBackgroundTask];//Restart the locationMaanger after 1 minuteself.shareModel.timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self
selector:@selector(restartLocationUpdates)
userInfo:nil
repeats:NO];//Will only stop the locationManager after 10 seconds, so that we can get some accurate locations//The location manager will only operate for 10 seconds to save batteryNSTimer * delay10Seconds;delay10Seconds = [NSTimer scheduledTimerWithTimeInterval:10 target:self
selector:@selector(stopLocationDelayBy10Seconds)
userInfo:nil
repeats:NO];
}我收到了一些请求,要求在一定时间间隔内向服务器发送位置时添加示例代码。我添加了示例代码,并结合了背景任务管理器的修复来解决后台运行较长时间的故障。