Latitude & Longitude Not Retrieved

2019-07-15 02:03发布

问题:

UPDATED for iOS9: I am new to iOS, experimenting with CoreLocation to return latitude and longitude values. The following code never executes the log output

 -(void)viewWillAppear:(BOOL)animated{

manager = [[CLLocationManager alloc]init];

manager.delegate = self;
manager.desiredAccuracy = kCLLocationAccuracyBest;

[manager startUpdatingLocation];
}

Here is my didUpdateToLocation function with is never reached

- (void)locationManager:(CLLocationManager *)manager
 didUpdateLocations:(NSArray<CLLocation *> *)locations{

NSLog(@"Location: %@", locations);
CLLocation *currentLocation = locations.lastObject;

if (currentLocation != nil) {
    float latitude = currentLocation.coordinate.latitude;

    float longitude = currentLocation.coordinate.longitude;

    NSLog(@"dLongitude : %f", longitude);
    NSLog(@"dLatitude : %f", latitude);
}

else{ NSLog(@"ERROR");
    }

}

回答1:

CLLocationManager is asynchronous, You should get the latitude and longitude in the delegate method.

locationManager.delegate = self;

Then implement this delegate method:

- locationManager:didUpdateLocations:



回答2:

1.first of all, you should use you should use a actual device instead of a simulator

2.implement CLLocationManagerDelegate in the interface,like

@interface XXXXX () <CLLocationManagerDelegate>

3.after

locationManager = [[CLLocationManager alloc] init];

add

locationManager.delegate = self;

4.implement the delegate method

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    for (CLLocation *location in locations) {
        //you can get locations here

    }
}