我正在开发一款应用,其中用户拥有特定数量的帖子。为了跟踪用户拥有的帖子数量,在 FirebaseDatabase 中有一个存储此数字的值。
我需要在加载我的 Collection View 之前检索这个值。
以下是我如何从 Firebase 检索此值:
var count = 0
private func retrievePostCount() {
let userID = Auth.auth().currentUser?.uid
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let count = value?["postCount"] as? Int ?? 0
self.count = count
}) { (error) in
print(error.localizedDescription)
}
}
我在加载 View 之前调用此方法。
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
retrievePostCount()
}
检索数据后,我会在分配单元格编号时调用计数。
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.count
}
这是数据库的结构。
我认为问题可能是在检索数据之前 View 加载速度过快。我该如何解决这个问题?
最佳答案
设置 count
后从 api 检索,您需要重新加载 collectionView
如下所示,以便从 numberOfItemsInSection
返回您的新计数方法,
ref.child("users").child(userID!).observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let count = value?["postCount"] as? Int ?? 0
self.count = count
// Reloading collectionView to reflect the new count
self.collectionView.reloadData()
}) { (error) in
print(error.localizedDescription)
}
关于ios - 在加载 View iOS 之前从 Firebase 检索数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51272647/