Hello!
I'm having an issue with retrieving data from Firebase. I followed the instructions from another website (https://peterfriese.dev/swiftui-firebase-fetch-data/). My code seems to be largely similar but when I check the console, it prints No documents
, which I can't seem to be able to fix.
My database contains several fields, but to make things simpler, I decided to only retrieve 3 fields (I hope that doesn't affect).
Here is my RecipeViewModel which retrieves the data from my database:
import Foundation
import FirebaseFirestore
class RecipeViewModel: ObservableObject {
@Published var recipes = [Recipe]()
private var db = Firestore.firestore()
func fetchData() {
db.collection("Recipes").addSnapshotListener { (querySnapshot, error) in
guard let documents = querySnapshot?.documents else {
print("No documents") // the printing is done here
return
}
self.recipes = documents.map { queryDocumentSnapshot -> Recipe in
let data = queryDocumentSnapshot.data()
let title = data["Title"] as? String ?? ""
print(title)
let author = data["Author"] as? String ?? ""
print(author)
let cookingTime = data["Cooking Time"] as? Int ?? 0
print(cookingTime)
// let prepTime = data["Prep Time"] as? Int ?? 0
// let diff = data["Difficulty"] as? String ?? ""
// let course = data["Course"] as? String ?? ""
// let cuisine = data["Cuisine"] as? String ?? ""
// let servingSize = data["Serving Size"] as? Int ?? 1
return Recipe(id: .init(), title: title, author: author, cookingTime: cookingTime)
// return Recipe(id: .init(), title: title, author: author, cookingTime: cookingTime, prepTime: prepTime, course: course, cuisine: cuisine, difficulty: diff, servingSize: servingSize)
}
}
}
}
Here is my Recipe struct and my RecipeView struct.
struct Recipe: Identifiable {
var id = UUID()
var title: String
var author: String
var cookingTime: Int
// var prepTime: Int
// var course: String
// var cuisine: String
// var difficulty: String
// var servingSize: Int
}
struct RecipeView: View {
@ObservedObject var viewModel = RecipeViewModel()
var body: some View {
NavigationView {
List(viewModel.recipes) { recipe in singleRecipe(recipe: recipe)}
.navigationBarTitle("Recipes")
}
.onAppear() {
self.viewModel.fetchData()
}
}
}
singleRecipe(recipe: recipe) is a basic View which prints the information out. Using a local array, the code works fine so I believe it has something to do with Firebase.
Is there a way to check that I have actually properly connected my app to Firebase (even though I was sure to follow the instructions on Firebase closely)?
For reference, a screenshot of my database on Firebase can be seen here:
https://drive.google.com/file/d/1zJ0UGaTvtY1R37gxCFYoXG2BqQ10WnFo/view?usp=sharing
Thanks!