NewYorker
NewYorker

Reputation: 67

Swift, Firebase retrieving data from unknown child

I would like to retrieve data from Firebase database child. But I don’t know the child node name.

My database looks like this:

I tried this:

override func viewDidLoad() {
    super.viewDidLoad()

    let userID = Firebase.Auth.auth().currentUser?.uid

    databaseRef = Database.database().reference().child("Users").child(userID!)
    databaseRef.observe(.value, with: { (snapshot) in

        var newItems = [Post]()

        for item in snapshot.children {
            let newPost = Post(snapshot: item as! DataSnapshot)
            newItems.append(newPost)
        }

        self.postArray = newItems
        self.tableView.reloadData()
        print(newItems)

    }) { (error) in
        print(error.localizedDescription)
    }
}

Upvotes: 0

Views: 422

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598718

In your current code you loop over the years already. If you also want to loop over the months, you'll need to add an extra for:

databaseRef = Database.database().reference().child("Users").child(userID!)
databaseRef.observe(.value, with: {(snapshot) in

    for year in snapshot.children.allObjects as [DataSnapshot] {
        for month in year.children.allObjects as [DataSnapshot] {
            print(month.key)
        }
    }


}){
    (error) in
    print(error.localizedDescription)
}

This will print the months. You can get properties of the specific month with:

print(month.childSnapshot(forPath:"Key").value)

Upvotes: 1

Related Questions