首页 > 解决方案 > Swift 存储在 Firebase 数据库中的数据未出现在 tableview 中

问题描述

我正在 Swift 中创建一个餐厅评级应用程序,供用户发布对某些餐厅的评论。该应用程序不需要用户注册或登录,因此我认为我不需要用户 ID。我可以成功地将用户评论引导到数据库中的特定餐厅,因此每家餐厅都有自己的评论部分(存储为下面的 locationName)。添加评论没有问题。不过,我似乎无法将 firebase 数据库中的评论显示到应用程序中。这是我的代码,非常感谢您的帮助,非常感谢您!

var comments = [String]()
var locationName = String() // created a specific node for each restaurant to display comments in the database
var ref: DatabaseReference?
var databaseHandle: DatabaseHandle?


func loadComments() { //in viewDidLoad

    ref = Database.database().reference()

    databaseHandle = ref?.child("comments").child(locationName).observe(.childAdded, with: { (snapshot) in

        let comment = snapshot.value as? String

        if let actualComment = comment {

            self.comments.append(actualComment)

            self.tableView.reloadData()

        }
    })


func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
    return comments.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
    let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "CellFour")
    cell.textLabel!.text = comments[indexPath.row]
    return cell
}

标签: swiftfirebasefirebase-realtime-database

解决方案


推荐阅读