Firebase分页-Swift 3

用户名

我已经为此战斗了几个小时,似乎无法弄清两件事。

  1. 如何首先显示所有最新帖子(将它们添加到我的“项目”数组中。我将“ queryEndingAtValue”与“ queryLimitedToLast”一起使用,现在我的帖子完全不显示。

  2. 我的工作原理是将这些项目多次添加到我的数组中。

提前致谢。

这是我的分贝 我的数据库的快照样本

这是我的代码,是Firebase的新手,实际上我只是承认我不知道自己在这里做什么。

 func downloadPostsFromFirebase(withValue: String) {
        // 1 - Get a reference to the database
        ref = FIRDatabase.database().reference(withPath: "items-for-sale")

        var startKey = withValue

        var count = GlobalConstants.FirebaseConstants.numerOfPostsPerPage

        var query = ref.queryOrderedByKey()

        if startKey != nil {
            query = query.queryEnding(atValue: startKey)
            count += 1
        }

        query.queryLimited(toLast: UInt(count)).observeSingleEvent(of: .value, with: { snapshot in
            guard var children = snapshot.children.allObjects as? [FIRDataSnapshot] else {
                // Handle error
                return
            }

            if startKey != nil && !children.isEmpty {
                // TODO - If the number of items in the array is equal to the number of items in the db now, then stop?
                for child in snapshot.children {

                    // instance of ItemForSale, it's added to the array that contains the latest version of the data.
                    let itemForSaleSingle = ItemForSale(snapshot: child as! FIRDataSnapshot)

                    startKey = itemForSaleSingle.key

                    self.items.append(itemForSaleSingle)
                    print("Total items count is \(self.items.count)")
                    self.collectionView?.reloadData()

                    print("start key is \(startKey)")
                }
            }
        })
    }
弗兰克·范普菲伦

我的工作原理是将这些项目多次添加到我的数组中。

您正在监听一个value事件。只要查询数据发生更改,就会触发此事件。每当触发时,它就会包含查询的完整数据。

这意味着,如果您从列表中的三个项目开始,则会得到以下三个项目:

1
2
3

然后,如果添加第四项,则将获得带有以下内容的value事件:

1
2
3
4

您会注意到,初始集合与添加值​​后得到的集合之间存在重叠,这就是您看到重复消息的原因。

处理此问题的最简单方法是侦听child_added事件,而不是值事件。在上述情况下,最初将获得三个child_added事件:

1
2
3

然后,在添加项目时,您将获得一个附加的附加信息child_added

4

使用child_added还可以简化代码,因为您不再需要处理集合:

query.queryLimited(toLast: UInt(count)).observeSingleEvent(of: .childAdded, with: { snapshot in
    // instance of ItemForSale, it's added to the array that contains the latest version of the data.
    let itemForSaleSingle = ItemForSale(snapshot: snapshot as! FIRDataSnapshot)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章