Swift 精准定位一次获取:CLLocationManager 使用教程
在 Swift 中,你可以使用 CLLocationManager 类来申请一次精准定位。下面是一个示例代码:
import CoreLocation
class LocationManager: NSObject, CLLocationManagerDelegate {
private let locationManager = CLLocationManager()
private var completion: ((CLLocation?, Error?) -> Void)?
func requestLocation(completion: @escaping (CLLocation?, Error?) -> Void) {
self.completion = completion
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.requestLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else {
completion?(nil, nil)
return
}
completion?(location, nil)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
completion?(nil, error)
}
}
使用示例:
let locationManager = LocationManager()
locationManager.requestLocation { (location, error) in
if let error = error {
print('定位失败:(error.localizedDescription)')
} else if let location = location {
print('经度:(location.coordinate.longitude)')
print('纬度:(location.coordinate.latitude)')
}
}
在上面的代码中,我们创建了一个名为 LocationManager 的类,该类封装了 CLLocationManager 的功能。通过调用 requestLocation(completion:) 方法,我们可以请求一次精准定位。定位结果将通过 completion 闭包参数返回。如果定位成功,将返回一个 CLLocation 对象,包含经纬度信息;如果定位失败,将返回一个 Error 对象,表示失败的原因。
原文地址: https://www.cveoy.top/t/topic/o9k3 著作权归作者所有。请勿转载和采集!