1、首先在plist表里边添加Privacy - Location Usage Description和NSLocationWhenInUseUsageDescription(这个是在程序使用期间进行定位,如果需要一直获取,添加NSLocationAlwaysUsageDescription),都为String类型
2、其次在.m中引入CoreLocation/CoreLocation.h头文件,并且遵循CLLocationManagerDelegate代理。然后定义一个CLLocationManager对象,代码如下:
#import "CoreLocation/CoreLocation.h" @interface ViewController ()<CLLocationManagerDelegate> @property (strong, nonatomic) CLLocationManager* locationManager; @end
3、开始定位的时候,首先判断是否能定位
-(void)startLocation{ if ([CLLocationManager locationServicesEnabled]) {//判断定位操作是否被允许 self.locationManager = [[CLLocationManager alloc] init]; self.locationManager.delegate = self;//遵循代理 self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; self.locationManager.distanceFilter = 10.0f; [_locationManager requestWhenInUseAuthorization];//使用程序其间允许访问位置数据(iOS8以上版本定位需要) [self.locationManager startUpdatingLocation];//开始定位 }else{//不能定位用户的位置的情况再次进行判断,并给与用户提示 //1.提醒用户检查当前的网络状况 //2.提醒用户打开定位开关 } }
4、代理方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
//当前所在城市的坐标值 CLLocation *currLocation = [locations lastObject]; NSLog(@"经度=%f 纬度=%f 高度=%f", currLocation.coordinate.latitude, currLocation.coordinate.longitude, currLocation.altitude); //根据经纬度反向地理编译出地址信息 CLGeocoder * geoCoder = [[CLGeocoder alloc] init]; [geoCoder reverseGeocodeLocation:currLocation completionHandler:^(NSArray *placemarks, NSError *error) { for (CLPlacemark * placemark in placemarks) { NSDictionary *address = [placemark addressDictionary]; // Country(国家) State(省) City(市) NSLog(@"#####%@",address); NSLog(@"%@", [address objectForKey:@"Country"]); NSLog(@"%@", [address objectForKey:@"State"]); NSLog(@"%@", [address objectForKey:@"City"]); } }]; }
5、定位失败,调用此方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{ if ([error code] == kCLErrorDenied){ //访问被拒绝 } if ([error code] == kCLErrorLocationUnknown) { //无法获取位置信息 } }:
warning!!!!!!!!!
如果打印错误信息为:Error Domain=kCLErrorDomain Code=0 "(null)"。进行如下操作:
Product -> Scheme -> Edit Scheme -> Options -> 把“ Allow Location Simulation ” 选项选中,并且设置下方的“default location”就可以了,不要让这个选项为none