【问题标题】:Get Firebase Documents as Array以数组形式获取 Firebase 文档
【发布时间】:2018-09-13 18:07:48
【问题描述】:

我在 Firestore 中创建了一个包含数组的文档。

我现在想在我的应用程序中本地存储该数组

我已经手动创建了一个数组,但是如何使用我的 Firestore 文档中的数据填充它?

//Manually created Array
var devices = [ "Laptop",
                "Tablet",
                "Smartphone",
                "Smartwatch",
                "Games Console"]

override func viewDidLoad() {
    super.viewDidLoad()
    createDevicePicker()
    createToolbar()
    getPickerData()
}

//Function to pull data from Firestore
func getPickerData() {
    let docRef = firebaseDB.collection("devices").document("types")
    docRef.getDocument { (document, error) in
        if let document = document, document.exists {
            //This will print out the data
            var test = document.data()
            print(test)
        } else {
            print("Document does not exist")
        }
    }
}

This is what my Firestore DB looks like

【问题讨论】:

  • 那么你有一个包含数组内容的文档吗?请编辑您的问题以准确显示您的文档包含的内容。
  • @DougStevenson 用图片更新问题

标签: swift firebase nsarray google-cloud-firestore


【解决方案1】:

document.data()[String: Any] 的形式出现。

只要它是 Firestore 中的 字符串数组

let array = document.data()["devices"] as! [String]
print(array) 

问题更新

如何追加到已经创建的设备数组。

 var devices = [ "Laptop",
                 "Tablet",
                 "Smartphone",
                 "Smartwatch",
                 "Games Console"]

 let array = data["sub_category"] as! [String]
 devices += array
 print(devices)

【讨论】:

  • 我怎样才能将该数组中的值分配给我在代码中创建的名为“设备”的数组
  • 我为你更新了我的答案。它应该像devices += array 一样简单
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-06-24
  • 1970-01-01
  • 2021-05-31
  • 2018-05-19
  • 1970-01-01
  • 2021-05-06
  • 2015-02-13
相关资源
最近更新 更多