iOS8之前与iOS8使用CoreLocation定位

 
iOS8之前使用CoreLocation定位一、首先定义一个全局的变量用来记录CLLocationManager对象,引入CoreLocation.framework使用#import <CoreLocation/CoreLocation.h>1    @property (nonatomic, strong) CLLocationManager  *locationManager;    二、初始化CLLocationManager并开始定位 -(CLLocationManager *)locationManager{     #warning 定位服务不可用,直接返回空  if (![CLLocationManager locationServicesEnabled]) return nil;        if (!_locationManager) {        //建立定位者        self.locationManager = [[CLLocationManager alloc]init];        //设置代理        self.locationManager.delegate = self;    }    return _locationManager;}- (void)viewDidLoad {[super viewDidLoad];    self.view.backgroundColor = [UIColor whiteColor];    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;    self.locationManager.distanceFilter = 10;    [self.locationManager startUpdatingLocation];}    三、实现CLLocationManagerDelegate的代理方法(1)获取到位置数据,返回的是一个CLLocation的数组,通常使用其中的一个    - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{    CLLocation *currLocation = [locations lastObject];    NSLog(@"经度=%f 纬度=%f 高度=%f", currLocation.coordinate.latitude, currLocation.coordinate.longitude, currLocation.altitude);}    (2)获取用户位置数据失败的回调方法,在此通知用户- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{    if ([error code] == kCLErrorDenied)    {        //访问被拒绝    }    if ([error code] == kCLErrorLocationUnknown) {        //没法获取位置信息    }}    四、在viewWillDisappear关闭定位    - (void)viewWillDisappear:(BOOL)animated{    [super viewWillDisappear:animated];    [_locationManager stopUpdatingLocation];}    iOS8中使用CoreLocation定位一、在使用CoreLocation前须要调用以下函数【iOS8专用】:iOS8对定位进行了一些修改,其中包括定位受权的方法,CLLocationManager增长了下面的两个方法:(1)始终容许访问位置信息- (void)requestAlwaysAuthorization;(2)使用应用程序期间容许访问位置数据- (void)requestWhenInUseAuthorization;示例以下: - (void)viewDidLoad {[super viewDidLoad];    self.view.backgroundColor = [UIColor whiteColor];       self.locMgr.desiredAccuracy = kCLLocationAccuracyBest;    self.locMgr.distanceFilter = 10;       #warning 定位服务,ios8之后添加这句    [self.locMgr requestAlwaysAuthorization];        [self.locMgr startUpdatingLocation];}    二、在Info.plist文件中添加以下配置:(1)NSLocationAlwaysUsageDescription(2)NSLocationWhenInUseUsageDescription
相关文章
相关标签/搜索