iOS-定位当前城市

1.导入框架

import

2.定义对象


@property(nonatomic,strong)CLLocationManager *locationManager;

3.开始定位


//定位服务
-(void)LocationService
{

if ([CLLocationManager locationServicesEnabled]) {
    // 初始化定位管理器
    self.locationManager=[[CLLocationManager alloc]init];
    self.locationManager.delegate=self;
    // 设置定位精确度到千米
    self.locationManager.desiredAccuracy=kCLLocationAccuracyKilometer;
    // 设置过滤器为无
    self.locationManager.distanceFilter=kCLDistanceFilterNone;
    //这句话ios8以上版本使用
    [ self.locationManager requestAlwaysAuthorization];
    //开始定位
    [ self.locationManager startUpdatingLocation];
} else {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"无法定位" message:@"请检查你的设备是否开启定位功能" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

}

4.代理方法

pragma mark--定位代理

  • (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
    {

    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray*array, NSError *error){
    if (array.count > 0){
    CLPlacemark *placemark = [array objectAtIndex:0];

          //获取城市
          NSString \*city = placemark.locality;
          if (!city) {
              //四大直辖市的城市信息无法通过locality获得,只能通过获取省份的方法来获得(如果city为空,则可知为直辖市)
              city = placemark.administrativeArea;
          }
          NSLog(@"city = %@", city);
          self.cityLabel.text=city;
    

//
}
else if (error == nil && [array count] == 0)
{
NSLog(@"No results were returned.");
}
else if (error != nil)
{
NSLog(@"An error occurred = %@", error);
}
}];
//系统会一直更新数据,直到选择停止更新,因为我们只需要获得一次经纬度即可,所以获取之后就停止更新
[manager stopUpdatingLocation];
}

你可能感兴趣的:(iOS-定位当前城市)