获取当前所在的城市信息

1、引入CoreLocation库

2、使用协议<CLLocationManagerDelegate>

-(void)initLocaltionManager
{
    // 初始化位置管理器
    if (![CLLocationManager locationServicesEnabled])
    {
        UIAlertView *locationServiceAlert = [[UIAlertView alloc] initWithTitle:nil message:@"定位不可用" delegate:nil cancelButtonTitle:@"我知道了" otherButtonTitles:nil];
        [locationServiceAlert show];
        [locationServiceAlert release];
    }
    else
    {
        locationManager = [[CLLocationManager alloc] init];
        locationManager.delegate = self;
        locationManager.desiredAccuracy=kCLLocationAccuracyBest;//使用最佳定位方式
        locationManager.distanceFilter=1000.0f;//精度
        [locationManager startUpdatingLocation];
    }
}

distanceFilter是距离过滤器,为了减少对定位装置的轮询次数,位置的改变不会每次都去通知委托,而是在移动了足够的距离时才通知委托程序,它的单位是米,这里设置为至少移动1000再通知委托处理更新。startUpdatingLocation就是启动定位管理了,一般来说,在不需要更新定位时最好关闭它,用stopUpdatingLocation,可以节省电量。对于委托CLLocationManagerDelegate,最常用的方法是:

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation;

这个方法即定位改变时委托会执行的方法。可以得到新位置,旧位置,CLLocation里面有经度纬度的坐标值,同时CLLocation还有个属性horizontalAccuracy,用来得到水平上的精确度,它的大小就是定位精度的半径,单位为米。如果值为-1,则说明此定位不可信。

另外委托还有一个常用方法是:

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error ;
当定位出现错误时就会调用这个方法。

- (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;//城市
             NSString *name=placemark.name;//全名
             NSString *thoroughfare=placemark.thoroughfare; //街道路
             NSString *subThoroughfare=placemark.subThoroughfare; //门牌号
            NSString *subLocality=placemark.subLocality; //区县
             NSString *ISOcountryCode=placemark.ISOcountryCode; // CN
             NSString *country=placemark.country; // 国家
         }
         else if (error == nil && [array count] == 0)
         {
             NSLog(@"No results were returned.");
         }
         else if (error != nil)
         {
             NSLog(@"An error occurred = %@", error);
         }
     }];
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值