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
HStack{
Text(String(r.componentName))
}
}
}
}
}