繁体   English   中英

iOS CLLocation - 获取ViewDidLoad上的位置

[英]iOS CLLocation - getting the location on ViewDidLoad

这可能是我想要的简单事情,但我已经设置了位置服务(为了清晰起见缩短了):

- (void)viewDidLoad
{
    self.locationManager = [[[CLLocationManager alloc] init] autorelease];
    self.locationManager.delegate = self;
    [self.locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    NSLog(@"%@",newLocation.coordinate.latitude);
    NSLog(@"%@",newLocation.coordinate.longitude);
}

工作正常,并给我一个位置数据流到日志。

但我想要的是能够立即在ViewDidLoad中获取当前位置,因为我只需要它一次,而不是一次不断的更新 - 它只是为了找到“最近”的便利设施,所以我可以向用户报告。 我试过添加:

self.locationLat = [self.locationManager location].coordinate.latitude;
self.locationLng = [self.locationManager location].coordinate.longitude;

在startUpdatingLocation之后立即到ViewDidLoad,但它们总是以null形式出现。 还有什么我需要调用才能在运行后获取数据吗?

谢谢

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    /*report to user*/
    [self.locationManager stopUpdatingLocation];
}

因此,您将获得一次位置,然后停止更新它。

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    [manager stopUpdatingLocation];
    NSLog(@"%@",newLocation.coordinate.latitude);
    NSLog(@"%@",newLocation.coordinate.longitude);
}

您只能获得值

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation

没有其他功能可用于获取位置值..因此,您将获得最快的值是在首次调用此函数时...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM