iOS开发基础篇-CoreLocation定位服务

来源:互联网 发布:淘宝怎么把排名靠前 编辑:程序博客网 时间:2024/06/10 05:42

一:方法以及属性说明

1.CLLocationManager

CLLocationManager的常用操作和属性
    locManager = [[CLLocationManager alloc]init];
          //设置每隔100米更新位置
          locManager.distanceFilter = 100;
          //设置位置精度
    locManager.desiredAccuracy = kCLLocationAccuracyBest; 
//设置代理    locManager.delegate = self;

开始用户定位- (void)startUpdatingLocation;

停止用户定位- (void) stopUpdatingLocation;
 当调用了startUpdatingLocation方法后,就开始不断地定位用户的位置,中途会频繁地调用代理的下面方法

  - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations;

//协议中的方法,作用是每当位置发生更新时会调用的委托方法-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{    CLLocation * loc = [locations firstObject];
// 拿到经纬度
    float longitude = loc.coordinate.longitude;    float latitude = loc.coordinate.latitude;}
//当位置获取或更新失败会调用的方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSString *errorMsg = nil;
    if ([error code] == kCLErrorDenied) {
        errorMsg = @"访问被拒绝";
    }
    if ([error code] == kCLErrorLocationUnknown) {
        errorMsg = @"获取位置信息失败";
    }
    
    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Location"
                                                      message:errorMsg delegate:self cancelButtonTitle:@"Ok"otherButtonTitles:nil, nil];
    [alertView show];
}


二:demo地址:

    https://github.com/qisimao/CoreLocationDemo


三:急速补充

刚才博客已经发出去了,突然想到一个问题,在iOS8上使用定位还需要在配置一些文件信息,希望来得及。

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

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

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

  - (void)requestAlwaysAuthorization;

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

  - (void)requestWhenInUseAuthorization;

  示例如下:

  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对定位进行了一些修改,其中包括定位授权的方法,CLLocationManager增加了以下两个方法:

  Added -[CLLocationManager requestAlwaysAuthorization]

  Added -[CLLocationManager requestWhenInUseAuthorization]

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

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

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

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


0 0
原创粉丝点击