Latitude & Longitude Not Retrieved

2019-07-15 02:29发布

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");
    }

}

2条回答
Anthone
2楼-- · 2019-07-15 02:44

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

    }
}
查看更多
乱世女痞
3楼-- · 2019-07-15 02:59

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

locationManager.delegate = self;

Then implement this delegate method:

- locationManager:didUpdateLocations:

查看更多
登录 后发表回答