How to store Firebase data in an array and print it?

I tried to store the database data in an array and print it all day, but to no avail. I will be very grateful for the help of the community.

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

enter image description here

Below is the code of what the function of reading 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);

    }


 }];

}
+4
source share
1 answer

Your code crashes because you are receiving a child from a user uidwho does not actually exist. K2xxxxxxxx- This is a unique string for each item and does not match the user ID. try it

_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 is %@, data is %@",key,allUsersData[key]);
      }
    }

 }];

}

Edit:

-

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

All Articles