简体   繁体   中英

How to get chronologically latest post from Firebase?

I am working on app in which Facebook like news feed is used,and i am using Firebase as a database. Everything is working fine, I just need to fetch posts, time wise.

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

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

The data in postsDictionary is same as in Database,But i want that data (post) to get sorted respect to time,So how to use query?

structure of my post in database as follow

在此处输入图片说明 Thanks

To filter the nodes on a child property, call queryOrderedByChild .

Then when you execute the query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

So you'll need to loop over the children:

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);

    }
}];

Loosely based on my answer here: IOS Firebase: Loop all key in snapshot.value get messy position

Usually people append the array they are feeding into the collectionView or tableView (for example) but in your case you can [myMutableArray insertObject:myObject atIndex:0]; now when you enumerate through your snapshot each post will be added to the front of your array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM