askaale
askaale

Reputation: 1199

Swift/Firebase - Sort posts in tableview by date

Basically I am trying to make a twitter-like app, showing status updates of the people you follow, ordered by date, just like twitter. How can I do that? I have the code for displaying the posts in a table view, but the ordering is all messed up and looks quite random. I have a path called posts, with an autoID path, containing message, date and sender. How is this possible, without just showing the date in order from new > old, but also show the message and sender as well?

Thanks in advance.

root
  posts
    autoID
      sender
      message
      timestamp
 users
    UID
     username

Upvotes: 1

Views: 5525

Answers (3)

Boomerange
Boomerange

Reputation: 665

For Swift 3:

Change . queryOrderedByChild('timestamp') for .queryOrdered(byChild: "timestamp")

Upvotes: 0

Jay
Jay

Reputation: 35659

The question is little bit unclear but if you want to populate a tableView you will need to get the data from Firebase, populate an array (the dataSource), and reload the tableView.

First off we need to set up an .ChildAdded observer to load the data into the messagesArray, which is used as the tableView datasource

class AppDelegate: NSObject, NSApplicationDelegate {

   var messagesArray = [[String:String]]() //an array of dicts, tableView datasource
   var initialLoad = true

and the code to load the data initially and then watch for added messages

messagesRef.observeEventType(.ChildAdded, withBlock: { snapshot in

  let dict = [String: String]()
  dict["date"] = snapshot.value("date")
  dict["msg"] = snapshot.value("message")
  dict["sender"] = snapshot.value("sender")

  self.messagesArray.append(dict)

  if ( self.initialLoad == false ) { //upon first load, don't reload the tableView until all children are loaded
    self.itemsTableView.reloadData()
  }
})

then - and this is the cool part...

    //this .Value event will fire AFTER the child added events to reload the tableView
    //  the first time and to set subsequent childAdded events to load after each child
   //   is added in the future
    messagesRef.observeSingleEventOfType(.Value, withBlock: { snapshot in

        print("inital data loaded so reload tableView!  \(snapshot.childrenCount)")
        self.messagesTableView.reloadData()
        self.initialLoad = false
    })

With the above code, the order of the data is by their key - and if those keys were generated by Firebase, they will be sequential in the order the messages were created.

Your tableView is then populated from the messagesArray, and you can pick off the date, message and sender to put into the tableView columns or however you want the populate your cellView.

Your other requirement was to have them ordered by Date, descending. That's a super great question and had has answer here - it was a two part question but you'll see the thought process.

In Firebase, how can I query the most recent 10 child nodes?

you will also want to leverage Firebases query capabilities to get the specific data you want instead of the general data from above...

messagesRef.queryOrderedByChild("date").observeEventType(.ChildAdded, withBlock: {
  snapshot in
    //create a dict from the snapshot and add to tableview
})

Upvotes: 3

Scriptable
Scriptable

Reputation: 19760

You are currently getting all posts from Firebase, which would likely be ordered by the order they were added in, you can specify the order you want the results in like so,

firebase.queryOrderedByChild("posts/publishedDate").observeEventType(FEventType.Value, withBlock: { (snapshot:FDataSnapshot!) in
   self.firebaseUpdate(snapshot)
})

I converted that directly when writing from the objective-c example firebase provide, So it may need some tweaks.

You could also sort the results locally once you receive them, but you would likely need listOfMessages to be an array of dictionaries, classes or structs that contain the sort field, then you can use a predicate or filter to sort the array.

Sorting an array using filter

Firebase Retreiving data

Upvotes: 0

Related Questions