iOS定位和地图功能要用到两个框架:mapkitcoreLocation
两个专门术语:lbs(Location Based Service)基于定位服务的APP和solomo(Social Local Mobile)社交+本地+手机。
- CoreLocation
1.导入框架,导入头文件。
2.创建CALocationManager对象。
3.设置代理。
4.实现方法
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations这个方法调用频率很高,一般情况下需要在该方法下写
停止语句。
#import "ViewController.h" #import <CoreLocation/CoreLocation.h> @interface ViewController () <CLLocationManagerDelegate> @property (nonatomic,strong) CLLocationManager *manager;//注意点 @end @implementation ViewController - (CLLocationManager *)manager { if(!_manager) { _manager = [[CLLocationManager alloc]init]; _manager.delegate = self; } return _manager; } - (void)viewDidLoad { [super viewDidLoad]; [self.manager startUpdatingLocation];//开启定位 } - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { NSLog(@"%@",locations); [self.manager stopUpdatingLocation];//停止定位 }
注意点:要把CoreLocation对象设为全局变量,不然方法走完就被销毁了。
在info.plist里添加Privacy - Location Usage Description,增加描述(非必选)。
iOS8实现方法定位服务
#import "ViewController.h" #import <CoreLocation/CoreLocation.h> @interface ViewController () <CLLocationManagerDelegate> @property (nonatomic,strong) CLLocationManager *manager; @end @implementation ViewController - (CLLocationManager *)manager { if(![CLLocationManager locationServicesEnabled]) { NSLog(@"不可用"); } if(!_manager) { _manager = [[CLLocationManager alloc]init]; _manager.delegate = self; if([[[UIDevice currentDevice]systemVersion]doubleValue]>8.0) { [_manager requestWhenInUseAuthorization];//前台定位。 //[_manager requestAlwaysAuthorization];//前后台同时定位。 } } return _manager; } - (void)viewDidLoad { [super viewDidLoad]; [self.manager startUpdatingLocation];//开启定位 } - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { NSLog(@"%@",locations); [self.manager stopUpdatingLocation];//停止定位 }
在 info.plist里加入对应的缺省字段 ,值设置为YES(前台定位写上边字段,前后台定位写下边字段)
NSLocationWhenInUseUsageDescription //允许在前台获取GPS的描述
NSLocationAlwaysUsageDescription //允许在前、后台获取GPS的描述
为了严谨期间,应该先判断用户是否打开了定位服务,在进行后续的代码。
if(![CLLocationManager locationServicesEnabled]) { NSLog(@"服务不可用"); return nil; }
@property(assign, nonatomic) CLLocationDistance distanceFilter;//每隔多少米定位一次 @property(assign, nonatomic) CLLocationAccuracy desiredAccuracy;//定位的精确程度 //desiredAccuracy的取值 extern const CLLocationAccuracy kCLLocationAccuracyBestForNavigation __OSX_AVAILABLE_STARTING(__MAC_10_7,__IPHONE_4_0);//最好的专门为导航准备 extern const CLLocationAccuracy kCLLocationAccuracyBest;//最好的 extern const CLLocationAccuracy kCLLocationAccuracyNearestTenMeters;//误差几十米之内 extern const CLLocationAccuracy kCLLocationAccuracyHundredMeters;//误差几百米之内 extern const CLLocationAccuracy kCLLocationAccuracyKilometer;//误差一千米 extern const CLLocationAccuracy kCLLocationAccuracyThreeKilometers;//误差三千米
精确度越高,越耗电。