如何将Firebase数据存储在数组中并将其打印出来?

时间:2016-06-06 08:16:51

标签: ios firebase firebase-realtime-database

我一直试图将firebase数据存储到数组中并整天打印出来,但无济于事。我真的很感谢社区的帮助。

下面是当前firebase数据库的外观图像:

enter image description here

以下是从firebase读取数据的函数的代码如下:

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

    }


 }];

}

1 个答案:

答案 0 :(得分:0)

您的代码失败是因为您正在通过实际不存在的用户uid获取子代。 K2xxxxxxxx是每个元素的唯一字符串,与用户ID不对应。试试这个

_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]);
      }
    }

 }];

}

编辑:

要查询特定用户,请将查询更改为

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