Firestore - Append to tableView when view is loaded

£可爱£侵袭症+ 提交于 2019-12-25 01:44:36

问题


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


来源:https://stackoverflow.com/questions/50191787/firestore-append-to-tableview-when-view-is-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!