swift - 数据未显示在 Firebase 的 TableView 中

标签 swift firebase uitableview firebase-realtime-database

在 Firebase 的表格中显示数据时,我遇到了 2 个问题。

  1. Firebase 的 TableView 中未显示任何内容
  2. 我无法向变量添加链接(子)

打印正常。我可以访问 Firebase,但没有向 TableView 添加任何内容。请查看我的代码并更正我错的地方。

这是我的模型

class Exercises {

    var titleExercise = ""
    var descriptionExercise = ""

    init (titleExercise: String, descriptionExercise: String) {

        self.titleExercise = titleExercise
        self.descriptionExercise = descriptionExercise
    }
}

这是我的 View Controller

class ExercisesViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {




    //MARK: Properties
    var refWorkout: String = ""
    var workout: TrainingProgram?
    var ref: DatabaseReference!


    @IBOutlet weak var tableView: UITableView!
    var exercises = [Exercises]()


    //MARK: Methods
    override func viewDidLoad() {
        super.viewDidLoad()

        fetchExercises()
        tableView.dataSource = self
        tableView.delegate = self

        refWorkout = workout!.title





    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as!  ExercisesTableViewCell

        let workouts = exercises[indexPath.item]
        cell.titleLabel.text = workouts.titleExercise
        cell.descriptionLabel.text = workouts.descriptionExercise

        return cell
    }

    func fetchExercises() {
        Database.database().reference().child("programs").child("OPEN SPACE").child("exercises").observe(.childAdded) { (snapshot) in
            print(snapshot.value)
            if let dict = snapshot.value as? [String: AnyObject] {
                let newTitle = dict["title"] as! String
                let newDescription = dict["description"] as! String
                let exerciseTableCell = Exercises(titleExercise: newTitle, descriptionExercise: newDescription)

            }
        }
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }


    }


}

我有第二个问题。它还解决了这个问题。 如您所见,我有 refWorkout = workout!.title 这是之前 ViewController 的标题,refWorkout 是 Firebase 的子项。如果我将编写下一个代码

ref = Database.database().reference().child("programs").child(refWorkout).child("exercises")

   ref.observe(.childAdded) { (snapshot) in
       print(snapshot.value)
   }

一切都会好起来的。打印将起作用。但是如果我将这段代码插入到 func fetchExercises() -> 它看起来像

func fetchExercises() {
        Database.database().reference().child("programs").child(refWorkout).child("exercises").observe(.childAdded)...

我的应用崩溃了。 请帮我解答两个问题。谢谢!

我的 Firebase 结构 image

最佳答案

这是一个常见的错误,您过早地重新加载 TableView 并且没有将结果分配/附加到数据源数组

observe API 异步工作,将重新加载 TableView 的行放到闭包中

func fetchExercises() {
    Database.database().reference().child("programs").child("OPEN SPACE").child("exercises").observe(.childAdded) { (snapshot) in
        print(snapshot.value)
        if let dict = snapshot.value as? [String: Any] { // most likely all values are value type
            let newTitle = dict["title"] as! String
            let newDescription = dict["description"] as! String
            let exercise = Exercises(titleExercise: newTitle, descriptionExercise: newDescription)
            self.exercises.append(exercise)

        }
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    }
}

旁注:

您的类(class)包含 3 个不良做法:

  1. 集合类型中使用的语义对象应以单数形式命名。
  2. 如果有初始值设定项,则不要声明具有默认值的属性。
  3. 变量名冗余信息过多

在大多数情况下,结构甚至常量就足够了。我会推荐

struct Exercise {
    let title : String
    let description : String
}

在结构中,您可以免费获得初始化程序。

关于swift - 数据未显示在 Firebase 的 TableView 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56199217/

相关文章:

angularjs - 循环遍历 firebase 数据库对象并 ng-repeat 结果

ios - Touches 在 TableView 上结束

cocoa-touch - 如何 : hide keyboard when UITextView is out of view?

ios - 无法将表达式的类型 'StaticString' 转换为类型 'StringLiteralConvertible' (Swift)

ios - 如何使用 PDFKit 突出显示 pdf 中选定的文本?

javascript - 使用 "Tinder"+ "Firebase"构建 "Geofire"应用程序,这可能吗?

ios - 在表格 View 单元格上无法访问detailTextLabel和imageView

xcode - 如何让 NSViewController 与 Swift 中的 NSToolbar 通信?

swift - 如何从 sks 文件加载节点,然后应用场景编辑器中定义的 Action

android - Android 中 Firebase 注册用户总数