【问题标题】:loading information from Firebase in a defined order按定义的顺序从 Firebase 加载信息
【发布时间】:2017-12-06 09:25:21
【问题描述】:

我正在向 Firebase 数据库发布一些信息

 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 的底部。我该怎么做才能使新帖子显示在前一个单元格的顶部。

【问题讨论】:

    标签: ios swift firebase firebase-realtime-database firebase-authentication


    【解决方案1】:

    您需要为每个帖子添加时间戳,然后根据时间戳对帖子进行排序。您没有发布您的TableView 是如何构建的,但我建议使用由多个帖子组成的tableArray,这些帖子是自定义类Post,它具有Firebase 中帖子的所有属性。然后您可以通过执行tableArray.sort({$0.date &gt; $1.date}) 来安排帖子,其中日期是Post 中的变量之一,其中包含创建时间戳的字符串。您可能希望在重新加载 TableView 的数据之前对 tableArray 进行排序。

    然后您可以使用

    填充您的 TableView
    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
        ...
    }
    

    由于您在tableArray 中的帖子按时间顺序排列,因此您在TableView 中的帖子也将按时间顺序排列。

    【讨论】:

      【解决方案2】:

      查看此 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()
      

      希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 2018-01-07
        • 2016-08-23
        • 2012-02-12
        • 1970-01-01
        • 2023-03-20
        • 2010-11-12
        • 1970-01-01
        • 1970-01-01
        • 2015-08-31
        相关资源
        最近更新 更多