Данные не отображаются в TableView из Firebase - PullRequest
0 голосов
/ 18 мая 2019

У меня 2 проблемы с отображением данных в таблице из Firebase.

  1. Ничего не отображается в TableView из Firebase
  2. Я не могу добавить ссылку (дочернюю) на переменную

Печать работает. Я получаю доступ к Firebase, но ничего не добавляется в TableView. Пожалуйста, посмотрите на мой код и исправьте, где я неправ.

Это моя модель

class Exercises {

    var titleExercise = ""
    var descriptionExercise = ""

    init (titleExercise: String, descriptionExercise: String) {

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

Это мой ViewController

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

1 Ответ

1 голос
/ 18 мая 2019

Это распространенная ошибка, вы слишком быстро перезагружаете табличное представление и не назначаете / не добавляете результат в массив источника данных.

API observe работает асинхронно, переводите строку вперезагрузите табличное представление в замыкание

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()
        }
    }
}

Примечание:

Ваш класс содержит 3 плохих метода:

  1. Семантически объекты, используемые в типах коллекций, должны иметь именав единственном числе.
  2. Не объявляйте свойства со значениями по умолчанию, если есть инициализатор.
  3. Слишком много избыточной информации в именах переменных

Ив большинстве случаев достаточно структуры и даже констант.Я бы порекомендовал

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

В структуре вы получаете инициализатор бесплатно.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...