swift - Firebase 在 TableView 中检索和插入

标签 swift uitableview firebase swift3 firebase-realtime-database

我需要帮助来检索子项并将其添加到 TableView 中。子类称为“Title”,是“Post”的子类。我已成功检索所有帖子并打印出来,但我不知道如何将“标题”放入我的表格 View 中。

var posts = [postStruct]()


override func viewDidLoad() {
    super.viewDidLoad()


    let ref = FIRDatabase.database().reference().child("Posts")

    ref.observeSingleEvent(of: .value, with: { snapshot in
        print(snapshot.childrenCount)
        for rest in snapshot.children.allObjects as! [FIRDataSnapshot] {

        print(rest.value!)


                //need help here! I want to put the title which is a child of "Post"






        }


    })


}






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

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")

    let label1 = cell?.viewWithTag(1) as! UILabel
    label1.text = posts[indexPath.row].title
    return cell!
}

最佳答案

let ref = FIRDatabase.database().reference().child("Posts")    

ref.observeSingleEvent(of: .value, with: { snapshot in

    print(snapshot.childrenCount)

    for rest in snapshot.children.allObjects as! [FIRDataSnapshot] {

        guard let value = rest.value as? Dictionary<String,Any> else { continue }

        guard let  title = value["Title"] as? String else { continue }

        let post = postStruct(title: title)

        self.posts.append(post)
    }

    self.tableView.reloadData()
})

关于swift - Firebase 在 TableView 中检索和插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43824078/

相关文章:

ios - 使用静态单元格创 build 置场景 - 附上屏幕截图和简单测试用例

swift - 强制 TableView 单元格到一页上

Swift 4 泛型,引用自身

iphone - 即使使用 setNeedsDisplay 和 setNeedsLayout 自定义 UITableViewCell 也不会更新

ios - TouchID 错误代码 : -1004 NSLocalizedDescription: User interaction is required

ios - Firebase以离线模式启动,不会为子值触发osberve *

java - Firebase 依赖项导致 Gradle 构建错误 - 程序类型已存在

android - Kotlin + 刀柄错误。 [Hilt] 和 java.lang.reflect.InvocationTargetException(无错误消息)

ios - 快速视频流启动

Swift 运算符和 nil