【问题标题】:Creating an array out of Firebase Dictionary从 Firebase 字典中创建一个数组
【发布时间】:2017-10-11 18:53:22
【问题描述】:

我正在尝试从 Firebase 检索字典并从字典中提取每个值并将其附加到一个空数组,但我的代码不起作用。我什至没有添加将其附加到数组的代码,当我运行它时,控制台中会打印“错误”。

This is what it looks like inside Firebase

这就是我的代码的样子:

    func convertAllMosaicsToArray() {
    // retrieve and convert here

    Database.database().reference().child("mosiacTitles").observe(.value, with: { (snapshot) in

        if let dictionary = snapshot.value as? [Int : AnyObject] {
            print(dictionary)
        } else {
            print("error")
        }
    })

}

【问题讨论】:

  • firebase 使用 json,它支持数组
  • @rMickeyD 错误:“Firebase 数据库不存储数组。它存储字典/关联数组。” stackoverflow.com/a/40055996/7715250。如果您想将 Firebase 与数组一起使用,则需要使用 FireSTORE
  • firebase.google.com/docs/database/ios/read-and-write @J.Doe 存储在 firebase 中时可能不是数组,但在 swift 客户端可以设置数组
  • @rMickeyD 我不需要通过客户端写入数据,我只需要能够从客户端读取数据。有一种方法可以从 Firebase 控制台中将数据写入 Firebase 数据库,但我不知道如何读取该数据并将其用作客户端的数组
  • @J.Doe 虽然我完全支持 Firestore 的开发人员,但这不一定是一个好案例。正如 rMickeyD 所说,Firebase 客户端在许多情况下将数据显示为数组。

标签: arrays swift firebase firebase-realtime-database


【解决方案1】:
    static func load(_ completion: @escaping () -> ()) {
    if let user = Auth.auth().currentUser {
        let ref = Database.database().reference().child("users").child(user.uid).child("something")
        ref.observe(.value, with: { (snapshot) in

            if let data = snapshot.value as? [String : AnyObject] {

                var arrayNeeded: [Int] = []

                if let array = data["key"] as? [Int] {
                        arrayNeeded = array
                }

            }
            completion()

        })
    }
}

【讨论】:

  • 我试过你的答案,但我无法从快照中访问数据。我还用 Firebase 中的数据库图片更新了我的问题。
  • 明确地说,我的回答是正确的。您需要的数据只比我提供的示例高一级。
【解决方案2】:

问题在于使用 if let 语句将其转换为 [Int : AnyObject],只需将其更改为 [String]

像这样:

    func retrieveMosaicTitles() {
    // retrieve and convert here

    Database.database().reference().child("mosaicTitles").observe(.value, with: { (snapshot) in

        if let allMosaicTitles = snapshot.value as? [String] {
            self.searchResultsVC.listOfMosaics = allMosaicTitles
        } else {
            print("error")
        }
    })
}

【讨论】:

    猜你喜欢
    • 2022-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 2019-06-23
    • 2022-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多