Reputation: 1
I am making an app that has posts and comments on said posts. However, whenever a user posts/comments they are not shown in the order they were posted after loaded in a UITableView. I have implemented a timestamp into the posts and comments, but I can't figure out how to sort them.
My Database:
"posts" : {
"47CCC57D-9056-4F5B-919E-F686065574A2" : {
"comments" : {
"99838A46-A84E-47E9-9D9C-E048543DC7C9" : {
"comment" : "Would you trade for a red one?",
"timestamp" : 1488315280579,
"commentID" : "99838A46-A84E-47E9-9D9C-E048543DC7C9",
"username" : "user"
}
},
"description" : "Don't really need this anymore. Willing to go for less if I can get a trade",
"image" : "JLMzSuhJmZ.jpeg",
"postID" : "47CCC57D-9056-4F5B-919E-F686065574A2",
"price" : "$5",
"rating" : "8",
"title" : "title",
"uid" : "5U1TnNtkhegmcsrRt88Bs6AO4Gh2",
"username" : "user"
},
How I am atttempting to sort comments in CommentViewController
:
var postDetails: String?
var posts = NSMutableArray()
func loadData() {
FIRDatabase.database().reference().child("posts").child(postDetails!)
.child("comments").queryOrdered(byChild: "timestamp")
.observeSingleEvent(of: .value, with: { snapshot in
if let postsDictionary = snapshot.value as? [String: AnyObject] {
for post in postsDictionary {
self.posts.add(post.value)
}
self.tableView.reloadData()
}
})
}
// Displays posts in postsDetailsTableView
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "commentCell", for: indexPath) as! CommentTableViewCell
// Configure the cell...
let post = self.posts[indexPath.row] as! [String: AnyObject]
cell.selectionStyle = .none
cell.commentLabel.text = post["comment"] as? String
cell.usernameLabel.text = post["username"] as? String
return cell
}
}
What can I do so that each comment is in the order it was posted?
Upvotes: 0
Views: 2049
Reputation: 35658
The problem: In your code, you are returning the snapshot but then converting it to a dictionary which looses the ordering.
When querying by .value, the keys, values and information about the ordering are contained in the snapshot but the ordering is lost once the snapshot is converted to a dictionary so you need to iterate over the children to get the correct order.
func loadData() {
FIRDatabase.database().reference().child("posts").child(postDetails!)
.child("comments").queryOrdered(byChild: "timestamp")
.observe(.value, with: { snapshot in
for child in snapshot.children {
print("child \(child)")
}
})
}
Upvotes: 1