Core Location是iOS系统提供的定位框架,很多开发者在初次使用时往往会遇到各种问题,不清楚该从哪些方面入手。下面就把开发过程中需要掌握的关键点逐一梳理。

一、核心组件CLLocationManager
CLLocationManager是Core Location的核心管理类,所有定位相关的操作都需要通过它来完成。使用前需要先创建实例并设置对应的代理,同时配置相关属性。
基础的初始化和代理设置代码如下:
import CoreLocation
class LocationManager: NSObject, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
override init() {
super.init()
// 设置代理
locationManager.delegate = self
// 设置定位精度,kCLLocationAccuracyBest为最高精度
locationManager.desiredAccuracy = kCLLocationAccuracyBest
// 设置位置更新最小距离,单位米,移动超过该距离才会回调更新
locationManager.distanceFilter = 10
}
}二、位置权限申请
iOS系统对定位权限管控严格,必须在Info.plist中配置对应的权限描述键,否则会导致应用闪退。常用的权限类型有两种:
- 使用时权限:对应键为
NSLocationWhenInUseUsageDescription,仅在应用前台运行时可以获取定位 - 始终权限:对应键为
NSLocationAlwaysAndWhenInUseUsageDescription,应用前后台都可以获取定位
申请权限的代码示例:
// 申请使用时权限 locationManager.requestWhenInUseAuthorization() // 如果需要后台定位,还需要申请始终权限 locationManager.requestAlwaysAuthorization()
三、定位配置与回调处理
配置完权限后,就可以启动定位服务,定位结果会通过代理方法回调。需要注意不同系统版本的差异,比如iOS 14之后新增了精确位置开关的配置。
启动定位和处理回调的代码:
// 启动定位
locationManager.startUpdatingLocation()
// CLLocationManagerDelegate代理方法,定位更新回调
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
// location包含经度、纬度、海拔、速度等信息
let latitude = location.coordinate.latitude
let longitude = location.coordinate.longitude
print("当前位置:纬度\(latitude),经度\(longitude)")
}
// 定位失败回调
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("定位失败,错误:\(error.localizedDescription)")
}四、地理编码与反地理编码
Core Location还提供了地理编码能力,可以把地名转换为经纬度(地理编码),也可以把经纬度转换为具体地址(反地理编码),对应的类是CLGeocoder。
反地理编码的示例代码:
let geocoder = CLGeocoder()
// 传入经纬度进行反地理编码
geocoder.reverseGeocodeLocation(location) { placemarks, error in
if let error = error {
print("反地理编码失败:\(error.localizedDescription)")
return
}
guard let placemark = placemarks?.first else { return }
// 获取详细地址信息
let address = placemark.name ?? ""
let city = placemark.locality ?? ""
print("当前地址:\(city)\(address)")
}五、后台定位配置
如果需要应用退到后台后仍然可以获取定位,除了申请始终权限外,还需要在Info.plist中配置UIBackgroundModes,添加location值,同时设置locationManager.allowsBackgroundLocationUpdates = true,注意这个属性仅在iOS 9及以上系统生效。
六、注意事项
- 不需要定位时要及时调用
locationManager.stopUpdatingLocation()停止定位,避免不必要的电量消耗 - 模拟器调试时可以手动设置模拟位置,方便测试不同场景下的定位逻辑
- 定位精度越高,耗电量越大,实际开发中可以根据需求调整
desiredAccuracy的值,不需要始终使用最高精度
Core Location的使用核心是先理清权限流程,再配置对应的定位参数,最后处理回调数据,只要把这些关键点理清楚,就能快速实现各类定位相关需求。
Core_LocationiOS定位CLLocationManager地理编码位置权限修改时间:2026-05-31 05:14:56