0

Here is my Database from Firebase:

enter image description here

Im trying to get the data for all purchases and quantities under "Tgb9MyxTfdTRd9tQhInsjNRXoPL2" and add to an array.

Here is my code:

    func fetchPurchase(withUID uid: String, completion: @escaping (Purchase) -> ()) {
        Database.database().reference().child("purchases").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in


        guard let dict = snapshot.value as? [String: Any] else { return }
            print("dict-->", dict)
        let purchase = Purchase(uid: uid, dictionary: dict)
            print("purchase-->", purchase)
        completion(purchase)
    }) { (err) in
        print("Failed to fetch purchase from database:", err)
    }
}

This is the print out for print("dict-->", dict):

dict--> ["-LzjaFBgD3ATl7e8uR2-": {
purchase = "Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0Lzk4OTUzMjEyODM=";
quantity = 1;
}, "-LzjaFBiAmrj4m3ZS8m4": {
purchase = "Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0Lzk4OTUzMDk2OTk=";
quantity = 2;
}]

This is the print out for print("purchase-->", purchase):

 purchase--> Purchase(uid: "Tgb9MyxTfdTRd9tQhInsjNRXoPL2", purchases: "", quantities: "")

The value dict holds the data I need, but I cant get past that to put the data into an array to display it?

How can I get the purchase and quantity data into their own arrays?

Please help!

1 Answer 1

1
    func fetchPurchase(withUID uid: String, completion: @escaping (Purchase) -> ()) {
            Database.database().reference().child("purchases").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in

            if snapshot.childrenCount > 0 {
                self.YourArrayList.removeAll()
                 for dict in snapshot.children.allObjects as! [DataSnapshot]
                    let purchase = Purchase(uid: uid, dictionary: dict)
                    self.YourArrayList.append(purchase)
                }

            }
            completion(purchase)
        }) { (err) in
            print("Failed to fetch purchase from database:", err)
        }
    }

}
Sign up to request clarification or add additional context in comments.

2 Comments

where is the i inside the for loop?
Not a big issue but you've cast all of the snapshot child nodes to[DataSnapshot] (which is spot on) but your loop var is called dict which is a little misleading as it looks like the Purchase object is expecting a Dictionary, not a DataSnapshot. Probably should call it childSnap or snap for clarity or cast it to a dict [String: Any]. Other than that, great answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.