Search code examples
iosswiftfirebasee-commerceanalytics

Can't log multiple items in Analytics Events E-commerce


I need to log items in carts but I can't figure out how to do that. In Swift it is not allowed to use append() function, so I tried to create a dictionary inside an array but with this method it does not work properly, I got an error in Firebase Debugview. Here is my codes: (Swift, iOS)

func logViewCart(items: [CartItem]){
  
    var itemList : [[String : Any]] = []
    
    for item in items{
        var itemParams : [String : Any] = [
            "item_id": item.id,
            "item_name": item.product?.name,
            "item_category": item.product.category,
            "price": item.price
        ]

        itemList.append(itemParams)
    }
    
    var itemTest : [String : Any] = [:]
    
    for i in itemList {
        itemTest[AnalyticsParameterItems] = [i]
    }

    
    Analytics.logEvent("view_cart", parameters: [
        "items": [itemTest]
    ])
}

Thanks in advance


Solution

  • I found the solution. Instead of declaring a dictionary inside an array, declaring another array variable with [Any] type solve the problem.

    var itemList : [Any] = []
        
        for item in items{
            let variantIndex = item.product?.attributes?[1].listValueLabel?.count ?? 1
            var itemParams : [String : Any] = [
                "item_id": item.itemID,
                "item_name": item.product?.name
            ]
    
            itemList.append(itemParams)
        }
    
        
        Analytics.logEvent("view_cart", parameters: [
            AnalyticsParameterItems: itemList
        ])