Как вернуть значения источника данных TableView, если я использую Firebase / Firestore для запроса возвращаемого значения? - PullRequest
0 голосов
/ 15 апреля 2020

Я понимаю, что Firestore асинхронный. У меня просто возникают проблемы с возвратом значений для методов cellForRowAt и numberOfRowsInSection. Он не возвращает никаких ячеек / строк, потому что возврат находится за пределами замыкания, но я не могу поместить возвращение внутрь замыкания. Как мне go обойти эту проблему?

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    //Return the count how many workouts exist for each date.
    var counter = 0

    Firestore.firestore().collection("/users/\(self.userIdRef)/Days/\(dayIdArray[section])/Workouts/").getDocuments { (querySnapshot, error) in
        if error == nil && querySnapshot != nil {
            counter = querySnapshot?.count ?? 0
        }
    }
    return counter
}


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

    let cell = tableView.dequeueReusableCell(withIdentifier: self.cellID, for: indexPath)

    Firestore.firestore().collection("/users/\(self.userIdRef)/Days/\(dayIdArray[indexPath.section])/Workouts/").getDocuments { (querySnapshot, err) in

        if let err = err
        {
            print("Error getting documents: \(err)");
        }
        else
        {

            let firstValue = querySnapshot!.documents[indexPath.row]

            let myData = firstValue.data()
            let myDayRef = myData["workout"] as? String ?? ""
            cell.textLabel?.text = "\(myDayRef)"
            cell.textLabel?.textAlignment = .center
            cell.accessoryType = .disclosureIndicator
            cell.layer.backgroundColor = UIColor.clear.cgColor
            cell.textLabel?.textColor = UIColor(red: 0.1333, green: 0.2863, blue: 0.4, alpha: 1.0)
            cell.textLabel?.font = UIFont(name: "HelveticaNeue", size: 20)
        }
    }
    return cell
}

1 Ответ

0 голосов
/ 15 апреля 2020

Вы должны перезагрузить свой tableView после заполнения ячеек, как объяснено здесь . Примерно так:

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

    let cell = tableView.dequeueReusableCell(withIdentifier: self.cellID, for: indexPath)

    Firestore.firestore().collection("/users/\(self.userIdRef)/Days/\(dayIdArray[indexPath.section])/Workouts/").getDocuments { (querySnapshot, err) in

        if let err = err {

            print("Error getting documents: \(err)");

        } else {

            let firstValue = querySnapshot!.documents[indexPath.row]
            let myData = firstValue.data()
            let myDayRef = myData["workout"] as? String ?? ""

            cell.textLabel?.text = "\(myDayRef)"
            cell.textLabel?.textAlignment = .center
            cell.accessoryType = .disclosureIndicator
            cell.layer.backgroundColor = UIColor.clear.cgColor
            cell.textLabel?.textColor = UIColor(red: 0.1333, green: 0.2863, blue: 0.4, alpha: 1.0)
            cell.textLabel?.font = UIFont(name: "HelveticaNeue", size: 20)

            tableView.reloadData()
        }
    }
    return cell
}

Обратите внимание на tableView.reloadData().

...