当我尝试为LBS应用程序进行实验时,我遇到了问题 . 在模拟器中测试时,它似乎工作 . 然后,我在iPhone上试了一下 . 它没有按预期工作 .
当我启动应用程序时,它会显示所有信息,例如我的位置纬度,经度,距离等 . 但是,当我走开时,这些信息没有改变 . 无论是运行应用程序还是我的iPhone自动关闭(然后再次打开应用程序),这些数据仍然保持不变 .
当我关闭应用程序并重新启动它时,它可以显示更新信息 .
这是我的代码
我在viewDidLoad中设置了CLLocationManager
- (void)viewDidLoad
{
[super viewDidLoad];
//setup locationManager
locationManager =[[CLLocationManager alloc]init];
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
locationManager.distanceFilter=kCLDistanceFilterNone;
[locationManager setDelegate:self];
[locationManager startUpdatingLocation];
}
这是CLLocationManager Delegate的代码
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
if (newLocation.horizontalAccuracy < 0) return;
NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
if (locationAge > 5.0) return;
if (myLocation == nil || myLocation.horizontalAccuracy > newLocation.horizontalAccuracy) {
self.myLocation = newLocation;
// NSLog(@"mylocation=%@",self.myLocation);
[self.mainTableView reloadData];
[self sortedDistArray];//this method is to calculate distance and put it in array. It work...
if (newLocation.horizontalAccuracy <= locationManager.desiredAccuracy) {
[self stopLocationManager];
}
}
}
- (void)stopLocationManager {[locationManager stopUpdatingLocation]; locationManager.delegate = nil; }
现在,我有以下问题 .
-
我的CLLocationManager设置有什么问题?我应该在appDelegate下面(在didFinishLaunchingWithOptions方法下)让它运行它背景?它会快速耗尽电池电量吗?或者在ViewWillAppear而不是ViewDidLoad中设置它?
-
另一方面,我把“拉下来刷新”到程序中 . 我认为在刷新期间可以更新更新的数据 . 但是,它也不会起作用 . 这是我的刷新代码(我把EGOTableViewPullRefresh用于刷新功能) .
-
(void)reloadTableViewDataSource {
// should be calling your tableviews data source model to reload
// put here just for demo
_reloading = YES;
locationManager =[[CLLocationManager alloc]init];
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
locationManager.distanceFilter=kCLDistanceFilterNone;
[locationManager setDelegate:self];
[locationManager startUpdatingLocation];
[self sortedDistArray];
[mainTableView reloadData];
[self doneLoadingTableViewData];
}
我的想法是CLLocationManager重置并在用户刷新期间启动更新位置 . 但是,它没有用 . 我的错是什么?
对不起,我有很多问题 . 如果有人给我建议,我将不胜感激 .
2 回答
您无法控制何时提供位置更新,您只能启动
CLLocationManager
,操作系统将决定何时向您提供CLLocationManagerDelegate
更新 .如果您希望它强制更新,您可以尝试检查
CLLocationManager
是否已经启动,如果已经启动,请停止并重新启动 .顺便提一下,作为旁注,我建议你将CLLocationManager包装在一个单例类中 . 如果您继续启动位置管理器,它将在许多情况下与应用程序一起运行并耗尽电池(当您实际停止时,我无法在您的代码中看到) . 根据需要启动和停止
CLLocationManager
.我不清楚你究竟想要什么 . 如果您只想在打开应用程序时显示位置,请将startupdatinglocation行移至viewDidAppear . 在屏幕上显示活动指示器,因为它需要一些时间进入并更新 .
如果您希望它不断更新,请不要调用stopUpdatingLocation . 只要您的位置发生变化,它就会触发委托方法以满足管理器的设置 .
我注意到的另一件事,你的意思是说
看起来你说比5.0更好,在这种情况下,如果需要更长的时间来获得更新,你将永远不会回复另一个 .
不是重复设置管理器,而是创建单例或保存在属性中 . 启动后,您只需根据需要启动/停止更新 .
您可以从我的一些提示中受益:
TTLocationHandler GitHub Repository