//Framework框架需要使用<>
#import <CoreLocation/CoreLocation.h>
@interface ViewController () <CLLocationManagerDelegate>{
//成员变量,如果是对象, 默认是stong。 如果基本数据类型, 默认assign
//在类的内部, 使用成员变量, 不会走set、get方法, 执行速度会块
//位置管理器
CLLocationManager *_mgr;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//1. 创建位置管理器
_mgr = [CLLocationManager new];
//2. 用户授权
//当使用时授权
[_mgr requestWhenInUseAuthorization];
//3. 设置代理(为了获取定位的数据, 需要中代理方法中获取)
_mgr.delegate = self;
//4. 开始定位
[_mgr startUpdatingLocation];
//5. 距离筛选器
//单位是米。 设置了10米的间隔
//开发中要获取Mac的信息是无法做到的。 需要通过设置模拟器来实现
//如果真的需要持续定位, 这个值不需要设置过大。
_mgr.distanceFilter = 1;
}
// CLLocationManagerDelegate
/*
持续定位会涉及耗电的问题
代理方法会频繁调用
位置筛选器、过滤器: 希望方法每隔一段距离再调用
*/
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
CLLocation *location = locations.firstObject;
//CLLocationCoordinate2D coordinate: 2D位置坐标 经纬度
//持续定位还会出现垃圾数据, 如何屏蔽?
//获取当前时间进行比较, 如果差值过大就不要来
NSTimeInterval time = -[location.timestamp timeIntervalSinceNow];
if (time > 1) {
return;
//也就是忽略该条数据
}
NSLog(@"location: 纬度:%f, 经度:%f, time: %@, 差值:%f, 速度: %f", location.coordinate.latitude, location.coordinate.longitude, location.timestamp, time, location.speed);
}