天天看点

使用CLLocationManager简单定位

背景:

ios开发免不了用到定位功能,Xcode已经给我们提供了这个框架,并且(好像?)只能用这个框架,因为苹果是不允许使用第三方定位的,最多就是封装了第三方定位,这里不必深究。

简介:

本文介绍<CoreLocation/CoreLocation.h>框架的简单使用,包括定位获取经纬度、通过经纬度获取对应位置信息和计算两个坐标之间的距离等。
           

核心代码:

1.首先,新建一个工程,并导入框架

#import <CoreLocation/CoreLocation.h>

2.属性

@property (nonatomic, strong) CLLocationManager *locationManager;//定位管理
@property (nonatomic, strong) NSString *latitude;//纬度
@property (nonatomic, strong) NSString *longitude;//经度
           

3.初始化定位管理

self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;//选择定位经精确度
    self.locationManager.distanceFilter = kCLDistanceFilterNone;
    //授权,定位功能必须得到用户的授权
    [self.locationManager requestAlwaysAuthorization];
    [self.locationManager requestWhenInUseAuthorization];

    [self.locationManager startUpdatingLocation];
           

4.执行代理方法

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    CLLocation *loc = [locations firstObject];

    //获得地理位置,把经纬度赋给我们定义的属性
    self.latitude = [NSString stringWithFormat:@"%f", loc.coordinate.latitude];
    self.longitude = [NSString stringWithFormat:@"%f", loc.coordinate.longitude];
    //也可以存入NSUserDefaults,方便在工程中方便获取
    [[NSUserDefaults standardUserDefaults] setValue:self.latitude forKey:@"latitude"];
    [[NSUserDefaults standardUserDefaults] setValue:self.longitude forKey:@"longitude"];

    //根据获取的地理位置,获取位置信息
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:[locations objectAtIndex:] completionHandler:^(NSArray *array, NSError *error) {
        //成功
        if (array.count > ) {
            CLPlacemark *placemark = [array objectAtIndex:];
            NSLog(@"dic ---- %@", [placemark addressDictionary]);//具体代表什么,看输出就知道了

        //失败
        }else if (error == nil && array.count == ){
            NSLog(@"无返回信息");
        }else if (error != nil){
            NSLog(@"error occurred = %@", error);//请求错误
        }
    }];
    NSLog(@"纬度=%f,经度=%f",self.latitude,self.longitude);
    [self.locationManager stopUpdatingLocation];


}
           

失败返回信息

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    if ([error code] == kCLErrorDenied)
    {
        //访问被拒绝
        NSLog(@"拒绝访问");
    }
    if ([error code] == kCLErrorLocationUnknown) {
        //无法获取位置信息
        NSLog(@"无法获取位置信息");
    }
}
           

5.到了这一步还没完,因为要授权的话我们还需要修改一下info.plist

a.右键工程的info.plist

b.选择Open As 选择Source Code

c.加入下面这段代码

<key>NSLocationAlwaysUsageDescription</key>
    <string>后台保持定位</string>
    <key>NSLocationWhenInUseUsageDescription </key>
    <string>只在程序运行时开启定位服务</string>
           

如图:

使用CLLocationManager简单定位

6.现在我们的定位功能就可以直接运行了

看输出信息:

使用CLLocationManager简单定位
使用CLLocationManager简单定位
*有时间后面会写地图的显示,定位与地图结合使用等。
本文为博主原创,转载请注明出处和链接。