Swift 为什么没有调用locationManager(:didUpdateLocations)

Swift 为什么没有调用locationManager(:didUpdateLocations),swift,cllocationmanager,Swift,Cllocationmanager,我编写了以下测试代码 @IBAction func btnLocation(_ sender: NSButton) { let locManager = CLLocationManager() if CLLocationManager.authorizationStatus() != .authorized { print("not authorized") } locManager.delegate = self locManager.

我编写了以下测试代码

 @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()
一个实例变量来保存委托的强引用,您还需要其中的1个

locManager.startUpdatingLocation()
locManager.requestLocation()

谢谢。我在类级别上做了let locManager=CLLocationManager()声明,现在可以正常工作了。