我正在使用真实设备来获取我当前的位置,问题是locationManager.location
isnil
并且didUpdateLocations
未调用该函数。
var location = CLLocationManager()
@IBOutlet weak var map: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
map.showsPointsOfInterest = true
map.showsScale = true
map.showsUserLocation = true
locationManagerConfiguration()
}
func locationManagerConfiguration(){
location.requestAlwaysAuthorization()
location.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled(){
location.delegate = self
location.desiredAccuracy = kCLLocationAccuracyBest
location.startUpdatingLocation()
}
let sourceCoordinates = location.location?.coordinate
let sourcePlacemark = MKPlacemark(coordinate: sourceCoordinates!
这是 sourceCoordinate 为零的问题
您提供的代码与您问题中的陈述不符,但我想我在代码中看到了问题。根据苹果文档:Startupdatinglocation
location.startUpdatingLocation()
是一个需要几秒钟才能获取位置的异步函数。该函数将立即返回,但当系统获得 GPS 位置(几秒钟后,异步)时,将调用委托回调。您上面的代码正在调用startUpdatingLocation()
并立即期望出现一个值(同步,永远不会出现)。您的代码需要更像:
func locationManagerConfiguration(){
location.requestAlwaysAuthorization()
location.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled(){
location.delegate = self
location.desiredAccuracy = kCLLocationAccuracyBest
location.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// TODO: Check the array is not empty
let sourceCoordinates = locations[0]
let sourcePlacemark = MKPlacemark(coordinate: sourceCoordinates!)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Location error: \(error)")
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句