首页 > 解决方案 > 以数组形式获取 Firebase 文档

问题描述

我创建了一个文档,其中包含 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")
        }
    }
}

这就是我的 Firestore 数据库的样子

标签: swiftfirebasensarraygoogle-cloud-firestore

解决方案


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)

推荐阅读