ios8之后使用CLLocationManager进行定位

    xiaoxiao2024-04-19  6

    在ios8或者之后的关于定位的简单使用:

    ios8之后使用定位框架有些变化,下面简单了解一下过程

    首先需要导入框架:CoreLocation.framework

    注意:需要配置info.plist文件,增加两个key:NSLocationWhenInUseUsageDescription 和 NSLocationAlwaysUsageDescription, key值自己写.

    配置好文件,写好代码,首次运行安装打开会提示需要获取位置权限

    测试代码如下:

    #import "ViewController.h" #import <CoreLocation/CoreLocation.h> @interface ViewController ()<CLLocationManagerDelegate> @property (nonatomic, strong) CLLocationManager *locationManger; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // 1.创建定位管理者 CLLocationManager *locationManager = [[CLLocationManager alloc] init]; self.locationManger = locationManager; // 2.想用户请求授权(iOS8之后方法) 必须要配置info.plist文件 if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) { // 以下方法选择其中一个 // 请求始终授权 无论app在前台或者后台都会定位 // [locationManager requestAlwaysAuthorization]; // 当app使用期间授权 只有app在前台时候才可以授权 [locationManager requestWhenInUseAuthorization]; } // 距离筛选器 单位:米 100米:用户移动了100米后会调用对应的代理方法didUpdateLocations // kCLDistanceFilterNone 使用这个值得话只要用户位置改动就会调用定位 locationManager.distanceFilter = 100.0; // 期望精度 单位:米 100米:表示将100米范围内看做一个位置 导航使用kCLLocationAccuracyBestForNavigation locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation; // 3.设置代理 locationManager.delegate = self; // 4.开始定位 (更新位置) [locationManager startUpdatingLocation]; // 5.临时开启后台定位 iOS9新增方法 必须要配置info.plist文件 不然直接崩溃 locationManager.allowsBackgroundLocationUpdates = YES; // 计算两个点之间的直线距离 [self compareDistance]; } // 比较两点之间的距离 --直线距离 - (void)compareDistance { // 北京的位置 CLLocation *location = [[CLLocation alloc] initWithLatitude:39 longitude:115]; // 上海的位置 CLLocation *location1 = [[CLLocation alloc] initWithLatitude:30 longitude:120]; // 比较距离 单位:米 CGFloat distance = [location distanceFromLocation:location1]; // 打印一下距离 NSLog(@"%f",distance / 1000); } // 当定位到用户位置时调用 // 调用非常频繁(耗电) - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations { // 一个CLLocation对象代表一个位置 NSLog(@"%@",locations); // 停止定位 // [manager stopUpdatingLocation]; } @end

    转载请注明原文地址: https://ju.6miu.com/read-1288145.html
    最新回复(0)