#import <CoreLocation/CoreLocation.h>
@interface ViewController ()<CLLocationManagerDelegate> {
CLLocationManager *locationManager;
NSString *longitude; // 纬度
NSString *latitude; // 经度
NSString *elevation; // 海拔
}
// 开始定位
- (void)startLocating {
if ([CLLocationManager locationServicesEnabled]) {
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
[locationManager requestAlwaysAuthorization];
[locationManager requestWhenInUseAuthorization];
// 设置寻址精度
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = 5.0;
[locationManager startUpdatingLocation];
}
}
// 定位失败
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
}
// 定位成功
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
[locationManager stopUpdatingLocation];
CLLocation *currentLocation = [locations lastObject];
latitude = [NSString stringWithFormat:@"%.1f", currentLocation.coordinate.latitude];
longitude = [NSString stringWithFormat:@"%.1f", currentLocation.coordinate.longitude];
elevation = [NSString stringWithFormat:@"%.1f", currentLocation.altitude];
}