iOS 开发 CoreLocation实现定位功能

1、首先得引入CoreLocation系统框架

屏幕快照 2016-12-16 上午11.17.04.png

2、导入头文件 遵循代理

import

3、在info.plist中打开定位权限

屏幕快照 2016-12-16 上午11.22.43.png

3、代码实现

@property (nonatomic, strong) CLLocationManager* locationManager;

- (void)viewDidLoad {
    [super viewDidLoad];
//检测定位功能是否开启
    if([CLLocationManager locationServicesEnabled]){
        
        if(!_locationManager){
            
            self.locationManager = [[CLLocationManager alloc] init];
            
            if([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]){
                [self.locationManager requestWhenInUseAuthorization];
                [self.locationManager requestAlwaysAuthorization];
                
            }
            
            //设置代理
            [self.locationManager setDelegate:self];
            //设置定位精度
            [self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
            //设置距离筛选
            [self.locationManager setDistanceFilter:100];
            //开始定位
            [self.locationManager startUpdatingLocation];
            //设置开始识别方向
            [self.locationManager startUpdatingHeading];
            
        }
        
    }else{
        UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"您没有开启定位功能" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        [alertView addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
        [self presentViewController:alertView animated:YES completion:nil];

    }
}

这里返回一个[placemark addressDictionary]的字典 打印一下可以看到字典里面的各种key,想用哪个key直接替换掉即可

//反地理编码
- (void)reverseGeocoder:(CLLocation *)currentLocation {
    
    CLGeocoder* geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        
        NSLog(@"array == %@",placemarks);
        
        if(error || placemarks.count == 0){
            NSLog(@"error = %@",error);
        }else{
            CLPlacemark* placemark = placemarks.firstObject;
            NSLog(@"dic == %@",[placemark addressDictionary]);
            NSLog(@"placemark:%@",[[placemark addressDictionary] objectForKey:@"Street"]);
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"您的位置" message:[[placemark addressDictionary] objectForKey:@"Street"] preferredStyle:UIAlertControllerStyleAlert];
            [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
            [self presentViewController:alert animated:YES completion:nil];
        }  
    }];  
}
//定位成功以后调用
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    [self.locationManager stopUpdatingLocation];
    CLLocation* location = locations.lastObject;
    [self reverseGeocoder:location];
}

你可能感兴趣的:(iOS 开发 CoreLocation实现定位功能)