Home > Net >  Swift 5 Firebase queryOrderedBy String value
Swift 5 Firebase queryOrderedBy String value

Time:12-06

is it possible to query after the child value if its a string? In alphabetically order? Doesnt matter whether it is descending or ascending. e.g. under the key, each reference has the assigned name of the follower, and I want to order all the followers alphabetically. Only manage to query it ordered by an integer unfortunately. (INCLUDING PAGINATION)

If this doesnt work, is there a way to query ordered by key? e.g. I have key 1 "-edasMmaed" and key 2 "-deLkdnw" etc and that if do paginate I start after the last value? I haven't found anything useful unfortunately.

Kind regards

Edit: This is for the first part of the question

enter image description here

enter image description here

EDIT 2:

        var query = Ref().databaseFollowingForUser(uid: userId, type: type).queryOrderedByKey()
    
    if let latestUserFollowers = uid, latestUserFollowers != 0 {
        query = query.queryEnding(atValue: latestUserFollowers).queryLimited(toLast: limit)
    } else {
        query = query.queryLimited(toLast: limit)
    }

    query.observeSingleEvent(of: .value, with: { (snapshot) in

With this code I receive the first 10 results (limit is defined as 10) everbody from ID: 276 through ID: 18. (starting at holgerhagerson and ending at manni85)

Now I want to paginate and load more which I am not able yet.

The passed uid is the uid of the latest fetched user which is "18", manni85

BIG EDIT: I managed to order it by keys. Reading your answers regarding keys are always saved as strings, I realized my mistake and are now able to do it properly.

Big thank you!

CodePudding user response:

Keys in the Firebase Realtime Database are stored (and sorted) as strings. Even if they look like numbers to you, Firebase will store (and sort) them as strings.

This means that the 2, 3, 4, etc in your screenshot are actually "2", "3", "4" etc. This affects how they are ordered, as strings are ordered lexicographically and in that order these keys will show up as "3", "30", "4", "44", "5", etc.

If you want to use keys that you can sort numerically, take these steps:

  1. Prefix keys with a short non-numeric prefix, to prevent Firebase interpreting them as an array.
  2. Use a fixed length for the numbers in all keys, prefixing the value with zeroes or spaces as needed.

When combined, your keys would show up as:

"key_003": ...,
"key_004": ...,
...
"key_008": ...,
"key_016": ...,
"key_018": ...,
"key_030": ...,
"key_044": ...

Which you can now reliably sort when you query /FOLLOW/Follower/2 by calling queryOrderedByKey().

  • Related