为什么不调用 locationManager (:didUpdateLocations)

Why is locationManager (:didUpdateLocations) not called

我写了下面的测试代码

 @IBAction func btnLocation(_ sender: NSButton) {
    let locManager = CLLocationManager()
    if CLLocationManager.authorizationStatus() != .authorized {
        print("not authorized")
    }
    locManager.delegate = self
    locManager.desiredAccuracy = kCLLocationAccuracyBest
    locManager.startUpdatingLocation()
    locManager.requestLocation()
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations[0]
    print(location.coordinate.latitude)
    manager.stopUpdatingLocation()
    let geoCoder = CLGeocoder()
    geoCoder.reverseGeocodeLocation(location, completionHandler: {(places, error) in
        let place: CLPlacemark = places![0]
        print(place.administrativeArea!)
    })
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print(error)
}

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    print("authorization changed")
}

但是 locationManager(:didUpdateLocations) 没有被调用,也没有打印错误。如果我删除 locationManager(:didFailWithError) 方法而不是开始工作并且打印位置坐标但 Xcode 还声称“代表必须响应 locationManager:didFailWithError: 我的代码有什么问题?

你需要

let locManager = CLLocationManager()

一个实例变量来保存委托的强引用,你也需要其中之一

locManager.startUpdatingLocation()
locManager.requestLocation()