Search code examples
iosswiftfirebasegoogle-cloud-firestoreswiftui

How to add data in a Firestore Database (SwiftUI)


I'm having trouble in the setup steps for adding a document to my FireStore Database.

For reference, these are what my files currently look like:

FirestoreDemoApp.swift

import SwiftUI
import FirebaseCore
import FirebaseDatabase
import FirebaseFirestore


class AppDelegate: NSObject, UIApplicationDelegate {
  func application(_ application: UIApplication,
                   didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
      
      FirebaseApp.configure()

    return true
  }
}

@main
struct YourApp: App {
  // register app delegate for Firebase setup
  @UIApplicationDelegateAdaptor(AppDelegate.self) var delegate


  var body: some Scene {
    WindowGroup {
      NavigationView {
        ContentView()
      }
    }
  }
}

let db = Firestore.firestore()

ContentView.swift

import SwiftUI

struct ContentView: View {
    var body: some View {
        
        // Error on line below
        db.collection("wine").addDocument(data: ["year": 2017, "type": "pinot-noir", "label": "Peller Estates"])
        
        Text("hi")
    }
}

#Preview {
    ContentView()
}

On line 13 of ContentView.swift (I labeled where), I get the error: Static method 'buildExpression' requires that 'DocumentReference' conform to 'View'

I understand this means that the line doesn't conform to a View and I would need a view, but I don't understand where else I would put this code since I'm following the FireStore documentation which is still using AppDelegate and ViewController format from storyboard (I think), and I'm not quite sure how to adjust for the current SwiftUI ContentView and App.swift format

For context here is the guide I am following: https://firebase.google.com/docs/firestore/manage-data/add-data#swift Along with a codeWithChris video (where the line of code comes from): https://www.youtube.com/watch?v=qA9L3_cK9Z0&t=523s (around timestamp 8:43)


Solution

  • What you are trying to do is to execute a function in a place where the compiler expects a View. SwiftUI is a declarative framework for building user interfaces, which means you describe what the interface should look like and how it should behave. The compiler does not know when to perform your method.
    Every action you want to perform needs to be done in designated areas (e.g. Buttons, the .task Modifier...)

    You can fix your current Code by wrapping the method call into a Button

    Button("Press me") {
        db.collection("wine").addDocument(data: ["year": 2017, "type": "pinot-noir", "label": "Peller Estates"])
    }