IOS-定位(显示城市)

1.导入框架

Xcode中添加 CoreLocation.framework

2.info.plist文件添加描述

3.导入头文件

#import

4.声明管理者和城市

{    

NSString * currentCity; //当前城市

}

@property (nonatomic, strong) CLLocationManager *locationManager;

5.初始化

self.locationManager= [[CLLocationManageralloc]init];

self.locationManager.delegate=self;

[_locationManagerrequestWhenInUseAuthorization];

currentCity= [[NSStringalloc]init];

6.开始定位

判断定位是否打开

- (void)locate {    

//判断定位功能是否打开    

if ([CLLocationManager locationServicesEnabled]) {         NSLog(@"开始定位");        

[self.locationManager startUpdatingLocation];    

}    


定位未开启,去打开定位

UIAlertController* alertVC = [UIAlertControlleralertControllerWithTitle:@"允许\"定位\"提示"message:@"请在设置中打开定位"preferredStyle:UIAlertControllerStyleAlert];

UIAlertAction* ok = [UIAlertActionactionWithTitle:@"打开定位"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction*_Nonnullaction) {

//打开定位设置

NSURL*settingsURL = [NSURLURLWithString:UIApplicationOpenSettingsURLString];

[[UIApplicationsharedApplication]openURL:settingsURL];

}];

UIAlertAction* cancel = [UIAlertActionactionWithTitle:@"取消"style:UIAlertActionStyleCancelhandler:^(UIAlertAction*_Nonnullaction) {

}];

[alertVCaddAction:cancel];

[alertVCaddAction:ok];

[selfpresentViewController:alertVCanimated:YEScompletion:nil];

7.代理方法

        -(void)locationManager:(CLLocationManager*)manager didUpdateLocations:(NSArray *)locations

    1.获取经纬度

CLLocation*currentLocation = [locationslastObject];

CLLocationCoordinate2Dcoordinate = currentLocation.coordinate;

NSLog(@"纬度%f 经度%f",coordinate.latitude,coordinate.longitude);

    2.获取城市

CLGeocoder* geoCoder = [[CLGeocoderalloc]init];

//反编码

[geoCoderreverseGeocodeLocation:currentLocationcompletionHandler:^(NSArray *_Nullableplacemarks,NSError*_Nullableerror) {

if(placemarks.count>0) {

CLPlacemark*placeMark = placemarks[0];

currentCity= placeMark.locality;

if(!currentCity) {

currentCity=@"无法定位当前城市";

}

//NSLog(@"%@",currentCity); //这就是当前的城市

//NSLog(@"%@",placeMark.name);//具体地址:xx市xx区xx街道

_cityLabel.text=currentCity;

_placeLabel.text= placeMark.name;

}

elseif(error ==nil&& placemarks.count==0) {

NSLog(@"No location and error return");

}

elseif(error) {

NSLog(@"location error: %@ ",error);

}

}];

8.Git地址

github.com/baipeng1990/BPMapLocationDemo.git

你可能感兴趣的:(IOS-定位(显示城市))