Based on what I have read on the documentation page on Firestore, after I get the document, completion handler (aka the closure) should be called. I have the following code and I am trying to display a field from every document from a collection from Firestore but when I run the app, it doesn't work. The label from every cell isn't changed.
Later Edit: Also, scrolling through the tableview is really buggy and when you scroll down and try to scroll up again you it won't go up, it will just shake.
import UIKit
import Firebase
import FirebaseFirestore
class AnunturiViewController: UITableViewController {
var anunturi: [Produs] = [Produs]()
var docRef: DocumentReference!
var docRefNrTotalProduse: DocumentReference!
var nrTotalProduse = 0
var isDone = false
override func viewDidLoad() {
super.viewDidLoad()
fetchData()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ADCell") as! ADTableViewCell
if isDone == true {
cell.denumireAnuntLabel.text = anunturi[nrTotalProduse - indexPath.row].denumire
}
return cell
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
docRefNrTotalProduse = Firestore.firestore().collection("nrproduse").document("nrproduse")
docRefNrTotalProduse.getDocument { (snapshot, error) in
if error != nil { print(error ?? "0") }
else {
let data = snapshot?.data()
self.nrTotalProduse = data!["nrtotalproduse"] as! Int
tableView.reloadData()
}
}
return nrTotalProduse
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 164.0
}
@IBAction func onRefreshButtonPressed(_ sender: UIBarButtonItem) {
tableView.reloadData()
}
func fetchData() {
var i = 0
while(i < nrTotalProduse) {
docRef = Firestore.firestore().collection("produse").document(String(nrTotalProduse - i))
docRef.getDocument { (snapshot, error) in
let data = snapshot?.data()
let produs = Produs(denumire: (data?["nume"] as? String)!)
self.anunturi.append(produs)
DispatchQueue.main.async {
if i == self.nrTotalProduse - 1 {
self.isDone = true
self.tableView.reloadData()
}
}
}
i += 1
}
}
}