iOS----定位

2017-07-31  本文已影响0人  GrayMantis

#import "ViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface ViewController ()<CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // 需求 : 根据用户的移动距离  决定是否定位
    
    // 1.创建位置管理器
    CLLocationManager *locationManager = [[CLLocationManager alloc] init];
    self.locationManager = locationManager;
    
    // 2.请求用户授权  -->iOS8之后才有的     
    //必须要配置info.plist文件------->参见文章后面注释1
    // 无论app在前台还是后台运行,都可以定位
//    [locationManager requestAlwaysAuthorization];
    // 只有app在前台运行时,才可以定位
    [locationManager requestWhenInUseAuthorization];
    // 3.设置代理
    locationManager.delegate = self;
    
    // 设置属性
    // 位置筛选器   单位:米    用户移动了100米后再更新定位  (调用对应的代理方法)
//    locationManager.distanceFilter = 100;
//    // 期望精度   单位:米      表示系统将100.3范围内当做一个位置
//    locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    
    if ([UIDevice currentDevice].systemVersion.floatValue >= 9.0) {
        // 临时开启后台定位  一定需要配置info.plist文件----->参见文章后面注释2
        locationManager.allowsBackgroundLocationUpdates = YES;
    }
    // 4.开始定位
    [locationManager startUpdatingLocation];
//    [locationManager startUpdatingHeading];  移动方向
    [self compareDistance];
}
// 比较两点的距离    比较的是两点之间的直线距离
- (void)compareDistance
{
    // 1.北京的位置
    CLLocation *location = [[CLLocation alloc] initWithLatitude:39 longitude:115];
    
    // 2.上海的位置
    CLLocation *location1 = [[CLLocation alloc] initWithLatitude:30 longitude:120];
    
    // 比较位置  单位 米
    double distance = [location distanceFromLocation:location1];
    NSLog(@"%f",distance * 0.001);

}
/// 定位成功后调用
/// 持续调用   耗电
/// locations:放着CLLocation的数组
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    NSLog(@"%@",locations);
     //停止定位 (省电)
    [manager stopUpdatingLocation];
}
@end

image.png Requeired background modes.png

也可以用简便的可视化方法

location update.png
上一篇 下一篇

猜你喜欢

热点阅读