如何从Firebase实时数据库中读取数据

问题描述 投票:-1回答:1

如何从Firebase数据库读取数据?我有带有以下json文件的实时Firebase数据库

{
  "Category" : {
    "Breakfast" : {
      "CategoryImg" : "Breakfast-img",
      "CategoryName" : "Breakfast"
    },
    "Gluten-Free" : {
      "CategoryImg" : "Gluten-free-img",
      "CategoryName" : "Gluten-free"
    },
    "Lunch" : {
      "CategoryImg" : "Lunch-img",
      "CategoryName" : "Lunch"
    },
    "Popular" : {
      "CategoryImg" : "Popular-img",
      "CategoryName" : "Popular"
    },
    "Trending" : {
      "CategoryImg" : "Trending-img",
      "CategoryName" : "Trending"
    },
    "Vegetarian" : {
      "CategoryImg" : "Vegetarian-img",
      "CategoryName" : "Vegetarian"
    }
  }
}

我正在使用此代码来检索详细信息

// 1
let rootRef = Database.database().reference()

// 2
let childRef = Database.database().reference(withPath: "Category")

// 3
let itemsRef = rootRef.child("Category")

// 4
let breakfastRef = itemsRef.child("Breakfast")

// 5
print(rootRef.key)
print(childRef.key)
print(itemsRef.key)
print(breakfastRef.key)

但是我在控制台中得到以下内容。有人可以帮忙吗?

nil
Optional("Category")
Optional("Category")
Optional("Breakfast")

我正在关注本教程,但无法获得相同的结果https://www.raywenderlich.com/3-firebase-tutorial-getting-started

swift firebase firebase-realtime-database
1个回答
0
投票

您正在关注的tutorial,在代码中说出了它的打印内容:

// 5
print(rootRef.key)   // prints: ""
print(childRef.key)  // prints: "grocery-items"
print(itemsRef.key)  // prints: "grocery-items"
print(milkRef.key)   // prints: "milk"

无法(或者至少对我来说不可行)说明结果为何不同。它可能是SDK行为的改变,也可能是Swift行为的改变,但这同样也像该文章在显示输出时将其重点放在它的Firebase方面(而不是Swift方面)上获得了一些自由一样。

但是让我们关注差异,以及如何在应用程序中处理差异。

差异:

  • 第一个print(rootRef.key)为您打印nil,而根据本教程它则打印""

    虽然Swift SDK的Firebase文档没有说出关于根密钥的任何具体信息,但Android SDK的文档说的是有关DataSnapshot.getKey()的内容:

    此快照的源位置的密钥名称,或如果此快照指向数据库根,则为null

    我很快进行了测试,JavaScript和Android SDK的确也打印了DataSnapshot.getKey()

    换句话说:您所看到的行为是预期的:由于您正在打印数据库根的键,因此值为null / nil

  • 您的其他键将打印为null,而本教程仅打印Optional(<value>)

    这也是预期的行为。因为(如第一个打印语句所示)键可以是<value>或值,所以其类型是nil。而且,当您打印可选字符串时,Swift会将其打印为Optional<String>(如第一行)或nil

    如果您只想像本教程中那样打印值,则可以使用Optional(<value>)(如果确定键不是指向根,则使用print(childRef.key!),否则使用print(rootRef.key ?? "nil")

    有关打印可选件的更多信息,请参见How to remove Optional from String Value Swift

© www.soinside.com 2019 - 2024. All rights reserved.