Iterate trough Struct for upload to Firebase

I have this struct:

struct CartItem {
    var name: String = ""
    var count = Int()
}

 var itemsInCart : [CartItem] = []    

I append to it with a button:

 @IBAction func addButton(_ sender: UIButton){
        
        if let index = itemsInCart.index(where: { $0.name == name })   {
            itemsInCart[index].count += 1
     
        } else {
            itemsInCart.append(CartItem(name: name, count: 1))
        }    
}     

Now, I want to upload this to firebase. When I do this:

@IBAction func orderButton(_ sender: UIButton) {
  
        for items in itemsInCart {

        //Write to firebase
        var dataArray = "\(items.count) \(items.name)"
        let data = ["CreatedOn" : timeStamp, "Order" : dataArray] as [String : Any]
        self.ref?.child(dateAndTime).updateChildValues(data, withCompletionBlock: { (error, ref) in
            if error != nil{
                print(error!)
                return
            }
           
        })
        let userData = ["CreatedOn" : timeStamp, "Order" : data] as [String : Any]
      
            break
        }
    }    

The problem with this is that its only writing the last appended value to Firebase. How can I get it to include the whole Struct?

If the user orders first: 2 bananas and then: 3 apples, firebase should read:
2 bananas
3 apples
Now it just reads 3 apples.

This topic was automatically closed after 166 days. New replies are no longer allowed.