如何从字典中检索Firestore数据并填充Tableview行/节?

问题描述 投票:2回答:1

[我正在尝试使用我已解析并存储在字典中的Firestore数据填充表视图的Sections and Rows,看起来像这样...

dataDict = ["Monday": ["Chest", "Arms"], "Wednsday": ["Legs", "Arms"], "Tuesday": ["Back"]]

坦白说,我什至不确定我是否应该像以前那样将数据存储在字典中。这样做是错误的吗?另外,由于数据是异步提取的,我该如何仅在after字典中填充我的节和行的网络数据?我正在使用完成处理程序,但是当我尝试打印结果时,dataDict会依次打印出三个数组,就像这样...

["Monday": ["Chest", "Arms"]]
["Tuesday": ["Back"], "Monday": ["Chest", "Arms"]]
["Tuesday": ["Back"], "Monday": ["Chest", "Arms"], "Wednsday": ["Legs", "Arms"]]

我希望它在完成后返回数组的单个打印。我在做什么错?

enter image description hereenter image description here

var dataDict : [String:[String]] = [:]


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

    vcBackgroundImg()
    navConAcc()

    picker.delegate = self
    picker.dataSource = self

    tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellID)
    tableView.tableFooterView = UIView()

    Auth.auth().addStateDidChangeListener { (auth, user) in
        self.userIdRef = user!.uid
        self.colRef = Firestore.firestore().collection("/users/\(self.userIdRef)/Days")

        self.loadData { (done) in
            if done {
                print(self.dataDict)
            } else {
                print("Error retrieving data")
            }
        }

    }

}

//MARK: - Load Data
func loadData(completion: @escaping (Bool) -> ()){
        self.colRef.getDocuments { (snapshot, err) in
            if let err = err
            {
                print("Error getting documents: \(err)");
                completion(false)
            }
            else {
                //Appending all Days collection documents with a field of "dow" to daysarray...
                for dayDocument in snapshot!.documents {
                    self.daysArray.append(dayDocument.data()["dow"] as? String ?? "")
                    self.dayIdArray.append(dayDocument.documentID)


                    Firestore.firestore().collection("/users/\(self.userIdRef)/Days/\(dayDocument.documentID)/Workouts/").getDocuments { (snapshot, err) in
                        if let err = err
                        {
                            print("Error getting documents: \(err)");
                            completion(false)
                        }
                        else {
                            //Assigning all Workouts collection documents belonging to selected \(dayDocument.documentID) to dictionary dataDict...
                            for document in snapshot!.documents {

                                if self.dataDict[dayDocument.data()["dow"] as? String ?? ""] == nil {
                                    self.dataDict[dayDocument.data()["dow"] as? String ?? ""] = [document.data()["workout"] as? String ?? ""]
                                } else {
                                    self.dataDict[dayDocument.data()["dow"] as? String ?? ""]?.append(document.data()["workout"] as? String ?? "")
                                }
                                DispatchQueue.main.async {
                                    self.tableView.reloadData()
                                }
                                // print(self.dataDict)
                            }
                            completion(true)
                        }
                    }
                }
                self.dayCount =  snapshot?.count ?? 0
            }
        }
    }
ios firebase asynchronous google-cloud-firestore tableview
1个回答
0
投票

这更像是您要寻找的结构,请注意我的评论:

var tableViewData : [String] //You will need to convert your data to strings at somepoint to put it in the table, so make an array of Strings.
var tableView : UITableView

override func viewDidLoad() {
    super.viewDidLoad()
    tableView = UITableView()
    tableView.delegate = self
    tableView.dataSource = self
    tableView.frame = CGRectMake(0, 50, 320, 200)

    vcBackgroundImg() //not sure what this is
    navConAcc() //not sure what this is

    tableView.tableFooterView = UIView() //not sure if this is neccessary

    Auth.auth().addStateDidChangeListener { (auth, user) in
        self.userIdRef = user!.uid
        self.colRef = Firestore.firestore().collection("users").document(self.userIdRef).collection("Days").document(<day.id goes here>).collection("Workouts").document(<workout.id goes here>) //You need to reference a document from the collection, maybe you need to rethink your database structure. I think maybe you want the `uid` to be the document, and store the data for that `uid` in that document.

        colRef.getDocument { (document, error) in
            if let document = document, document.exists {
                let dataDescription = document.data().map(String.init(describing:)) ?? "nil"
                print("Document data: \(dataDescription)")

                var dict : Dictionary = document.data(); //returns a dictionary: An NSDictionary containing all fields in the document or nil if the document doesn’t exist.

                for (key, value) in dict {
                    //You need to do what you need to do to loop through the dictionary and get the data that you need, if you want to leave it in dictionary form, then when the data gets put into the cells, you need to handle the data then.
                    tableViewData.append(value) //This probably isn't what you want to do, just as an example, if `value` is a string.
                }
            } else {
                print("Document does not exist")
            }
        }
    }
}

然后您在tableViewData中使用:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cellReuseIdentifier = "cell"
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
    let cell:UITableViewCell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdentifier) as UITableViewCell!

    cell.textLabel?.text = tableViewData[indexPath.row]

    return cell
}
© www.soinside.com 2019 - 2024. All rights reserved.