首页 > 解决方案 > 将 Firebase 文档计数作为表行计数返回

问题描述

我有一个函数可以获取集合中 firestore 文档的计数,我想将此计数用作表视图函数 numberOfRowsInSection 的返回值。在从服务器检索计数并使程序崩溃之前调用 return。我相信我需要使用闭包来让返回等待完成,但我不确定如何从闭包中返回一个整数。我对 swift 非常陌生,甚至对 Closures 也很陌生。

func getCount(completion: @escaping (Int) -> (Int)) {
    let today = getToday()
    let eventsRef = db.collection("users").document("test@test.com").collection(today)
     eventsRef.getDocuments() { (querySnapshot, err) in

            if let err = err {
                print("Error getting documents: \(err)")

            } else {
                completion((querySnapshot?.count)!)
            }

    }

    }

 override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {


        getCount { (count) in

            self.count = count
        }

        return count!

    }

标签: iosswiftuitableviewfirebasegoogle-cloud-firestore

解决方案


您需要设置一个实例数组

var arr = [<#typeHere#>]()

//

返回它的计数

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
   return arr.count
}

并在此处重新加载表格

func getCount(completion: @escaping (Int) -> (Int)) {
  let today = getToday()
  let eventsRef = db.collection("users").document("test@test.com").collection(today)
  eventsRef.getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        }  
         // fill the array here  
         tableView.reloadData() // if it's a background thread embed code in DispatchQueue.main.async {---}
    }
}

推荐阅读