2017-02-28 236 views
0

我正在制作一个应用程序,对所述帖子发表帖子和评论。但是,每当用户发布/评论时,他们都不会按照它们在加载到UITableView后发布的顺序显示。我在帖子和评论中实施了时间戳,但我无法弄清楚如何对它们进行排序。如何按时间顺序对Firebase数据库进行排序?

我的数据库:

"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" 
}, 

如何我atttempting排序在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 
    } 
} 

我能做些什么,使每个评论是在它被张贴的顺序?

回答

0

问题:在您的代码中,您正在返回快照,但随后将其转换为丢失排序的字典。

当通过.value查询时,关键字,值和有关排序的信息包含在快照中,但是一旦快照转换为字典,顺序就会丢失,因此您需要迭代子节点以获取正确的顺序。

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)") 
       } 
    }) 
} 
+0

谢谢周杰伦。我应该用你的例子替换'func loadData'还是应该将代码添加到现有的函数中? – gabe

+0

@gabe无论哪种方式。很明显,您需要删除我的打印语句,这是为了演示正确的顺序,并将其替换为代码以将所需的任何内容追加到数组中。在循环完成后,self.tableView.reloadData()。关键在迭代snapshot.children以维护正确的顺序。 – Jay

相关问题