将 Firebase 文档作为数组获取
Get Firebase Documents as Array
我在 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
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)
我在 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
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)