【发布时间】:2019-03-01 11:15:59
【问题描述】:
我的数据库中有数据,可以搜索单个记录,这很好。但是,当我尝试使用所有数据库记录简单地填充表视图时,它不会接收/显示任何数据。
这是我的代码:
struct drinkStruct {
let pub: String!
let rating: String!
let price: String!
}
override func viewDidLoad() {
super.viewDidLoad()
loadDrinks()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func homeClicked(_ sender: Any) {
homeClicked()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let label1 = cell.viewWithTag(1) as! UILabel
label1.text = posts[indexPath.row].pub
let label2 = cell.viewWithTag(2) as! UILabel
label2.text = posts[indexPath.row].rating
let label3 = cell.viewWithTag(3) as! UILabel
label3.text = posts[indexPath.row].price
return cell
}
func loadDrinks(){
let databaseRef = Database.database().reference().child("Drinks")
ref = Database.database().reference()
databaseRef.queryOrderedByKey().observe(.childAdded, with: { (snapshot) in
if let valueDictionary = snapshot.value as? [AnyHashable:String]
{
let pub = valueDictionary["pub"]
let rating = valueDictionary["rating"]
let price = valueDictionary["price"]
self.posts.insert(drinkStruct(pub: pub, rating: rating, price: price), at: 0)
}
})
self.tableview.reloadData()
}
我是否在做明显错误的事情?或者任何人都可以看到是什么导致没有数据加载?
没有错误/未使用的变量等。
提前致谢!
【问题讨论】:
-
回调是异步的,所以你在下载任何东西之前调用 tableView.reloadData()
-
@JoakimDanielson 感谢您的回复 - 那么我应该什么时候给它打电话?
-
你需要一个数据模型。
-
使用下面的快速枚举来获取每个数组元素的字典。在 snapshot.children.allObjects 作为饮料! [数据快照] { }
-
@JoakimDanielson 虽然这是对 那个 问题的一个很好的回答,但它与 Firebase 闭包无关,因为它们的行为不同。 Firebase 闭包中的 UI 调用在主线程上运行,因此不需要调度调用。参见this answer 以及@frankvanpuffelen 对this question 的评论。只需将
self.tableview.reloadData()移动到闭包内即可。
标签: swift firebase firebase-realtime-database