swift - Swift / Firestore - 如何获取包含嵌套地图对象的单个文档并将它们发送到结构?
问题描述
我正在尝试将我的数据从单个文档中获取到 Tableview 的 Struct 中。出于某种原因,从 Firestore 获取单个文档时。它以键值对的形式返回。我以为它会是一本字典。与从集合中获取所有文档时相同。我在地图(照片)中有几个嵌套的地图(照片)。如何获取嵌套地图并将单个项目添加到我的结构中?
var items: [Item] = []
db.collection("items").document("aAZWjpXwo2V05rMOsQjR")
.getDocument{ (docSnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
for document in docSnapshot!.data()! {
print("\(document)")
if let item = Item(dictionary: document){
self.items.append(item)
}
}
}
}
struct Item {
var photoUrl: String
var item_id: String
init(photoUrl: String, item_id: String) {
self.photoUrl = photoUrl
self.item_id = item_id
}
// I don't know how to use key-value pairs in Swift
// init?(dictionary: (key: String, value: Any)) {
init?(dictionary: [String: Any]) {
for photoInfo in dictionary["photos"] {
let photoData = photoInfo["photo"] as? [String: Any]
let photoUrl = photoData!["photoUrl"] as! String
let item_id = photoData!["item_id"] as! String
}
self.init(photoUrl: photoUrl!, item_id: item_id!)
}
}
解决方案
我能够以这种方式获取嵌入的地图项。我使用 [[String: Any]] 来解决我的问题。我猜嵌入式地图被视为数组内的数组。我还在学习 Swift。我花了一个多星期才弄清楚这一点。祝大家编码愉快...
var items: [Item] = []
db.collection("items").document("aAZWjpXwo2V05rMOsQjR")
.getDocument{ (docSnapshot, err) in
if let err = err {
print("Error getting documents: \(err)")
} else {
if let document = docSnapshot.data(),
let doc = document["photos"] as? [[String: Any]] {
for photoInfo in doc {
if let item = Item(dictionary: photoInfo){
self.items.append(item)
}
}
}
}
struct Item {
var photoUrl: String
var item_id: String
init(photoUrl: String, item_id: String) {
self.photoUrl = photoUrl
self.item_id = item_id
}
// I don't know how to use key-value pairs in Swift
// init?(dictionary: (key: String, value: Any)) {
init?(dictionary: [String: Any]) {
let photoData = dictionary["photo"] as? [String: Any]
let photoUrl = photoData!["photoUrl"] as! String
let item_id = photoData!["item_id"] as! String
self.init(photoUrl: photoUrl!, item_id: item_id!)
}
}
推荐阅读
- javascript - HTML 和纯 javascript 中的搜索框查找所有匹配的锚标记并显示结果
- javascript - 将 Firebase 数据库价值纳入云函数
- matlab - 在 Matlab 中插入不同时间的矩阵
- ansible - 如何在 INI 文件中使用加密变量 (ansible_ssh_pass)?
- reactjs - 如何从步数计算一个人的步伐?
- javascript - Button 创建的上传图片预览代码不会预览图片。Javascript/HTML
- python - 对大型 TIFF 堆栈 ndarray 上的 numpy/scipy 样条进行优化?
- javascript - Javascript - 在一个函数函数执行后一段时间内禁用所有嵌套函数
- xml - 无法加载 WixUIExtension.dll
- jira - Jira - 项目或时间