IOS 定位功能获取经纬度和地理编码
在info.plist中加入:
//允许在前台使用时获取GPS的描述
定位权限:Privacy - Location When In Use Usage Description
//允许永久使用GPS描述
定位权限: Privacy - Location Always Usage Description
定位权限 :Privacy - Location Always and When In Use Usage Description
适配不同版本都加上
代理:<CLLocationManagerDelegate>
#import <CoreLocation/CoreLocation.h>
@interface infoVC ()<CLLocationManagerDelegate>
{
CLLocationManager *locationmanager;//定位服务
NSString *currentCity;//当前城市
NSString *strlatitude;//经度
NSString *strlongitude;//纬度
}
- (void)viewDidLoad {
[super viewDidLoad];
[self getLocation];
// Do any additional setup after loading the view.
}
-(void)getLocation
{
//判断定位功能是否打开
if ([CLLocationManager locationServicesEnabled]) {
locationmanager = [[CLLocationManager alloc]init];
locationmanager.delegate = self;
[locationmanager requestAlwaysAuthorization];
currentCity = [NSString new];
[locationmanager requestWhenInUseAuthorization];
//设置寻址精度
locationmanager.desiredAccuracy = kCLLocationAccuracyBest;
locationmanager.distanceFilter = 5.0;
[locationmanager startUpdatingLocation];
}
}
#pragma mark CoreLocation delegate (定位失败)
//定位失败后调用此代理方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
//设置提示提醒用户打开定位服务
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"允许定位提示" message:@"请在设置中打开定位" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"打开定位" style:UIAlertActionStyleDefault handler:nil];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
[alert addAction:okAction];
[alert addAction:cancelAction];
[self presentViewController:alert animated:YES completion:nil];
}
#pragma mark 定位成功后则执行此代理方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
[locationmanager stopUpdatingHeading];
//旧址
CLLocation *currentLocation = [locations lastObject];
CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
//打印当前的经度与纬度
NSLog(@"%f,%f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);
//反地理编码
[geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
if (placemarks.count > 0) {
CLPlacemark *placeMark = placemarks[0];
currentCity = placeMark.locality;
if (!currentCity) {
currentCity = @"无法定位当前城市";
}
/*看需求定义一个全局变量来接收赋值*/
NSLog(@"----%@",placeMark.country);//当前国家
NSLog(@"%@",currentCity);//当前的城市
// NSLog(@"%@",placeMark.subLocality);//当前的位置
// NSLog(@"%@",placeMark.thoroughfare);//当前街道
// NSLog(@"%@",placeMark.name);//具体地址
}
}];
}