iOS定位获取国家和城市

1.在target->Build Phases->link Binary With Libraries中加入
CoreLocation.framework
2.在info.plist中加入
Privacy - Location Always Usage Description //总是开启 Privacy - Location When In Use Usage Description //在使用期间开启
3.在需要定位的页面加入头文件
#import
#import
4.声明一个定位管理服务对象
@property(nonatomic ,strong)CLLocationManager *locationManager;
5.遵守定位管理服务协议
CLLocationManagerDelegate
6.在viewDidLoad中初始化定位服务对象- (void)viewDidLoad { [super viewDidLoad]; //定位服务初始化对象 _locationManager = [[CLLocationManager alloc]init ]; _locationManager.delegate = self; _locationManager.desiredAccuracy = kCLLocationAccuracyBest; _locationManager.distanceFilter = 1000.0f; if (![CLLocationManager locationServicesEnabled]) { NSLog(@"定位服务当前可能尚未打开,请设置打开!"); return; }

  1. 实现CLLocationManagerDelegate 协议方法:
    - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
    - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *currentLocation = [locations lastObject]; CLGeocoder *geocoder = [[CLGeocoder alloc]init]; //反地理编码 [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray * _Nullable placemarks, NSError * _Nullable error) {
    MMLog(@"--array--%d---error--%@",(int)placemarks.count,error);
    if (placemarks.count > 0) {
    CLPlacemark *placemark = [placemarks objectAtIndex:0];
    NSString *city = placemark.administrativeArea;//获取城市
    NSString *country = placemark.country;// 获取国家
    NSLog(@"位于:%@",city);
    MMLog(@"%@",placemark.addressDictionary[@"Name"]);
    }
    }];
    }
    `
    这只是作为真机测试

你可能感兴趣的:(iOS定位获取国家和城市)