做的app需要定位城市的功能,在网上看了一堆,不是太详细,研究半天终于搞定,分享给他家
如上图,首先得在plist文件中配置权限(ios8下这是必须实现的)
为plist文件添加key
NSLocationWhenInUseDescription,允许在前台获取GPS的描述
NSLocationAlwaysUsageDescription,允许在后台获取GPS的描述
最后是代码的实现
/**
* 获取当前城市位置
*/
- (void)getCurrentCity
{
if ([CLLocationManager locationServicesEnabled]) {
if (!self.cllManager) {
self.cllManager = [[CLLocationManager alloc]init];
}
self.cllManager.delegate = self;
self.cllManager.distanceFilter = 1.0;
self.cllManager.desiredAccuracy = kCLLocationAccuracyBest;
if ([self.cllManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
[self.cllManager requestAlwaysAuthorization];//永久授权;
//[self.cllManager requestWhenInUseAuthorization];//使用中授权;
}
[self.cllManager startUpdatingLocation];//开启位置更新;
self.cllManager.delegate = self;
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *location=[locations firstObject];//取出第一个位置
CLLocationCoordinate2D coordinate=location.coordinate;//位置坐标
NSLog(@"经度:%f,纬度:%f,海拔:%f,航向:%f,行走速度:%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);
//获取当前所在的城市名;
CLGeocoder * geocoder = [[CLGeocoder alloc]init];
//根据经纬度反向地理编译出地址信息;
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
if (placemarks.count > 0) {
CLPlacemark * placemark = placemarks[0];
//NSLog(@"%@",placemark.name);
//获取城市
NSString * city = placemark.locality;
if (!city) {
//四大直辖市无法通过locality获得,只能通过省份方法获取
city = placemark.administrativeArea;
}
NSLog(@"city == %@",city);
[barBtn setTitle:[city substringToIndex:3] forState:UIControlStateNormal];
}else if (error == nil && placemarks.count == 0){
NSLog(@"无返回");
}else if (error != nil){
NSLog(@"error == %@",error);
}
}];
//如果不需要实时定位,使用完即使关闭定位服务
[_cllManager stopUpdatingLocation];
}
总结:这个定位的实现跟大家分享的原因就是,如果单纯的实现了方法,定位的代理方法是不会实现的,必须要配置plist文件.