Assuming you are using SwiftUI, you can follow these steps:
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
}
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))
}
}
}
}
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)
}
}
}
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.
Asked: 2022-12-22 11:00:00 +0000
Seen: 8 times
Last updated: Nov 14 '21