0

Im uploading my data like this:

enter image description here

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?

enter image description here

16
  • You need all purchases or do you want to filter it with some value? Commented Jan 29, 2020 at 4:00
  • Because Database.database().reference().child("purchases").child(uid) this will return you only one value. And if you can more purchases in the screenshot that will be helpful. Commented Jan 29, 2020 at 4:01
  • I can only store one value of purchases, but I want to store more. If I use ChildAutoId, then I can store them all. However I can retrieve them all? Commented Jan 29, 2020 at 4:14
  • If you want to get all values use "Database.database().reference().child("purchases")" with single value observer Commented Jan 29, 2020 at 4:18
  • Adding "child(uid)" will give you a matching result only Commented Jan 29, 2020 at 4:21

1 Answer 1

1

Prepare an array from multiple records, sample code:

var myPurchases: [Purchase] = []
for (key, value) in userDictionary {
    guard let dic = value as? [String: Any] else {
         continue
    }

    let purchaseModel = Purchase(uid: key, dictionary: dic)
    myPurchases.append(purchaseModel)
}
Sign up to request clarification or add additional context in comments.

3 Comments

cant recognise json.dictionaryObject
Do I put this in the func fetchPurchaseForCurrentUser()? I dont have userDictionary in the view controller Im trying to get the data to
You will get userDictionary in fetchPurchaseForCurrentUser via let userDictionary = purchases[uid] and then you can use the above code to add values to your purchase model.

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.