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

标签 ios swift asynchronous cllocation

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

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/

相关文章:

ios - 如何自动调用 UITableViewDelegate 和 UITableViewDataSource 方法?

ios - Swift:函数调用之间的区别

iphone - 我不明白如何让 UIButton 来激活 iPhone LED

asynchronous - 使用异步Rust时,如何解决 “ld: can' t写入输出文件错误?

javascript - Array.prototype.map() 之后的下一个函数可以安全地假设映射中的所有回调都已返回吗?

javascript - 使用 Promises 等待嵌套的异步任务

ios - 如何从 Storyboard单元测试单元

ios - 当前用户重新登录后 Firebase 无法正常工作

ios - 如何在表格 View 单元格的背景中设置图像动画

ios - UICollectionView | UICollectionView |电池可重复使用