Firebase queryOrderedByChild() method not giving sorted data
Use method observeEventType
instead of observeSingleEventOfType
.
Also, make FIRDataEventType to ChildAdded
.
Last, If you want Top 20 items, use queryLimitedToFirst
instead of queryLimitedToLast
.
{
"users" : {
"alovelace" : {
"name" : "Ada Lovelace",
"score" : 4
},
"eclarke" : {
"name" : "Emily Clarke",
"score" : 5
},
"ghopper" : {
"name" : "Grace Hopper",
"score" : 2
}
}
}
For the dataset above
let queryRef = FIRDatabase.database().reference().child("users").queryOrderedByChild("score").queryLimitedToFirst(20)
queryRef.observeEventType(.ChildAdded, withBlock: { (snapshot) in
print("key: \(snapshot.key), value: \(snapshot.value)")
})
key: ghopper, value: Optional({
name = Grace Hopper;
score = 2;
})key: alovelace, value: Optional({
name = Ada Lovelace;
score = 4;
})key: eclarke, value: Optional({
name = Emily Clarke;
score = 5;
})
Snapshot will returns the contents as native types.
Data types returned:
- NSDictionary
- NSArray
- NSNumber (also includes booleans)
- NSString
So, you can get your scores this way.
let queryRef = FIRDatabase.database().reference().child("users").queryOrderedByChild("score").queryLimitedToFirst(20)
queryRef.observeEventType(.ChildAdded, withBlock: { (snapshot) in
if let scores = snapshot.value as? NSDictionary {
print(scores["score"])
}
})
Optional(2)
Optional(4)
Optional(5)
Moreover, the default of realtime database return everything in ascending order.
If you want descending order, you can make some tricks(4:40) in your database.
Sort Firebase Data with queryOrdered by date
I think what you're missing here is the sort
function, Please try the code below and let me know what are the results:
DataService.ds.REF_INCOMES.queryOrdered(byChild: "date").observe(.value, with: { (snapshot) in
guard let usersSnapshot = snapshot.value as? [String:NSObject] else{
return
}
let users = usersSnapshot["users"] as! [String:AnyObject]
let sorted = users.sorted{($0.0.value["date"] as! Double) > ($0.1.value["date"] as! Double)}
print(sorted) // It should be: New Year Now, New Year, Last Year
})
How to sort and filter data in Firebase?
It gives you null because it does not exists, you need to do something like this:
queryOrdered(byChild: "TimeStampDateAndTime").queryStarting(atValue: 152).queryEnding(atValue: 152\uf8ff)
this will give you all TimeStampDateAndTime
that have 152 at the beginning
Swift - How to create Sort query as Descending on Firebase?
self.posts = self.posts.reverse()
To save NSDate
instances, I personally use timeIntervalSinceReferenceDate()
which returns an NSTimeInterval
(which is a Double
), which you can then save in Firebase. When reading the data, you can obtain the original NSDate
with init(timeIntervalSinceReferenceDate:)
.
orderByChild not working in Firebase
When you call snapshot.val()
, you are getting back a JSON object. The order of keys in a JSON object is determined by your browser and not by Firebase.
To get the children in order use the built-in forEach
method of the snapshot:
self.getAllProfiles = function () {
var qProfile = $q.defer();
var ref = new Firebase(FBURL);
ref.child("users").orderByChild('last_update').on("value", function (snapshot) {
snapshot.forEach(function(child) {
console.log(child.val()) // NOW THE CHILDREN PRINT IN ORDER
});
qProfile.resolve(snapshot.val());
}, function (errorObject) {
qProfile.reject(errorObject);
});
return qProfile.promise;
};
You can leave the q.resolve()
call where it is: snapshot.forEach()
is not an asynchronous call.
Firebase query sort order in swift?
When Firebase loads the data into your tableView data source array, call this:
yourDataArray.sortInPlace({$0.date > $1.date})
Swift 3 Version:
yourDataArray.sort({$0.date > $1.date})
Swift 4 Version:
yourDataArray.sort(by: {$0.date > $1.date})
Request result structure firebasedatabase Swift
In short, if you have extra data at the same level and that makes decodeFirebase
crash, you still can use it:
let value = snapshot.value
let modifiedValue:NSMutableDictionary = (value as AnyObject).mutableCopy() as! MutableDictionary
You then can remove elements by key: modifiedValue.removeObject(forKey: test)
and then apply decode.
How to properly use queryOrderedByValue
When you fire a query against Firebase, it returns the keys of the items that match your query, the value of those items and the relative order of the items in the result. If you listen for a .Value event, all three of these are combined into a single FIRDataSnapshot.
But when you then either ask for the value
property of that snapshot or print that snapshot as one block, the data is converted into a Dictionary. Since a dictionary can only contain keys and values, the ordering of the items is lost at that point. And as it turns out, the dictionary then prints the items ordered by their key.
To get the items in order, you should iterate over them using snapshot.children
:
leaderboardDB.observeSingleEvent(of: .value, with: { (snapshot) in
for child in snapshot.children {
print(child.key)
}
}, withCancel: nil)
Also see:
- Firebase snapshot.key not returning actual key?
- Firebase getting data in order
- Firebase queryOrderedByChild() method not giving sorted data
Related Topics
Check If My iOS Application Is Updated
Get Version Number of iOS Universal Framework in Client
How to Create a PDF File Programmatically in an iOS Application
Open App from Sms with My Url Scheme as a Link
Stroke Width with a Scenekit Line Primitive Type
Why Is Uiwebview Cangoback=No in iOS7
How to Group Array of Objects by Date in Swift
Why Must a Protocol Operator Be Implemented as a Global Function
Best Analytics Offering for Iphone
Application Identifier Entitlement Value Has Changed
Why Is Audio Coming Up Garbled When Using Avassetreader with Audio Queue
Set<Nsobject>' Does Not Have a Member Named 'Anyobject." - Xcode 6.3
The Bundle's Info.Plist Does Not Contain a Cfbundleversion Key or Its Value Is Not a String
Load a .Tmx (Tiled Map) in Sprite Kit