Im uploading my data like this:
By using these function:
extension Database {
func createPurchase (purchaseID : String, quantity: String, completion: @escaping (Error?) -> ()){
guard let uid = Auth.auth().currentUser?.uid else { return }
let userPostRef = Database.database().reference().child("purchases").child(uid) //taken off auto ID
let values = ["purchase" : purchaseID, "quantity" : quantity ] as [String: Any]
userPostRef.updateChildValues(values) { (err, ref) in
if let err = err {
print("Failed to save purchase to database", err)
completion(err)
return
}
completion(nil)
}
}
}
.
In Viewcontroller 1:
func callID (){
let itemCount = CartController.shared.items.count
for i in 0...itemCount-1 {
let quantity = CartController.shared.items[i].quantity
let quantity1 = String(quantity)
let item = CartController.shared.items[i].product.id
Database.database().createPurchase(purchaseID: item, quantity: quantity1 ) { (err) in
if err != nil {
print("error uploading purchase to Firebase ")
return
}
}
}
}
callID uses createPurchase to take the sku number of each product and its quantity and uploads to firebase. However, it overrides what was previously uploaded. So when I load more than 1 product. It only leaves the last products sku and quantity. For this example, I started with 3 product, but only 1 (the last one) got uploaded. How can I upload all the data. i.e stop this overide?
Here is how Im retrieving it:
extension Database {
func fetchPurchase(withUID uid: String, completion: @escaping (Purchase) -> ()) {
Database.database().reference().child("purchases").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
guard let userDictionary = snapshot.value as? [String: Any] else { return }
let purchase = Purchase(uid: uid, dictionary: userDictionary)
completion(purchase)
}) { (err) in
print("Failed to fetch purchase from database:", err)
}
}
}
.
In viewcontroller 2:
struct Purchase {
let uid: String
let purchases: String
let quantities: String
init(uid: String, dictionary: [String: Any]) {
self.uid = uid
self.purchases = dictionary["purchase"] as? String ?? ""
self.quantities = dictionary["quantity"] as? String ?? ""
}
}
var myPurchases: [Purchase] = []
private func fetchPurchaseForCurrentUser() {
guard let currentLoggedInUserId = Auth.auth().currentUser?.uid else { return }
Database.database().fetchPurchase(withUID: currentLoggedInUserId, completion: { (purchases) in
self.myPurchases.append(purchases)
print("myPurchases", self.myPurchases)
})
}
This is the printout I get:
myPurchases [myShop.Purchase(uid: "Tgb9MyxTfdTRd9tQhInsjNRXoPL2", purchases: "Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0Lzk4OTUzMDk2OTk=", quantities: "2")]
This only shows the one product, however Im needing to have multiple products.
Please Help!
EDIT:
This is a screenshot of when I use ChildByAutoId(). I get all products (2 in this case). But I am unable to retrieve the information from the snapshot and set to my text fields?

