简体   繁体   中英

Retrieving Data from Firebase under ChildByAutoId and adding to array - Xcode - Swift

Here is my Database from Firebase:

在此处输入图片说明

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!

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM