如何查询Firebase数据childByAutoID?

时间:2019-06-03 16:01:58

标签: swift firebase firebase-realtime-database

可以只查询一次该路径,并按locality值对商品进行排序(例如伦敦),但仅获取在某处开始/结束的商品childByAutoID

原因-当我在tableView中向下滚动时,我想从数据库中获取按某个区域排序的更多旧商品,例如伦敦,并且旧于oldestKey,这是媒体项目。

最初使用.childAdded方法下载第一批项目。

数据:

 media
   -LgSsaqYzevONPTk2447 // <- childByAutoID
       caption: "12"
       locality: "City of London"
       mediaUID: "-LgSsaqYzevONPTk2447"

  -LgSsZnpSNLJwZBNgXGJ
       caption: "15"
       locality: "New York"
       mediaUID: "-LgSsZnpSNLJwZBNgXGJ"

代码

   class func observeNewMediaSingleTime(_ oldestKey: String,_ 
  userLocality: String, _ completion: @escaping ([Media], String?) -> Void) {


   let ref = Database.database().reference()
     let query = ref.child("media").queryOrdered(byChild: userLocality).queryStarting(atValue: oldestKey).queryLimited(toLast: 50)


 ref.observeSingleEvent(of: .value, with: { snapshot in

    guard snapshot.exists() else {
        completion([],nil)
        return}

     let firstItem = snapshot.children.allObjects.first as! DataSnapshot

      var arrayOfMedia = [Media]()

     var count = 0
     let enumerator = snapshot.children
     while let mediaItem = enumerator.nextObject() as? DataSnapshot {
        let media = Media(dictionary: mediaItem.value as! [String:Any])

        print("media.locality is \(media.locality)")
        //check if new media has same key as oldest post downloaded in previously
        if media.mediaUID != oldestKey{
            count += 1
            arrayOfMedia.append(media)
        }
    }//end of while
    arrayOfMedia.reverse()

    if count == arrayOfMedia.count {
        let updatedOldestKey = firstItem.key
        completion(arrayOfMedia, updatedOldestKey)
    }

})
}

1 个答案:

答案 0 :(得分:2)

如果您知道第一项的locality值,则可以使用queryStarting(atValue:childKey:)

let query = ref.child("media")
  .queryOrdered(byChild: "locality")
  .queryStarting(atValue: "City of London", childKey: "-LgSsaqYzevONPTk2447")
  .queryLimited(toLast: 50)

因此,以上方法按其位置对所有子节点进行排序,然后开始使用locality = "City of London"和键-LgSsaqYzevONPTk2447从处返回结果。