swift - 为什么是locationManager(:didUpdateLocations) not called

标签 swift cllocationmanager

我编写了以下测试代码

 @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 还声称“委托(delegate)必须响应 locationManager:didFailWithError: 我的代码有什么问题吗?

最佳答案

你需要做

let locManager = CLLocationManager()

一个实例变量来保存委托(delegate)的强引用,您也需要其中 1 个

locManager.startUpdatingLocation()
locManager.requestLocation()

关于swift - 为什么是locationManager(:didUpdateLocations) not called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54271155/

相关文章:

iPhone:核心位置弹出问题

objective-c - swift 2 : no delegate callbacks for push notifications as opposed to objective-c

iOS - 使用设置和取消按钮打开定位服务 - 如何捕获取消按钮点击

ios - 为什么这个 UIAlertController 不显示?

swift - 如何在swift中获取数组的元素类型

iphone - iPhone 中的 CLLocationManager 和航向度数

ios - 在执行 UI 测试期间更新模拟器中的位置

ios - CLLocationManager startMonitoringForRegion 会使用 desiredAccuracy 吗?

swift - 带有空初始化的协议(protocol)

ios - 从 JSON 解析返回数据 - Swift