标签:
CoreLocation导入框架 :#import <CoreLocation/CoreLocation.h>
需要了解的基本的属性和方法:
属性:
方法:
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
- (void)locationManager:(CLLocationManager *)manager didEnterRegion:(CLRegion *)region
- (void)locationManager:(CLLocationManager *)manager didExitRegion:(CLRegion *)region
CoreLocatio定位的基本操作:
在ios8后,系统不会默认帮我们调用定位授权,需要我们自己主动要求用户给我们授权,我们需要调用此方法:
[self.mgr requestAlwaysAuthorization];
并且我们还需要在info.plist文件中配置:
NSLocationWhenInUseDescription,允许在前台获取GPS的描述
NSLocationAlwaysUsageDescription,允许在后台获取GPS的描述
#import "ViewController.h" #import <CoreLocation/CoreLocation.h> @interface ViewController ()<CLLocationManagerDelegate> /** * 定位管理者 */ @property (nonatomic ,strong) CLLocationManager *mgr; @end @implementation ViewController // 懒加载 // 创建CoreLocation管理者 - (CLLocationManager *)mgr { if (!_mgr) { _mgr = [[CLLocationManager alloc] init]; } return _mgr; } - (void)viewDidLoad { [super viewDidLoad]; // 设置代理监听获取到的位置 self.mgr.delegate = self; // 判断是否是iOS8 if([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) { NSLog(@"是iOS8"); // 主动要求用户对我们的程序授权, 授权状态改变就会通知代理 [self.mgr requestAlwaysAuthorization]; }else { // 开始监听(开始获取位置) [self.mgr startUpdatingLocation]; } } // 授权状态发生改变时调用 - (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status { if (status == kCLAuthorizationStatusNotDetermined) { NSLog(@"等待用户授权"); }else if (status == kCLAuthorizationStatusAuthorizedAlways || status == kCLAuthorizationStatusAuthorizedWhenInUse) { NSLog(@"授权成功"); // 开始定位 [self.mgr startUpdatingLocation]; }else { NSLog(@"授权失败"); } } #pragma mark - CLLocationManagerDelegate // 获取到位置信息之后就会调用(调用频率非常高) - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { // 定位的信息 // CLLocation *location = [locations lastObject]; }
标签:
原文地址:http://www.cnblogs.com/GeekStar/p/4451074.html