【问题标题】:Wait for separate data class to get data from firestore before updating tableView in viewcontroller?在更新视图控制器中的 tableView 之前等待单独的数据类从 firestore 获取数据?
【发布时间】:2021-04-13 17:02:14
【问题描述】:

我有一个单独的类,它从 firestore 加载和存储我的数据。 在我的视图控制器中,我创建了一个数据类的实例,并在 viewdidload 中调用了 dataClass.pullfromfirestore(),它将我的 firestore 数据加载到该类中。

我需要等待 firebase 获取我的数据,然后重新加载我的 tableview。我该怎么做?

如果我的 pullfromfirestore 函数在我的视图控制器中,我可以在函数内部调用 dispatchqueue.main.async{tableview.reloadData()},但当然这个函数是另一个类,所以我不能这样做。

【问题讨论】:

  • 我需要等待。你没有。在异步完成闭包内重新加载表视图,或者使用一种方式在数据可用时通知
  • 我应该把异步完成闭包放在哪里?我不能把它放在我的数据类中
  • 然后在pullfromfirestore()中添加另一个完成处理程序

标签: swift firebase google-cloud-firestore


【解决方案1】:

一种方法是传递某种回调函数——当 Firestore 调用完成时调用的函数。

类似:

func pullFromFirestore(completion: @escaping () -> Void) {
  let docRef = db.collection("cities").document("SF")

  docRef.getDocument { (document, error) in
    if let document = document, document.exists {
        let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
        print("Document data: \(dataDescription)")
        completion() //<-- Here
    } else {
        print("Document does not exist")
    }
  }
}

在您的视图控制器中:

dataClass.pullFromFirestore(completion: { [weak self] in
  dispatchqueue.main.async{ self?.tableview.reloadData() }
})

如果您愿意,您还可以通过回调函数将数据传回。

【讨论】:

  • 谢谢,太好了,以前从未遇到过回调函数
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-12
  • 2017-06-29
  • 1970-01-01
  • 1970-01-01
  • 2016-02-12
  • 1970-01-01
  • 2018-09-05
相关资源
最近更新 更多