首页 > 解决方案 > Swift / Firestore - 如何获取包含嵌套地图对象的单个文档并将它们发送到结构?

问题描述

我正在尝试将我的数据从单个文档中获取到 Tableview 的 Struct 中。出于某种原因,从 Firestore 获取单个文档时。它以键值对的形式返回。我以为它会是一本字典。与从集合中获取所有文档时相同。我在地图(照片)中有几个嵌套的地图(照片)。如何获取嵌套地图并将单个项目添加到我的结构中?

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!)
    }
}

标签: swiftdictionarygoogle-cloud-firestore

解决方案


我能够以这种方式获取嵌入的地图项。我使用 [[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!)
    }
}

推荐阅读