gpt4 book ai didi

swift - iOS10下CLLocationManager不报初始位置(委托(delegate)函数未被调用)

转载 作者:行者123 更新时间:2023-11-28 08:20:32 24 4
gpt4 key购买 nike

我有一个应用程序可以根据用户的位置显示一些数据。它在 Swift2 和 iOS9 上运行良好。现在没有调用 CLLocationManager 委托(delegate)的函数。 这是我的代码:

override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self //locationManager is being initialized at the top of class file and is not nil
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
locationManager.startUpdatingLocation() //This line executes from viewDidLoad, but not from delegate function
}


func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) { //This is never called
if CLLocationManager.authorizationStatus() != .authorizedWhenInUse {
locationManager.requestWhenInUseAuthorization()
}else{
locationManager.startUpdatingLocation()
}
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { //This is never called
if updatingLocation == true {
//if location is updating, go next step
}
}

我在我的 Info.plist 中启用了 Privacy - Location Always Usage Description 和 Privacy - Location When In Use Usage Description。为了测试我的代码,我还尝试调用 requestLocation,它也应该启动 didUpdateLocations,但它没有。也许我遗漏了一些东西,但对于 iOS10 的 CLLocationManager 处理似乎没有任何改变。

更新:更多代码

class HomeViewController: BaseViewController, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
var updatingLocation = true
//other stuff
}

最佳答案

viewDidLoad() 中取出所有 locationManager 委托(delegate)函数:

override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self //locationManager is being initialized at the top of class file and is not nil
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
locationManager.startUpdatingLocation()
}

func locationManager(_ manager: CLLocationManager, didDetermineState state: CLRegionState, for region: CLRegion) {
...
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
...
}

同时实现:

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Failed: \(error.localizedDescription)")
}

查看您可能遇到的错误。

关于swift - iOS10下CLLocationManager不报初始位置(委托(delegate)函数未被调用),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41430086/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com