ios - 在加载 View iOS 之前从 Firebase 检索数据

标签 ios swift firebase firebase-realtime-database

我正在开发一款应用,其中用户拥有特定数量的帖子。为了跟踪用户拥有的帖子数量,在 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
}

这是数据库的结构。

enter image description here

我认为问题可能是在检索数据之前 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/

相关文章:

ios - FooterView 未显示在 Storyboard UICollectionView 中

javascript - 如何减少 Firebase bundle 的大小?

android - FirebaseAuth.getInstance() 总是返回 null

iOS 9 - 广告资源不可用

ios - 图像拖放 ios 喜欢 happn 应用程序

ios - 使用水龙头关闭 UIKeyboard 时如何忽略所有 UIControl 水龙头

快速错误: Could not find an overload for '&&' that accepts the supplied arguments

ios - RESTKit POST 请求教程

ios - 当排列的 subview 的高度均为零时,UIStackView 高度不为 0

firebase - 带有 Firebase 的 Google 云平台