3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Firebase Realtime Database 並べ替えられた(queryOrdered)結果の受け取りかた

Posted at

Firebase Realtime DatabaseでqueryOrderedメソッドで並べ替えられたデータをDataEventType.valueで取得する。

observeメソッドでDataEventType.childAddedなどのchildイベントをリッスンすると子要素ごとにコールバックが発生してしまう。
DataEventType.valueではすべての子要素を含んだsnapshotでコールバックが発生する。
並べ替えられた子要素にはDataSnapshot.children: NSEnumeratorプロパティでアクセスできる。DataSnapshot.valueの子要素は並べ替えられていない。

example
Database.database().reference()
    .child("users").child(user.uid)
    .queryOrdered(byChild: "created")
    .observe(DataEventType.value) { (snapshot) in

        // 子要素は並べ替えられていない
        print(snapshot.value)

        // 並べ替えられた順に子要素が反復される
        for case let child as DataSnapshot in snapshot.children {
            print(child.value)
        }
}
import Firebase

extension DataSnapshot {
    
    var childSnapshots: LazyMapSequence<NSEnumerator, DataSnapshot> {
        return self.children.lazy.map { $0 as! DataSnapshot}
    }
  
}
3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?