这是我第一次使用CLLocationManager
。我不确定我做的是否正确。如果我错了,请纠正我。
我在viewDidLoad
方法中初始化locationManager,并以相同的方法告诉locationManager startUpdatingLocation。
当代表收到
时-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
[locationManager stopUpdatingLocation];
//do stuff with the coordinates
}
避免重复调用此委托方法。
我有一个UIButton
,用户可以点击此处更新位置
//called by user action
-(IBAction)updateLocation{
//start updating delegate
locationManager.delegate=self;
[locationManager startUpdatingLocation];
}
然而,当位置发生变化时,当我点击UIbutton
时,位置坐标根本没有变化。 :(
我做错了什么?这是做的权利还是我根本不应该停止locationManager?
帮助将不胜感激。
答案 0 :(得分:10)
CLLocationManager
缓存您的上一个位置,并在您致电-startUpdatingLocation
后立即将其返回。因此,您正在开始更新,接收旧位置,然后停止更新。
这不是-startUpdatingLocation/-stopUpdatingLocation
的用法。正如我上面提到的,多次调用委托方法有什么问题?如果您只想在用户点按按钮时获取该位置,请保留CLLocationManager
更新,并在用户点按您的按钮时检查CLLocationManger
的{{1}}媒体资源。
如果您试图避免多次调用委托方法的原因是因为您担心功耗等问题,请使用以下内容调整location
的{{1}}属性: desiredAccuracy
。
总而言之,它可能看起来像这样......
.h文件:
CLLocationManager
.m文件:
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
答案 1 :(得分:0)
假设您已将#import <CoreLocation/CoreLocation.h>
框架包括在内。这是您开始获取位置更新的方式。
CLLocationManager *locationMgr = [[CLLocationManager alloc] init];
locationMgr.desiredAccuracy = kCLLocationAccuracyBest;
locationMgr.delegate = self;
[locationMgr startUpdatingLocation];
你在这里是对的。在此之后,您将开始获取位置更新,此处为此委托 -
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
// Handle location updates
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
// Handle error
}