iOS 定位功能的实现

1、导入框架

 Xcode中添加“CoreLocation.framework”

2、导入主头文件

 #import <CoreLocation/CoreLocation.h>

3、声明管理器和代理

 @interface ViewController ()<CLLocationManagerDelegate>
 @property (nonatomic, strong) CLLocationManager* locationManager;
 @end

4、在appDelegate或控制器中 初始化管理器

//定位管理器
    self.locationManager=[[CLLocationManager alloc]init];
    
    if (![CLLocationManager locationServicesEnabled]) {
       SSLog(@"定位服务当前可能尚未打开,请设置打开!");
        //return;
    }
    
    //如果没有授权则请求用户授权
    if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined){
        [self.locationManager requestWhenInUseAuthorization];// 当使用app时获取位置
//        [self.locationManager requestAlwaysAuthorization];// 一直获取位置
    }
    //设置代理
    self.locationManager.delegate = self;
    //设置定位精度
    self.locationManager.desiredAccuracy=kCLLocationAccuracyBest;
    //定位频率,每隔多少米定位一次
    CLLocationDistance distance = 10.0;//十米定位一次
    self.locationManager.distanceFilter=distance;
    //启动跟踪定位
    [self.locationManager startUpdatingLocation];

5、代理方法

// 跟踪定位代理方法,每次位置发生变化即会执行(只要定位到相应位置)
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    CLLocation *location=[locations firstObject];//取出第一个位置
    CLLocationCoordinate2D coordinate=location.coordinate;//位置坐标
    self.coordinate = coordinate;
    SSLog(@"经度:%f,纬度:%f,海拔:%f,航向:%f,行走速度:%f",coordinate.longitude,coordinate.latitude,location.altitude,location.course,location.speed);
    //如果不需要实时定位,使用完即使关闭定位服务
    [self.locationManager stopUpdatingLocation];
}

6、在plist文件中设置

NSLocationWhenInUseUsageDescription   后面对应的是使用时对用户的说明

原文地址:https://www.cnblogs.com/shen5214444887/p/5941615.html