将Firebase数据放入数组以放入文本视图(Swift)



所以我一直在尝试将一些Firebase数据放入Swift中的数组中,这样我就可以将其放入文本字段中。一切正常,但是,我的文本视图是空的,不包含任何行和数据。有人知道为什么会发生这种事吗?我的代码如下(我已经在顶部导入了Firebase和UIKit,不知道为什么Stack Overflow不让我把它放进去…很抱歉(:

class SummaryEmployeesFeelingViewController: UIViewController, UITableViewDataSource{
struct Feedback {
let id: Int
let feeling: String
let date: Timestamp
}

var feedbackarray = [Feedback]()
@IBOutlet weak var tableView: UITableView!
let summarydb = Firestore.firestore()
override func viewDidLoad() {
super.viewDidLoad()
addDatatoArray()
tableView.dataSource = self
tableView.tableFooterView = UIView()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return feedbackarray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let feedbackcell = tableView.dequeueReusableCell(withIdentifier: "CellReuseIdentifier")!
let text = feedbackarray[indexPath.row] as? String
feedbackcell.textLabel?.text = text
return feedbackcell
}
func addDatatoArray(){
summarydb.collection("employeefeedback").getDocuments { (snapshot, error) in
if error == nil && snapshot != nil{
for document in snapshot!.documents{
var idValue = document.get("id")
var feelingValue = document.get("feeling")
var dateValue = document.get("date")
let newEntry = Feedback(id: idValue as! Int, feeling: feelingValue as! String, date: dateValue as! Timestamp)
self.feedbackarray.append(newEntry)
}
}
}

}

}

谢谢!

获取数据后,需要重新加载tableView

func addDatatoArray(){
summarydb.collection("employeefeedback").getDocuments { (snapshot, error) in
if error == nil && snapshot != nil{
for document in snapshot!.documents{
var idValue = document.get("id")
var feelingValue = document.get("feeling")
var dateValue = document.get("date")
let newEntry = Feedback(id: idValue as! Int, feeling: feelingValue as! String, date: dateValue as! Timestamp)
self.feedbackarray.append(newEntry)
}
print("count:(self.feedbackarray.count)")
DispatchQueue.main.async {
tableView.reloadData()
}
}
}
}

同时设置表格查看代理

override func viewDidLoad() {
super.viewDidLoad()
addDatatoArray()
tableView.dataSource = self
tableView.delegate = self
tableView.tableFooterView = UIView()
}

也更新你的这个方法

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let feedbackcell = tableView.dequeueReusableCell(withIdentifier: "CellReuseIdentifier")!
let feedBack = feedbackarray[indexPath.row] as? Feedback
feedbackcell.textLabel?.text = feedBack.feeling
return feedbackcell
}