skip to Main Content

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)

2

Answers


  1. 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"])
    }
    
    Login or Signup to reply.
  2. You would do something like this

    func appendRemoteDB(year: String,type: String, label: String){
    if let user = Auth.auth().currentUser?.email{
        db.collection("wine").addDocument(data: [
            "year": year,
            "type": type,
            "label": label,
        ]) { (error) in
            if let error = error {
                print("Something went wrong (error.localizedDescription)")
            } else {
                print("Saved seccessfully!")
                
            }
        }
    }}
    

    When you call the function, you pass the data as parameters.
    To call it in the view, you would do,

            Button {
            appendRemoteDB(year: "2017", type: "pinot-noir", label: "Peller Estates")
        } label: {
            Text("Save to remote DB")
        }
    

    If it helps, I have implemented all Firebase from scratch in a project of mine.

    It is in Domain -> ItranslatorViewModel.swift
    If you do not understand, leave a comment and I will help you.

    https://github.com/Raidansz/itranslator/tree/main

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search