获取用户的经度/纬度当viewDidLoad时

Luc*_*uca 12 core-location ios

我的目的是在加载视图时获取用户的经度/纬度,并将值存储在两个变量中以供以后计算.我不需要跟踪用户位置并更新它,我只需要获得他/她的坐标一次.我的代码看起来像这样:

- (void)viewDidLoad {
    [super viewDidLoad];
    // locationManager update as location
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self; 
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; 
    locationManager.distanceFilter = kCLDistanceFilterNone; 
    [locationManager startUpdatingLocation];
    CLLocation *location = [locationManager location];
    // Configure the new event with information from the location
    CLLocationCoordinate2D coordinate = [location coordinate];

    float longitude=coordinate.longitude;
    float latitude=coordinate.latitude;

    NSLog(@"dLongitude : %f",longitude);
    NSLog(@"dLatitude : %f", latitude); 
}
Run Code Online (Sandbox Code Playgroud)

在控制台中我一直这样:

dLongitude : 0.000000
dLatitude : 0.000000
Run Code Online (Sandbox Code Playgroud)

你能帮我吗?

Vla*_*mir 7

要获得用户的位置,即使您需要locationManager开始更新位置(您这样做)并实现管理员在检索位置时调用的委托方法 - 您也无法立即从位置管理器获取位置.

如果您不想跟踪用户位置 - 只需在第一次获取位置后停止更新该委托方法中的位置(并在将来需要时存储它).


Joe*_*son 7

一旦调用[locationManager startUpdatingLocation];viewDidLoad方法就完成了.你需要实施

-(void) locationManager: (CLLocationManager *)manager didUpdateToLocation: (CLLocation *) newLocation 
           fromLocation: (CLLocation *) oldLocation
Run Code Online (Sandbox Code Playgroud)

- (void) locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
Run Code Online (Sandbox Code Playgroud)

当您的locationManager获取位置或失败时,它将被调用.在这两种方法中,您都可以打电话[locationManager stopUpdatingLocation].

在didUpdateToLocation方法中,您应该从viewDidLoad移动所有代码,从CLLocation *location = [locationManager location];那里开始,您将获得正确的值.


小智 6

这对我有用

- (void)viewDidLoad {
    [super viewDidLoad];
    // locationManager update as location
    locationManager = [[CLLocationManager alloc] init];
    locationManager.delegate = self; 
    locationManager.desiredAccuracy = kCLLocationAccuracyBest; 
    locationManager.distanceFilter = kCLDistanceFilterNone; 
    [locationManager startUpdatingLocation];
    [locationManager stopUpdatingLocation];
    CLLocation *location = [locationManager location];
    // Configure the new event with information from the location

    float longitude=location.coordinate.longitude;
    float latitude=location.coordinate.latitude;

    NSLog(@"dLongitude : %f", longitude);
    NSLog(@"dLatitude : %f", latitude); 
}
Run Code Online (Sandbox Code Playgroud)