以定义的顺序
问题描述:
我张贴了一些信息,以火力地堡数据库以定义的顺序
let bookObject: Dictionary<String, Any> = [
"uid": uid,
]
FIRDatabase.database().reference().child("posts").child(key).setValue(bookObject)
从火力地堡加载信息,我想中检索中的tableView
func loadData(){
if (FIRAuth.auth()?.currentUser) != nil{
FIRDatabase.database().reference().child("posts").child(self.loggedInUser!.uid).observeSingleEvent(of: .value, with: { (snapshot:FIRDataSnapshot) in
let loggedInUserData = snapshot
if let postsDictionary = snapshot .value as? [String: AnyObject] {
for post in postsDictionary {
self.posts.add(post.value)
}
self.TableView.reloadData()
}})}
}
其中一期工程,不过,帖子中的数据随机加载到TableView,有时一个新的帖子会被发布到TableView的顶部,有时它会被发布到TableView的底部。我该怎么做才能让新帖子显示在前一个单元格的顶部。
答
您需要为每个帖子添加时间戳,然后根据时间戳对帖子进行排序。您没有发布如何构建TableView
,但我建议使用由多个帖子组成的tableArray
,这些帖子是自定义类Post
,该帖子具有Firebase中帖子的所有属性。然后,您可以通过执行tableArray.sort({$0.date > $1.date})
来安排帖子,其中日期是Post
中包含创建时间戳的字符串的变量之一。您可能想要在重新加载TableView
的数据之前对tableArray进行排序。
可以再用
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = //dequeueResuableCell
//retrieve data from the cell's corresponding post
let postCreator = tableArray[indexPath.row].creatorUID
let postContent = tableArray[indexPath.row].content
...
//populate the cell using the above data
...
}
填充您的TableView,并因为在tableArray
自己的帖子按时间顺序,在你TableView
的职位也将在时间顺序排列。
答
查看Firebase文档页面上的“排序数据”部分。 https://firebase.google.com/docs/database/ios/lists-of-data
它基本上允许您按您选择的孩子来排序查询的结果。在您的情况下,您应该根据您在Firebase实时数据库中存储的内容按'日期'或'时间戳'进行排序。
例子:
// My top posts by number of stars
let myTopPostsQuery = (ref.child("user-posts").child(getUid())).queryOrdered(byChild: "starCount")
如果当你订购的孩子你仍然可以看到在你的tableView底部来临的新条目,你可以简单地扭转你的阵列,以确保最新的会在上面。
yourArray.reversed()
希望这会有所帮助。