应用程序不从firebase检索数据

时间:2016-05-16 14:48:24

标签: ios firebase firebase-realtime-database

我似乎无法从我的firebase数据库中检索任何信息。我创建了一个既有作者又有标题的表格。

database screenshot

这是我在ios应用程序中运行的代码,但应用程序只是一直崩溃。

// Get a reference to our posts
Firebase *ref = [[Firebase alloc] initWithUrl: @"**********"];

[ref observeEventType:FEventTypeChildAdded withBlock:^(FDataSnapshot *snapshot) {
    NSLog(@"%@", snapshot.value[@"author"]);
    NSLog(@"%@", snapshot.value[@"title"]);
}];

}

我不知道哪里出错了,对此我的任何帮助都将不胜感激。

谢谢

2 个答案:

答案 0 :(得分:3)

将事件类型更改为

[ref observeEventType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {
     NSLog(@"%@", snapshot.value[@"author"]);
      NSLog(@"%@", snapshot.value[@"title"]);
 }];

答案 1 :(得分:1)

您通常不会在根节点下存储类似的数据 - 它通常是存储在根节点下的子节点,如下所示:

sizzling-inferno-255
  book_node_0
    author: test_author
    title: test title
  book_node_1
    author: another author
    title: another title title


Firebase *ref = [[Firebase alloc] initWithUrl: @"sizzling-inferno-255"];

[ref observeEventType:FEventTypeChildAdded withBlock:^(FDataSnapshot *snapshot) {
    NSLog(@"%@", snapshot.value[@"author"]);
    NSLog(@"%@", snapshot.value[@"title"]);
}];

将迭代每个书籍节点并返回该节点的快照。因此,第一次返回快照时,它将是

  book_node_0
    author: test_author
    title: test title

并且第二次返回快照将是

  book_node_1
    author: another author
    title: another title title

使用childByAutoId生成book_node键。

ChildAdded一次一个地读取每个子节点作为快照。

值读取节点中的所有内容;所有子节点,那些子节点等都可以是大量数据。如果ref节点包含子节点,就像在这个答案中一样,返回所有节点并且需要迭代它们以获取子数据,因此在观察块内......

for child in snapshot.children {
   NSLog(@"%@", child.value[@"author"]);
}

编辑 - 并专门回答OP问题,以下是您在问题中使用Firebase结构的方法:

self.myRootRef = [[Firebase alloc] initWithUrl:@"https://**********"];
[ref observeEventType:FEventTypeChildAdded withBlock:^(FDataSnapshot *snapshot) { 
    NSString *key = snapshot.key;
    NSString *value = snapshot.value;

    if ( [key isEqualToString:@"author"] ) {
        NSLog(@"author = %@", value);
    } else if ([snapshot.key isEqualToString:@"title"] ) {
        NSLog(@"title = %@", value);
    }
}];
相关问题