Learn Courses My Dashboard

Trying to use Firebase codable to map documents from server to struct

Hi all, I am trying to use retrieve data form airbase and map it to an array of struct’s. I am using the codable method for this based on this tutorial; https://peterfriese.dev/firestore-codable-the-comprehensive-guide/, after my own more boilerplate version failed to give the desired result.

The code I have below is computing fine however it is not coming back the var I am assigning the data to be empty as the view code is blank. As ever, any help greatly appreciated, thanks!

struct ComponentsAdded: Codable,Identifiable {

   @DocumentID var id:String? = UUID().uuidString
    var componentCategory:String = "catagory"
    var componentName:String = "component name"
    var componentCalories:Double = 0
    enum CodingKeys: String, CodingKey {
      case id = "ID"
      case componentCategory = "itemCalories"
      case componentName = "itemCatagory"
      case componentCalories = "itemName"

class DailyTotal: Identifiable, ObservableObject {
    @Published var id:UUID? = UUID()
   @Published var todayTotal:Double = 0
    @Published var todayDate:Date?
    @Published var catagoryTotals = ["Breakfast":0.0, "Full Meals":0.0]
    @Published var componentsAdded:[ComponentsAdded]

    init() {
        self.componentsAdded = [ComponentsAdded()]


    func updateDailyTotalClass (dailyTotal:DailyTotal) {
        let db = Firestore.firestore()
        let date = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "ddMMyyyy"
        let todayDate = dateFormatter.string(from: date)
        let userName = "Aurellio2005" + "-"
        let dailyTotalCollection = db.collection("dailyTotals")
        let dailyTotalDocumentName = String(userName) + todayDate
        var newComponentsAdded:ComponentsAdded = ComponentsAdded()
        var newComponentsAddedList = [ComponentsAdded]()
        dailyTotalCollection.document(String(dailyTotalDocumentName)).getDocument { (documentSnapshot, error) in
            if let error = error {
                print("Daily Total not available; \(error)")
            else {
                let todayDate = documentSnapshot?.get("toadyDate") as? Timestamp ?? Timestamp()
                dailyTotal.todayDate = todayDate.dateValue()
                dailyTotal.todayTotal = documentSnapshot?.get("todayTotal") as? Double ?? 0
                dailyTotal.catagoryTotals = documentSnapshot?.get("catagoryTotals") as? [String:Double] ?? ["Breakfast":0.0, "Full Meals":0.0]
                dailyTotal.id = UUID()
            **dailyTotalCollection.document(String(dailyTotalDocumentName)).collection("itemsAdded").getDocuments { (querySnapshot, error) in**
**                guard let documents = querySnapshot?.documents else {**
**                    print("No Documents")**
**                    return**
**                }**
**                **
**                newComponentsAddedList = documents.compactMap { QueryDocumentSnapshot -> ComponentsAdded? in**
**                    return try? QueryDocumentSnapshot.data(as: ComponentsAdded.self)**
**                }**
**                **
**                dailyTotal.componentsAdded = newComponentsAddedList**
**            }**

import SwiftUI

struct ItemsAddedView: View {
    @EnvironmentObject var model3:DailyTotal
    var body: some View {
        VStack {
            ForEach (model3.componentsAdded) { r in

have you actually tried printing the raw data?

since if it cannot parse it then it should crash and not work at all… but it seems to be doing fine from what you are trying to explain so the only way is to slowly print and debug it and see where it goes wrong

If the variable names between the struct and the external database have to match, you might be running into a problem because category is misspelled several times.

HI Francis, it is just printing an empty array, I’m not sure where to go from there, any ideas?

Thanks Mark, the spelling mistakes are consistent so it should read through fine i.e it’s always ‘catagory’ and ‘toadyDate’ when referring to the server. This is dyslexic coding!

are you sure you have it saved or returned to the dataArray though? maybe you just ran the operations but forgot to save or pass it somewhere

How about setting a breakpoint and then doing some of that “po myVariable” action?