0

I'm using Firebase with Alamofire, AlamofireImage to cache my imageURL data on memory and upload ImageShack.

I stuck creating descending query tried to do and search but I couldn't find possible description for me. Here's my test ref_post on Firebase.

childByAutoId()

-- userUid

-- imageUrl

-- timestamp (I have created using this)

*Using NSDate().formattedISO8601 Is it best way or Can you advice me to handle it basically?

How Can I do descending query in Firbase IOS/Swift. Here's my viewDidLoad:

let query = DataService.ds.REF_POSTS.queryOrderedByChild("timestamp")

    query.observeEventType(.Value, withBlock: { snapshot in

        if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] {
            self.posts = []
            for snap in snapshots {
                if let postDict = snap.value as? Dictionary<String, AnyObject> {

                    print(postDict)

                    let post = Post(imageUrl: postDict["imageUrl"]! as? String, username: DataService.ds.REF_USERS.authData.uid)

                    self.posts.append(post)
                }
            }

            self.tableView.reloadData()
        }
    })
Community
  • 1
  • 1
iamburak
  • 3,508
  • 4
  • 34
  • 65

2 Answers2

5
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:).

Tim Vermeulen
  • 12,352
  • 9
  • 44
  • 63
  • @Tim Should I save the timestamp value in Firebase as Double or String? I was just wondering how firebase will order the data when querying with `ref.queryOrderedByChild("timestamp").observeEventType(.Value, withBlock: { snapshot in`. If timestamp (of type Double) is saved as string in Firebase, how will the snapshot elements be ordered when retrieved, in which order? – bibscy Dec 15 '16 at 14:38
  • @bibscy I believe I stored the timestamp as an integer, but I don't remember the details. You should probably just try it out! – Tim Vermeulen Dec 15 '16 at 16:06
5

Instead of

self.posts.append(post)

use

self.posts.insert(post, at: 0)

This will add the items at the beginning of your list and consequently reverse the ascending order you get from firebase into a descending order.

normad
  • 81
  • 1
  • 3