我使用swift和firestore,firebase。 我想将数据放到tableView上。
我使用Firestore和Querying,但在表格视图中,数据未显示.. 如何在表格中显示数据?
import UIKit
import Firebase
class JjimVC: UITableViewController {
var tours:[Tour_] = []
override func viewDidLoad() {
super.viewDidLoad()
let db = Firestore.firestore()
let uid = Auth.auth().currentUser?.uid as! String
var ref = db.collection("userTourRelations").whereField("state", isEqualTo: 1).whereField("user", isEqualTo: uid).getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
let tourRef = db.collection("tours").document(document.data()["tour"] as! String)
let tour = Tour_()
tourRef.getDocument { (document, error) in
if let document = document, document.exists {
tour.id = document.documentID
tour.name = document.data()!["name"] as! String
tour.creator = document.data()!["creator"] as! String
tour.timeLimit = document.data()!["timeLimit"] as! Int
tour.detail = document.data()!["detail"] as! String
tour.createDate = document.data()!["createDate"] as! Date
tour.updateDate = document.data()!["updateDate"] as! Date
} else {
print("Document does not exist")
}
}
self.tours.append(tour)
}
}
}
self.tableView.reloadData()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem
}
答案 0 :(得分:0)
你有许多异步调用考虑使用DispatchGroup
let dGroup = DispatchGroup() /// 1
//
var ref = db.collection("userTourRelations").whereField("state", isEqualTo: 1).whereField("user", isEqualTo: uid).getDocuments() { (querySnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in querySnapshot!.documents {
dGroup.enter() /// 2
let tourRef = db.collection("tours").document(document.data()["tour"] as! String)
let tour = Tour_()
tourRef.getDocument { (document, error) in
if let document = document, document.exists {
tour.id = document.documentID
tour.name = document.data()!["name"] as! String
tour.creator = document.data()!["creator"] as! String
tour.timeLimit = document.data()!["timeLimit"] as! Int
tour.detail = document.data()!["detail"] as! String
tour.createDate = document.data()!["createDate"] as! Date
tour.updateDate = document.data()!["updateDate"] as! Date
self.tours.append(tour)
dGroup.leave() /// 3
} else {
print("Document does not exist")
}
}
}
}
}
dGroup.notify(queue: .main) { //// 4
self.tableView.reloadData()
}