#
import "ViewController.h"
#
import <CoreLocation/CoreLocation.h>
@interface ViewController ()<CLLocationManagerDelegate>
/**
iOS8以后, 要定位, 必须使用位置管理器(授权), 使用 Strong 属性, 保证不被释放
*/
@property (nonatomic, strong) CLLocationManager *locationManager;
@end
@implementation ViewController
/**
如果定位方法不走
1. 没有配置 plist 键值
2. 模拟器 bug
3. 没有使用 strong 的属性
*/
- (
void)viewDidLoad {
[
super viewDidLoad];
self.locationManager = [CLLocationManager
new];
if ([self.locationManager respondsToSelector:
@selector(requestWhenInUseAuthorization)]) {
[self.locationManager requestWhenInUseAuthorization];
}
if ([self.mgr respondsToSelector:
@selector(requestWhenInUseAuthorization)]){
[self.mgr requestWhenInUseAuthorization];
}
/**
iOS9新特性 --> 临时获取后台定位权限
*/
if ([UIDevice currentDevice].systemVersion.floatValue >=
9.0) {
self.mgr.allowsBackgroundLocationUpdates = YES;
}
self.mgr.delegate = self;
[self.mgr startUpdatingLocation];
CLLocation *location1 = [[CLLocation alloc] initWithLatitude:
40 longitude:
116];
CLLocation *location2 = [[CLLocation alloc] initWithLatitude:
34.27 longitude:
108.93];
CLLocationDistance distance = [location1 distanceFromLocation:location2];
NSLog(@
"distance: %f",distance /
1000);
}
#pragma mark 代理方法
/** 当完成位置更新的时候调用 --> 次方法会频繁调用*/
- (
void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
CLLocation *location = locations.lastObject;
**/
self.locationManager.delegate = self;
[self.locationManager startUpdatingLocation];
/**
为了省电, 所有要对持续定位 app 进行优化
*/
self.locationManager.distanceFilter =
10;
NSLog(@
"self.%zd",self.locationManager.desiredAccuracy);
}
/**
当用户更新位置的时候调用此方法 频繁调用, 非常耗电
*/
- (
void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
CLLocation *location = locations.firstObject;
NSLog(@
"latitude: %f,longitude: %f",location.coordinate.latitude, location.coordinate.longitude);
}
@end
CLLocation
包括几个重要的属性:
coordinate中包含经度、维度两个属性重要的方法distanceFromLocation 计算该点与本点之间的直线距离
//CLLocation : 位置对象, 最核心的就是经纬度 //CLLocationCoordinate2D coordinate : 2D位置坐标 –> 经纬度
//CLLocationDegrees latitude; –> 纬度 //CLLocationDegrees longitude; –> 经度