如何在iOS 8中使用CoreLocation定位

来源:互联网 发布:mac怎么打开html文件 编辑:程序博客网 时间:2024/05/29 03:16

在iOS 8中,苹果已经强制开发者在请求定位服务时获得用户的授权,此外iOS状态栏中还有指示图标,提示用户当前应用是否正在使用定位服务。另外在iOS 8中,苹果进一步改善了定位服务,让开发者请求定位服务时需要向用户提供更多的透明。此外,iOS 8中还支持让应用开发者调用全新的“访问监控”功能,当用户允许后应用才能获得更多的定位数据。

如何在iOS 8中使用CoreLocation定位

iOS 8以前使用CoreLocation定位

1、首先定义一个全局的变量用来记录CLLocationManager对象,引入CoreLocation.framework使用#import <CoreLocation/CoreLocation.h>

?
1
@property (nonatomic, strong) CLLocationManager  *locationManager;

2、初始化CLLocationManager并开始定位

?
1
2
3
4
5
self.locationManager = [[CLLocationManager alloc]init];
_locationManager.delegate = self;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
_locationManager.distanceFilter = 10;
[_locationManager startUpdatingLocation];

3、实现CLLocationManagerDelegate的代理方法

(1)获取到位置数据,返回的是一个CLLocation的数组,一般使用其中的一个。

?
1
2
3
4
5
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *currLocation = [locations lastObject];
    NSLog(@"经度=%f 纬度=%f 高度=%f", currLocation.coordinate.latitude, currLocation.coordinate.longitude, currLocation.altitude);
}

(2)获取用户位置数据失败的回调方法,在此通知用户

?
1
2
3
4
5
6
7
8
9
10
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    if ([error code] == kCLErrorDenied)
    {
        //访问被拒绝
    }
    if ([error code] == kCLErrorLocationUnknown) {
        //无法获取位置信息
    }
}

4、在viewWillDisappear关闭定位

?
1
2
3
4
5
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_locationManager stopUpdatingLocation];
}

iOS 8中使用CoreLocation定位

1、在使用CoreLocation前需要调用如下函数【iOS 8专用】:

iOS 8对定位进行了一些修改,其中包括定位授权的方法,CLLocationManager增加了下面的两个方法:

(1)始终允许访问位置信息

- (void)requestAlwaysAuthorization;

(2)使用应用程序期间允许访问位置数据

- (void)requestWhenInUseAuthorization;

示例如下:

?
1
2
3
4
5
6
self.locationManager = [[CLLocationManager alloc]init];
_locationManager.delegate = self;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
_locationManager.distanceFilter = 10;
[_locationManager requestAlwaysAuthorization];//添加这句
[_locationManager startUpdatingLocation];

2、在Info.plist文件中添加如下配置:

(1)NSLocationAlwaysUsageDescription

(2)NSLocationWhenInUseUsageDescription

这两个键的值就是授权alert的描述,示例配置如下[勾选Show Raw Keys/Values后进行添加]:

如何在iOS 8中使用CoreLocation定位

总结:

iOS 8对定位进行了一些修改,其中包括定位授权的方法,CLLocationManager增加了以下两个方法:

Added -[CLLocationManager requestAlwaysAuthorization]

Added -[CLLocationManager requestWhenInUseAuthorization]

在使用定位服务前需要通过上面两个方法申请授权:

[CLLocationManager requestAlwaysAuthorization] 授权使应用在前台后台都能使用定位服务

-[CLLocationManager requestWhenInUseAuthorization] 授权则与之前的一样

另外,在使用这两个方法授权前,必须在info.plist中增加相应的键值( NSLocationAlwaysUsageDescription、NSLocationWhenInUseUsageDescription),这两个键的值就是授权alert的描述。

0 0