Tony Ong Tony Ong - 6 months ago 297
iOS Question

how to store firebase data in array and print them out?

I had been trying to store firebase data into an array and print them out all day long, but to no avail. I will really appreciate help from the community.

Below is an image of how the current firebase database looks like:

enter image description here

Below is the code of how the function to read data from firebase looks like:

- (void)readDataFromServer {

_ref = [[FIRDatabase database] reference];

_hotelRef = [_ref child:@"hotel bookings"];

NSString *userID = [FIRAuth auth].currentUser.uid;

FIRDatabaseQuery *userHotelBookingsQuery = [[_hotelRef child:userID] queryOrderedByChild:@"number"];

[userHotelBookingsQuery observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {

if (snapshot.value == [NSNull null]) {

NSLog(@"No messages");

} else {

[self.arrayOfBookingDetail removeAllObjects];

self.arrayOfBookingDetail = (snapshot.value);

NSString *firstMessage = [self.arrayOfBookingDetail objectAtIndex:0];

NSLog(@"First message is: %@", firstMessage);

}


}];

}


With thanks!

Answer

Your code fails because you are getting the child by the user uid which do not actually exist. The K2xxxxxxxx are a unique string for each element and do not correspond to the user id. Try this

_ref = [[FIRDatabase database] reference];

_hotelRef = [_ref child:@"hotel bookings"];

FIRDatabaseQuery *userHotelBookingsQuery = [_hotelRef queryOrderedByChild:@"number"];

[userHotelBookingsQuery observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {

    if (snapshot.value == [NSNull null]) {
        NSLog(@"No messages");
    } else {
      //[self.arrayOfBookingDetail removeAllObjects];
      //self.arrayOfBookingDetail = (snapshot.children);
      //NSString *firstMessage = [self.arrayOfBookingDetail objectAtIndex:0];
      //NSLog(@"First message is: %@", firstMessage);
      NSDictionary *allUsersData = (NSDictionary*)snapshot.value;
      for (NSString *key in allUsersData.allKeys) {
           NSLog("key = % data = %@",key,allUsersData[key]);
      }
    }

 }];

}

Edit :

To query for a particular user - change your query to

 FIRDatabaseQuery *userHotelBookingsQuery = [[_hotelRef queryOrderedByChild:@"userID"] queryEqualToValue:@"GEmxxxxxxxxx"];