gpt4 book ai didi

ios - CLLocationManager 是异步的。遇到这个问题

转载 作者:行者123 更新时间:2023-11-29 05:55:03 26 4
gpt4 key购买 nike

我正在做的事情非常简单。

class HomeDatasourceController: UICollectionViewController, CLLocationManagerDelegate{
let locationManager:CLLocationManager = CLLocationManager()

//CurrentLocation is my variable that isn't changing on time
var currentLocation = CLLocation(latitude: 5.0, longitude: 5.0)

override func viewDidLoad() {
super.viewDidLoad()


locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
self.locationManager.startUpdatingLocation()


fetchHomeFeed()
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
for currentLocationTemp in locations {
self.currentLocation = currentLocationTemp
print("This is latitude: \(currentLocation.coordinate.latitude) , and this is longitude: \(currentLocation.coordinate.longitude)")
}
}
fetchHomeFeed(){
print("Hello: ", self.currentLocation)
}

当 fetchHomeFeed 被调用时,它只打印出我设置的虚拟位置(5.0 纬度和经度),而不是我的实际位置。我知道这是异步的,但我不确定如何在第一次至少一次获得调用,以便我可以正确打印出我的位置(第一次)。

我还需要它在此之后继续更新,因为我想要实时更新用户的位置。

我尝试在 func locationManager 中使用 fetchHomeFeed() ,但这多次打印出 ("Hello: ", self.currentLocation) ,并且我只希望 fetchHomeFeed() 仅被调用一次(具有正确的位置) ,之后连续调用该位置,因为我将有另一种方法使用它。

我不确定如何实现这一点。

最佳答案

来自documentation for didUpdateLocations :

locations

An array of CLLocation objects containing the location data. This array always contains at least one object representing the current location. If updates were deferred or if multiple locations arrived before they could be delivered, the array may contain additional entries. The objects in the array are organized in the order in which they occurred. Therefore, the most recent location update is at the end of the array.

因此,您不需要循环遍历位置数组,只需使用 locations.last 即可,除非您的应用程序需要担心延迟的位置更新。

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last {
currentLocation = location
}
}

如果您希望 fetchHomeFeed 仅被调用一次,有几个选项,但最简单的是一个 bool 标志,您在调用它之前检查它,并在第一次调用它时更改它。

关于ios - CLLocationManager 是异步的。遇到这个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55249660/

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