iOS获取当前城市

1.倒入头文件

#import <CoreLocation/CoreLocation.h>post

2.实现定位协议CLLocationManagerDelegateatom

3.定义定位属性

@property(nonatomic,retain)CLLocationManager *locationManager;spa

4.開始定位3d

- (void)locatecode

{ci

    // 推判定位操做是否被赞成it

    if([CLLocationManager locationServicesEnabled]) {io

        self.locationManager = [[CLLocationManager alloc] init] ;编译

        

        self.locationManager.delegate = self;ast

    }else {

        //提示用户没法进行定位操做

        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:

        @"提示" message:@"定位不成功 ,请确认开启定位" delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"肯定", nil];

        [alertView show];

    }

    // 開始定位

    [self.locationManager startUpdatingLocation];

}


5.实现定位协议回调方法

#pragma mark - CoreLocation Delegate

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

{

    //此处locations存储了持续更新的位置坐标值,取最后一个值为最新位置,假设不想让其持续更新位置,则在此方法中获取到一个值以后让locationManager stopUpdatingLocation

    CLLocation *currentLocation = [locations lastObject];

    

    // 获取当前所在的城市名

    CLGeocoder *geocoder = [[CLGeocoder alloc] init];

    //依据经纬度反向地理编译出地址信息

    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)

     {

         if (array.count > 0)

         {

             CLPlacemark *placemark = [array objectAtIndex:0];

             

             //将得到的所有信息显示到label

             NSLog(@"%@",placemark.name);

             //获取城市

             NSString *city = placemark.locality;

             if (!city) {

                 //四大直辖市的城市信息没法经过locality得到,仅仅能经过获取省份的方法来得到(假设city为空,则可知为直辖市)

                 city = placemark.administrativeArea;

             }

             self.cityName = city;

         }

         else if (error == nil && [array count] == 0)

         {

             NSLog(@"No results were returned.");

         }

         else if (error != nil)

         {

             NSLog(@"An error occurred = %@", error);

         }

     }];

    //系统会一直更新数据。直到选择中止更新。因为咱们仅仅需要得到一次经纬度就能够,因此获取以后就中止更新

    [manager stopUpdatingLocation];

}

- (void)locationManager:(CLLocationManager *)manager

       didFailWithError:(NSError *)error {

    

    if (error.code == kCLErrorDenied) {

        // 提示用户出错缘由。可按住Option键点击 KCLErrorDenied的查看不少其它出错信息,可打印error.code值查找缘由所在

    }

}

相关文章
相关标签/搜索