需要用户确认授权的功能。
1、导入类库
import CoreLocation
2、创建位置管理器
let locationManager = CLLocationManager()
3、请求位置
locationManager.requestWhenInUseAuthorization() // 请求授权
locationMananger.delegate = self // 指定代理对象为自己
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers // 请求位置的精度
locationManager.requestLocation() // 请求位置信息
4、info.plist
配置:privacy -Location When In Use Usage Descriotion: 描述信息用于描述获取位置信息的用途
5、代理、委托获取到位置信息:
实现协议:CLLocationManagerDelegate
// 成功获取位置执行
func locationManager(_ manager:CLLocationManager,didUpdateLocations locations: [CLLocation]){
//获取经纬度等等位置信息
let lon = locations[0].coordinate.longitude
let lat = locations[0].coordinate.latitude
}
//获取位置失败执行
func locationManager(_ manager:CLLocationManager,didFailWIthError error: Error){
print(error)
}