获取当前所在的城市信息

来源:互联网 发布:mysql win10 64位安装 编辑:程序博客网 时间:2024/04/29 19:22

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
原创粉丝点击