按子时间戳排序tableviewcell

时间:2019-02-20 19:50:28

标签: swift firebase uitableview firebase-realtime-database

我尝试使用此代码按时间戳对帖子进行排序,这是行不通的,每次启动模拟器时,单元的顺序都不同,我想这不是做到这一点的方法,有人可以解释一下我吗我错了... 我编辑了代码,现在的问题是最新的帖子显示在底部,我希望它们显示在顶部

        self.user.removeAll()
        for child in DataSnapshot.children.allObjects as! [DataSnapshot] {
            print("Processing user \(child.key)")

            let value = child.value as? NSDictionary
            //if country == "UNITED STATES"{
            if let uid = value?["userID"] as? String{
                if uid != Auth.auth().currentUser!.uid {
                    //
                    let userToShow = User()
                    if let fullName = value?["username"] as? String , let imagePath = value?["photoURL"] as? String{
                        userToShow.username = fullName
                        userToShow.imagePath = imagePath
                        userToShow.userID = uid
                        self.user.append(userToShow)
                    }

                }
            }
        }

1 个答案:

答案 0 :(得分:0)

调用DataSnapshot.value时,您会将快照中的数据转换为字典。而且不能保证该字典中键的顺序。

要保持元素从数据库返回时的顺序,您需要遍历DataSnapshot.children。有关如何执行此操作的示例,请参见以下问题:


对于您的代码,它看起来像:

ref.child("users").queryOrdered(byChild: "timestamp").observeSingleEvent(of: .value, with: { snapshot in

    self.user.removeAll()

    for child in snapshot.children.allObjects as [DataSnapshot] {
        print("Processing user \(child.key)")

        let value = child.value as? NSDictionary

        if let uid = value["userID"] as? String {
            ...
        }
    }


    self.tableview.reloadData()
})