将Firebase文档获取为数组

时间:2018-09-13 18:07:49

标签: swift firebase nsarray google-cloud-firestore

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

1 个答案:

答案 0 :(得分: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)