Felix F. Felix F. - 3 months ago 19
Swift Question

Retrieve a Childs Child in Firebase - Unwrap unique-post-ids

I am trying to unwrap data in childs from childs basically. My current database structure looks like this:

- user-posts
- <user-id>
- user-data
- <unique-post-id> (As a result from childByAutoId)
- the data I want to display
- <unique-post-id> (As a result from childByAutoId)
- the data I want to display
...
-<user-id>
-...
-<user-id>
...


So as it can be seen, the actual data I want to retrieve is always a child of
<unique-post-id>
, which is automatically generated when the data is written to the database. Retrieving from the database I so far only get:

- <unique-post-id>
- <unique-post-id>
- ...


Is there a way of unwrapping those and display their childs? What is working for me now is displaying all the unique post id's, but I can't figure out how to get then the child below them, and that for all of them.

The code I'm using to retrieve the data:

func getQuery() -> FIRDatabaseQuery {
let myTopPostsQuery = (ref.child("user-posts")).child(getUid()).child("user-data")
return myTopPostsQuery
}

dataSource = FirebaseTableViewDataSource.init(query: getQuery(),cellReuseIdentifier: "Cellident", view: self.tableView)



dataSource?.populateCellWithBlock { (cell: UITableViewCell, obj: NSObject) -> Void in
let snap = obj as! FIRDataSnapshot

cell.textLabel?.text = snap.key as String
}

Answer
 dataSource?.populateCellWithBlock { (cell: UITableViewCell, obj: NSObject) -> Void in
                    let snap = obj as! FIRDataSnapshot

                    cell.textLabel?.text = snap.key as! String
                    let childString = snap.value as! String
                    // If the child is another dictionary  use `as! [String : AnyObject]`

                }

But a different approach might go like this : -

  ref.child("user-posts")).child(getUid()).child("user-data").observeEventType(.Value, withBlock: { (snap) in

      if snap.exists(){

         for each in snap as! [String : AnyObject] {

              let childString = snap.Value as! String

            }
        }
})
Comments