免费开源的iOS开发学习平台

定位服务:2-CoreLocation框架的基本使用

本节的示例代码,使用CoreLocation框架来获取设备的位置信息,包括经度、纬度以及海拔高度信息。

准备工作

在使用CoreLocation框架之前,需要提前导入CoreLocation框架。

在info.plist文件中,添加提示信息,用户请求用户授权使用设备的位置信息。

使用Storyboard搭建如下的界面,添加三个UITextField控件,用于显示设备当前的经度、纬度以及海拔高度,并建立UITextField控件与控制器类的连线。

引入CoreLocation框架的头文件,并为控制器类添加一个CLLocationManager类的属性。

#import <CoreLocation/CoreLocation.h>
@interface ViewController () <CLLocationManagerDelegate>
@property (weak, nonatomic) IBOutlet UITextField *lngTextField;
@property (weak, nonatomic) IBOutlet UITextField *latTextField;
@property (weak, nonatomic) IBOutlet UITextField *heightTextField;
@property (nonatomic, strong) CLLocationManager *locationManager;
@end

实例化CLLocationManager对象

在locationManager属性的getter方法中,设置其相关属性。

- (CLLocationManager *)locationManager{
    if (_locationManager == nil) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;//精度设置
        _locationManager.distanceFilter = 1000.0f;//设备移动后获得位置信息的最小距离
        _locationManager.delegate = self;
        [_locationManager requestWhenInUseAuthorization];//弹出用户授权对话框,使用程序期间授权
    }
    return _locationManager;
}

在viewDidAppear:方法中开始定位。

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.locationManager startUpdatingLocation];
}

控制器视图消失时,停止定位。

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.locationManager stopUpdatingLocation];
}

CLLocationManagerDelegate代理方法的实现

在CLLocationManagerDelegate代理方法中,我们可以获取到当前的定位信息,因此,我们可以从locationManager属性中取出当前的位置信息,并更新到界面的UITextField中。

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    self.lngTextField.text = [NSString stringWithFormat:@"%3.5f",self.locationManager.location.coordinate.longitude];//获取经度
    self.latTextField.text = [NSString stringWithFormat:@"%3.5f",self.locationManager.location.coordinate.latitude];//获取纬度
    self.heightTextField.text = [NSString stringWithFormat:@"%3.5f",self.locationManager.location.altitude];//获取高度
}

当定位失败时,可以打印出定位失败的原因。

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    NSLog(@"%@",error);
}

运行程序后,系统会首先给用户请求提示,然后显示当前的位置信息。

示例代码

https://github.com/99ios/17.2.2