Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Assuming you are using SwiftUI, you can follow these steps:

  1. Create a model for your data. This model should contain the properties of your child data and conform to Identifiable.

    struct Child: Identifiable {
       let id: String
       let name: String
       let age: Int
    }
    
  2. Create an ObservableObject that will hold your child data.

    class ChildViewModel: ObservableObject {
       @Published var children: [Child] = []
    
       init() {
           // Get the currently logged in user UID
           guard let uid = Auth.auth().currentUser?.uid else { return }
    
           // Set up a database reference to the children node for this user
           let ref = Database.database().reference().child("users").child(uid).child("children")
    
           // Listen for child added events and update the children array
           ref.observe(.childAdded) { snapshot in
               if let data = snapshot.value as? [String: Any] {
                   let id = snapshot.key
                   let name = data["name"] as? String ?? "Unknown"
                   let age = data["age"] as? Int ?? 0
                   self.children.append(Child(id: id, name: name, age: age))
               }
           }
       }
    }
    
  3. In your sub view, create an instance of the ChildViewModel and use a ForEach to display each child in a list.

    struct ChildListView: View {
       @ObservedObject var viewModel = ChildViewModel()
    
       var body: some View {
           List(viewModel.children) { child in
               Text(child.name)
           }
       }
    }
    
  4. Add the ChildListView to your tab view.

    struct MyTabView: View {
       var body: some View {
           TabView {
               ChildListView()
                   .tabItem {
                       Image(systemName: "person.crop.circle")
                       Text("Children")
                   }
           }
       }
    }
    

Make sure you have imported Firebase and FirebaseAuth in your code.