为什么位置管理器在 viewDidLoad 中为 nil 并且 didUpdateLocations func 没有被调用 我使用的是真实设备?

阿拉曼杜

我正在使用真实设备来获取我当前的位置,问题是locationManager.locationisnil并且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] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

Related 相关文章

热门标签

归档