Objective c ios CLLocationManager赢得';第二次得不到位置
我有一个Objective c ios CLLocationManager赢得';第二次得不到位置,objective-c,ios,core-location,Objective C,Ios,Core Location,我有一个getLocation方法来初始化我的CLLocationManager并调用startUpdatingLocation。获取用户位置后,我调用stopdationlocation 稍后,当用户按刷新时,我调用一个方法reloadData,该方法调用getLocation,以便获取用户的最新位置。但是,这从不调用locationManager:didUpdateToLocation:fromLocation 方法。。因此,我从未获得用户的最新位置。可能是什么问题 -(void) getL
getLocation
方法来初始化我的CLLocationManager
并调用startUpdatingLocation
。获取用户位置后,我调用stopdationlocation
稍后,当用户按刷新时,我调用一个方法reloadData
,该方法调用getLocation
,以便获取用户的最新位置。但是,这从不调用locationManager:didUpdateToLocation:fromLocation
方法。。因此,我从未获得用户的最新位置。可能是什么问题
-(void) getLocation {
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.delegate = self;
[self.locationManager startUpdatingLocation];
}
- (void) locationManager: (CLLocationManager *)manager
didUpdateToLocation: (CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
if (oldLocation!= nil) { // make sure to wait until second latlong value
[self setLatitude:newLocation.coordinate.latitude];
[self setLongitude: newLocation.coordinate.longitude];
[self.locationManager stopUpdatingLocation];
self.locationManager.delegate = nil;
self.locationManager = nil;
[self makeUseOfLocationWithLat:[self getLatitude] andLon:[self getLongitude]];
}
}
-(void) reloadData {
[self getLocation];
}
是否确实需要分配新的CLLocationManager?尝试只分配一次(例如在init中),然后根据需要调用startUpdatingLocation和StopUpdateLocation。
对我来说,这个解决方案非常有效。在测试过程中你会移动吗?因为我认为只有在以下情况下才会触发回调:
- 您可以调用
startUpdatingLocation
- 你的位置改变了
- 位置管理器获得更好的结果(更详细)
locationManager:didUpdateToLocation:fromLocation:
只会在您点击refresh之后被调用一次,并且由于没有旧位置,您将不会进入if
案例
另一件事:你们班上肯定只有一个CLLocationManager。我只在每个项目/应用程序中使用一个(包装在单例中)。这是最好的方法!此外,我认为这将保留oldLocation值,以便通过更改此值可以解决您的问题
最好的,
Christian您可以尝试一下,这将有助于您在每次打开页面时进行更新。因为如果您将startUpdatingLocation放入viewdidload中,它将仅第一次获得加载
-(void)viewWillAppear:(BOOL)animated
{
[locationManager startUpdatingLocation];
}
您确定没有调用委托方法吗?它可能会在再次调用时显示缓存数据,这样它就可以保存新位置,而您不会注意到任何更改。我在委托方法中放置了一个NSLog,以查看它是否被调用。我也没有尝试过,但是我注意到我有另一个问题,如果我在停止更新Location之后没有将委托设置为nil,那么有时候我会进入一个无限循环,委托方法不断被调用。在任何情况下,我不认为分配一个新的CLLocationManager会导致这个问题……或者它会导致这个问题吗?在getLocation的开头设置一个断点,这样您就可以真正看到发生了什么,以及您是否有一个有效的位置管理器。