如何从Firebase获得按时间顺序排列的最新帖子?

时间:2017-03-07 14:30:47

标签: ios objective-c firebase firebase-realtime-database

我正在开发使用Facebook的新闻Feed,我正在使用Firebase作为数据库。一切都很好,我只需要及时获取帖子。

FIRDatabaseQuery * query = [[[_firebaseReference child:@"Demo"]child:@"posts"]queryLimitedToFirst:100];

[query observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
    if (snapshot.exists) {
        postsDictionary = snapshot.value;
        [self createSocialAppDataSource];
    }
}];

postsDictionary中的数据与数据库中的数据相同,但我希望数据(post)按时间排序,那么如何使用查询?

我在数据库中的帖子结构如下

enter image description here 感谢

2 个答案:

答案 0 :(得分:1)

要过滤子属性上的节点,请调用queryOrderedByChild

然后,当您对Firebase数据库执行查询时,可能会有多个结果。因此快照包含这些结果的列表。即使只有一个结果,快照也会包含一个结果的列表。

所以你需要循环孩子:

FIRDatabaseQuery * query = [[[[_firebaseReference child:@"Demo"] child:@"posts"] queryOrderedByChild: "dateTime"] queryLimitedToFirst:100];

[query observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
    for ( FDataSnapshot *child in snapshot.children) {

        NSLog(@"child.key = %@",child.key);

    }
}];

基于我在这里的回答:IOS Firebase: Loop all key in snapshot.value get messy position

答案 1 :(得分:0)

通常人们会将他们正在加入的数组附加到collectionViewtableView(例如),但在您的情况下,当您通过[myMutableArray insertObject:myObject atIndex:0];枚举时,您可以snapshot每个帖子都会添加到array

的前面