Firestore - Append to tableView when view is loade

2019-09-01 03:46发布

问题:

Can someone please show me how I can append data from Firestore into an array? What I would like to do is make it so that when the view appears the data is appended into the below array and then into the correct labels of the tableView. When I call print("(document.data())") the data shows the way it should do in the bottom panel, I just don't know how to make it so that it appends into my array. Any help would be greatly appreciated, Many thanks!!

Firestore

Xcode bottom panel

struct DetailsAdded {
    var titleName: String
    var detailsName: String

}

var array = [DetailsAdded]()

override func viewDidLoad() {
    super.viewDidLoad()

    db = Firestore.firestore()
    loadData()

    }

func loadData() {
    db.collection("Users").getDocuments() { (querySnapshot, err) in
        if let err = err {
            print("Error getting documents: \(err)")
        } else {
            for document in querySnapshot!.documents {
                print("\(document.data())")
            }
        }
    }

}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "CreateWorkoutCell", for: indexPath) as! CreateWorkoutTableViewCell

    cell.titleLabel.text = array[indexPath.row].titleName
    cell.detailsLabel.text = array[indexPath.row].detailsName

    return cell
}

回答1:

    if let snapshot = querySnapshot {

        for document in snapshot.documents {

            let data = document.data()
            let name = data["name"] as? String ?? ""
            let details = data["details"] as? String ?? ""
            let newDetails = DetailsAdded(titleName: name, detailsName: details)
            array.append(newDetails)
        }

        self.tableView.reloadData()
    }