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

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

    }


 }];

}

最佳答案

您的代码失败是因为您通过用户 uid 获得了实际上并不存在的 child 。 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"];

关于ios - 如何将 Firebase 数据存储在数组中并打印出来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37652564/

相关文章:

c# - 如何检查 Unity 中的 firebase 数据库中是否已存在键/值

android - 带有 spark 包的 Firebase 分析

java - Swift AES 实现

ios - iOS 8 和 iOS 9 中相同代码的不同行为的可能原因

java - Android 的 Firestore 超时

iOS Firebase Crashlytics : Out Of Memory (OOM) Reporting

ios - 从 Firebase 获取数据为零

ios - 对成员 'downloadTask(with:completionHandler:)' 的模糊引用

ios - 带有 Indy 或第三方 Internet 组件的 iOS 上的 Delphi XE2

ios - 在 Swift 中将 Any 类型的数据转换为字符串数组