当我启动我的应用程序时,它应该显示我的数据库中所有各方的名称和位置数据,但事实并非如此。我很确定我得到了正确的数据,但我不知道什么是错的。如何让我的表显示所有数据并在每次添加新数据时更新?
import UIKit
import Firebase
import FirebaseDatabase
class FindPartiesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var parties = [party]()
@IBOutlet weak var partyTable: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
partyTable.delegate = self
partyTable.dataSource = self
let ref = FIRDatabase.database().reference()
ref.child("parties").queryOrderedByKey().observe(.childAdded, with: {
snapshot in
let snapshotValue = snapshot.value as? NSDictionary
let name = snapshotValue?["name"] as! String
let location = snapshotValue?["location"] as! String
let description = snapshotValue?["description"] as! String
self.parties.append(party(name: name, description: description, location: location))
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// creates the number of cells in the table
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return parties.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Make table cells the show the user name
var cell = partyTable.dequeueReusableCell(withIdentifier: "Cell")
let nameLabel = cell?.viewWithTag(1) as! UILabel
nameLabel.text = parties[indexPath.row].name
let locationLabel = cell?.viewWithTag(2) as! UILabel
locationLabel.text = parties[indexPath.row].location
return cell!
}
}
这是我的数据库设置:
testApp
parties
-KUUzxkssjWoSZ22QS8r
description: ""
location: "Here"
name: "party 1"
-KUV0ObFVbPyI_SJ0f3F
description: ""
location: "There"
name: "party 2"
答案 0 :(得分:2)
更新数据模型后需要重新加载表格视图:
ref.child("parties").queryOrderedByKey().observe(.childAdded, with: {
snapshot in
let snapshotValue = snapshot.value as? NSDictionary
let name = snapshotValue?["name"] as! String
let location = snapshotValue?["location"] as! String
let description = snapshotValue?["description"] as! String
self.parties.append(party(name: name, description: description, location: location))
DispatchQueue.main.async {
partyTable.reloadData()
}
})