Firebase request with Swift 3.0

I am trying to get all the entries where createdAt is Today , but returns nothing.

What am I doing wrong here? And how can I query the data the way I'm trying to do?

JSON:

  { "thoughts" : { "-KWGdcdZD8QJSLx6rSy8" : { "createdAt" : "Tomorrow", "thought" : "meno", "user" : "ET9tYfHqThNTsLG4bZGIbuLGauu2" }, "-KWGeGivZl0dH7Ca4kN3" : { "createdAt" : "Today", "thought" : "meno", "user" : "ET9tYfHqThNTsLG4bZGIbuLGauu2" }, "-KWGeIvWHBga0VQazmEH" : { "createdAt" : "Yesterday", "thought" : "meno", "user" : "ET9tYfHqThNTsLG4bZGIbuLGauu2" } } } 

Swift:

  let db = FIRDatabase.database().reference().child("thoughts") let ref = db.queryEqual(toValue: "Today", childKey: "createdAt") ref.observe(.value, with:{ (snapshot: FIRDataSnapshot) in for snap in snapshot.children { print((snap as! FIRDataSnapshot).key) } }) 
+7
source share
3 answers

You need to use queryOrderedByChild to createdAt and not use equalTo Today

 let ref = FIRDatabase.database().reference().child("thoughts").queryOrdered(byChild: "createdAt").queryEqual(toValue : "Today") ref.observe(.value, with:{ (snapshot: FIRDataSnapshot) in for snap in snapshot.children { print((snap as! FIRDataSnapshot).key) } }) 
+12
source

This is my solution for this JSON:

JSON:

 { "users" : { "-KWGdcdZD8QJSLx6rSy8" : { "name" : "dummy1", "visibility" : true }, "-KWGeGivZl0dH7Ca4kN3" : { "name" : "dummy2", "visibility" : false }, "-KWGeIvWHBga0VQazmEH" : { "name" : "dummy3", "visibility" : true } } } 

SWIFT:

// Get only descendants with the attribute "visibility" = true

 Database.database().reference().child("users").queryOrdered(byChild: "visibility").queryEqual(toValue: true).observeSingleEvent(of: .value, with: { (snapshot) in guard let dictionary = snapshot.value as? [String:Any] else {return} dictionary.forEach({ (key , value) in print("Key \(key), value \(value) ") }) }) { (Error) in print("Failed to fetch: ", Error) } 
0
source

My solution in Swift 5, hope this helps.

 let ref = Database.database().reference().child("thought") let refHandle=ref.queryOrdered(byChild:"thoughts").queryEqual(toValue:"Today").observe(.value, with: { (snapshot) in if let snapshot = snapshot.children.allObjects as? [DataSnapshot]{ let snap = snapshot.value as? [String:Any] print(snap) } }) 
0
source

Source: https://habr.com/ru/post/1259577/


All Articles