【问题标题】:Swift Firebase sort by last 10 and then show 10 new valuesSwift Firebase 按最后 10 个排序,然后显示 10 个新值
【发布时间】:2016-09-09 23:41:34
【问题描述】:

我目前无法通过我的 tableview 显示值,因为我正在创建这个类似 Instagram/Facebook 的提要,其中 tableView 在底部更新(只需通过 firebase 从数据库中获取新值)。但是,我真的很难用非重复数据填充 tableView。我目前正在按子项(时间戳)对我的 firebase ref 进行排序,默认情况下我显示“queryLimitedToLast(10)”。然而,问题来了。我真的找不到显示“新”数据的方法,这些数据没有在上面的表格视图中列出。

我的 ViewController 中有一个“curLength:Int = 10”(显然是变量)。

对于用户每次更新tableView,curLength为+= 10,后跟一个简单更新tableView的函数。不幸的是,我无法真正弄清楚如何从查询中显示不存在的数据,因为我通过“queryLimitedToLast(x)”运行它,在这种情况下,它只是用相同的数据重新填充 tableView 两次,然后10 条新记录。

如果我想显示最新数据,每次更新“10 个新帖子”,我将如何处理?

【问题讨论】:

    标签: swift uitableview firebase firebase-realtime-database


    【解决方案1】:

    您需要将时间戳用作分页光标。如果您请求按时间戳排序的 10 个帖子,请从 tableView 中具有最新时间戳的帖子的值开始查询接下来的 10 个帖子。这样,您只会获取比您拥有的最新帖子更新的帖子。

    // will give you posts before most recent timestamp
    let beforeRef = FIRDatabase.database().referenceWithPath("posts")
        .queryOrderedByChild("timestamp")
        .queryEndingAtValue(mostRecentTimestamp - 1)
        .queryLimitedToLast(10)
    
    // will give you posts after most recent timestamp
    let afterRef = FIRDatabase.database().referenceWithPath("posts")
        .queryOrderedByChild("timestamp")
        .queryStartingAtValue(mostRecentTimestamp + 1)
        .queryLimitedToLast(10)
    
    beforeRef.observeEventType(.ChildAdded, withBlock: { snap in
        print(snap) // prepend the snap to your datasource
    })
    
    afterRef.observeEventType(.ChildAdded, withBlock: { snap in
        print(snap) // append the snap to your datasource
    })
    

    【讨论】:

    • 如何在不先执行observeeventtype的情况下始终获得最新的时间戳?
    • 好吧,您将从数组中的第一个对象中获取最新的时间戳,并从数组中的最后一个对象中获取最旧的时间戳,因为它们是按降序排列的。
    • 我明白了。让它降序只是简单地反转()我从中填充表格视图的数组,对吗?
    • 通过按时间戳排序,firebase 将按升序返回节点,因此最新的节点将位于堆的底部,我假设您希望它们位于顶部。所以基本上,每次你获得下 10 个帖子时,你需要在将它们添加到填充表格视图的主数组之前反转它们
    • 是的,我知道。但是,必须有更简单的方法来做到这一点?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    • 2022-09-23
    • 1970-01-01
    相关资源
    最近更新 更多