Search code examples
iosfirebasefirebase-realtime-databaseswiftui

Read data from Realtime Database from Firebase in SwiftUI


Ive been looking all over for documentation on using the Realtime Database with SwiftUI but all I find is information on using Firestore or old information with UIKit. Is there any info on how to just read from a database with a basic example?


Solution

  • In general, in SwiftUI, it's helpful to put networking/asynchronous code like Firebase into an ObservableObject that the View has access to. Then, you can use a trigger like onAppear to run your Firebase functions. Then, when a @Published property on your ObservableObject changes, your view will automatically re-render.

    For example:

    class FirebaseManager : ObservableObject {
      @Published var result : String?
    
      func makeFirebaseCall() {
        //make your Firebase data call here -- plenty of examples exist on how to do this, which is not SwiftUI or UIKit specific. When the Firebase call returns, set the returned value to your @Published property.
           self.result = //the result of my firebase call
        }
      }
    }
    
    struct ContentView : View {
      @StateObject private var firebaseManager = FirebaseManager()
    
      var body : some View {
        VStack {
          Text("Hello, world")
          if let result = firebaseManager.result {
            Text(result)
          }
        }.onAppear {
          firebaseManager.makeFirebaseCall()
        }
      } 
    }