Firebase + Swift:仅获取子节点的最新更改

时间:2016-11-08 20:59:27

标签: swift firebase firebase-realtime-database

我有一个locations-orders表,如下所示:

enter image description here

我想只抓取添加到记录中的最新订单(而不是已经包含在其中的所有其他订单)。这就是我所拥有的,这是行不通的(fyi我硬编码了location-orders键):

  static func observeOrders(lId: String, f: @escaping (AppState.Order) -> () ) {
    FIRDatabase.database().reference(withPath: "locations-orders/5P9TF215PZ3ZV")
      .child("orders")
      .queryEnding(atValue: nil)
      .queryLimited(toLast: 1)
      .observe(.childAdded, with: { firebaseSnapshot in

      let orderObject = firebaseSnapshot.value as! [String: AnyObject]

      print("orderObject")
      print(orderObject) // <-------------------- only prints once, never prints again


      let order = AppState.Order(
        title: orderObject["name"] as! String,
        subtitle: orderObject["item_variation_name"] as! String,
        createdAt: Date(timeIntervalSince1970: TimeInterval(orderObject["created_at"] as! Int / 1000)),
        name: "name",
        status: AppState.Order.Status.Pending
      )

      f(order)
    })
  }

我的查询有什么问题??

1 个答案:

答案 0 :(得分:3)

让我们简化一下。如果您想要添加最后一项,然后添加任何新项目,请执行以下操作:

let ref = "your orders path"
ref.queryLimited(toLast: 1)
   .observe(.childAdded, with: { snapshot in
     print(snapshot?.value) 
})