在Firebase中检索Childs子项 - 展开独特的后ID

时间:2016-08-09 15:25:42

标签: swift firebase firebase-realtime-database

我试图基本上从孩子们的孩子中解开数据。我当前的数据库结构如下所示:

- 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>
 ...

因此可以看出,我想要检索的实际数据始终是<unique-post-id>的子项,这是在将数据写入数据库时​​自动生成的。从数据库中检索我到目前为止只得到:

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

有没有办法打开那些并展示他们的孩子?现在为我工作的是显示所有独特的帖子ID,但是我无法弄清楚如何让孩子在他们下面,以及所有这些孩子。

我用来检索数据的代码:

  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
                    }

1 个答案:

答案 0 :(得分:1)

 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]`

                }

但另一种方法可能是这样的: -

  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

            }
        }
})