繁体   English   中英

在 ChildByAutoId 下从 Firebase 检索数据并添加到数组 - Xcode - Swift

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

这是我来自 Firebase 的数据库:

在此处输入图片说明

我试图在“Tgb9MyxTfdTRd9tQhInsjNRXoPL2”下获取所有购买和数量的数据并添加到数组中。

这是我的代码:

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

这是print("dict-->", dict)的打印输出:

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

这是print("purchase-->", purchase)的打印输出:

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

值 dict 包含我需要的数据,但我无法通过它将数据放入数组中以显示它?

如何将采购和数量数据放入他们自己的数组中?

请帮忙!

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

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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