UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Unable to retrieve data from Firebase

Forums > SwiftUI

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!

2      

Hi @Hazel1603 ,

This usually happens when the collection you're listening to doesn't exist. The reason might be as simple as a misspelled collection name. Unfortunately, the link to the screenshopt you posted doesn't work for me - can you share it again?

Also, I noticed you're using the rather verbose code for mapping documents from the first part of the article. There is a follow-up article that shows how to make mapping documents a lot easier by using Codable: https://peterfriese.dev/swiftui-firebase-codable/

Also, if you're using SwiftUI 2, I'd recommend using @StateObject instead of @ObservedObject following Apple's guidelines at State and Data Flow.

Cheers, Peter

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.