在 Firestore 中存储 Indetifiable 结构数组

Store Indetifiable struct array in Firestore

我有这个代码:

    struct Restaurants: Identifiable {
    let name: String
    let imageUrl: URL
    let id: String
    let rating: Double
    let url: String
    let category: String
    
    static var viewModels: [Restaurants] = [
        Restaurants(name: "Silverio's Mexican Kitchen", imageUrl: URL(string: "https://mainsite-prod-cdn.azureedge.net/partner-images/432257/micrositeimage_p1.jpg")!, id: "hjkhjhjh", rating: 2, url: "https://google.com"),//, category: "Mexican"),
        Restaurants(name: "Taqueria La Esquinita", imageUrl: URL(string: "https://s3-media0.fl.yelpcdn.com/bphoto/x-KCQ7osmvBWLA9WpPdO_Q/o.jpg")!, id: "hjdha", rating: 3, url: "https://google.com")//, category: "Mexican")
    ] {
        didSet {
            print("data set")
        }
    }
}

如何在 Firestore 中存储 viewModels?我想维护这个对象结构,以便我可以跨多个设备携带它。

这个应用程序的想法是帮助团体找到吃饭的地方。因此,我有这样的结构:

感谢@FaridShumbar,我现在正在为每家餐厅使用子系列。如何从子集合中获取文档?

您需要 get() 方法才能检索文档。

根据文档中的示例,您可以按如下方式检索文档:

db.collection("parties").getDocuments() { (querySnapshot, err) in
    if let err = err {
        print("Error getting documents: \(err)")
    } else {
        for document in querySnapshot!.documents {
            print("\(document.documentID) => \(document.data())")
        }
    }
}

此示例检索集合中的所有文档。

我是通过将每个元素分别保存在结构中,然后在获取文档时将其放回原处来实现的。

保存代码:

db.collection("parties").document(Utilities.code).collection("Restaurants").document(card.name).setData([
                                                "name" : card.name,
                                                "img" : imgUrl,
                                                "id" : card.id,
                                                "rating" : card.rating,
                                                "url" : card.url,
                                                "yes" : FieldValue.arrayUnion([Utilities.name])
                                            ], merge: true) { error in
                                                if error != nil {
                                                    print("error adding restaurant: \(error!)")
                                                }
                                            }

检索代码:

class restaurantsFirebase: ObservableObject {
    @Published var restaurants: [RestaurantListViewModel] = []
    
    private let db = Firestore.firestore()
    private var devices = Array<String>()
    
    func fetchData() {
        db.collection("parties").document(Utilities.code).addSnapshotListener { doc, error in
            if error == nil {
                if doc != nil && doc!.exists {
                    if let getDevices = doc!.get("devices") as? Array<String> {
                        self.devices = getDevices
                    }
                }
            }
        }
        db.collection("parties").document(Utilities.code).collection("Restaurants").addSnapshotListener { (querySnapshot, error) in
            guard let documents = querySnapshot?.documents else {
                print("no documents")
                return
            }
            self.restaurants = documents.compactMap({ (queryDocumentSnapshot) in
                print(queryDocumentSnapshot.data())
                let data = queryDocumentSnapshot.data()
                
                let name = data["name"] as? String ?? ""
                let img = data["img"] as? String ?? ""
                let id = data["id"] as? String ?? ""
                let rating = data["rating"] as? Double ?? 0
                let url = data["url"] as? String ?? ""
                let yes = data["yes"] as? Array<String> ?? []
                let compiled = RestaurantListViewModel(name: name, imageUrl: URL(string: img)!, id: id, rating: rating, url: url)
                print("restaurant = \(compiled), restaurants = \(self.restaurants)")
                print("yes = \(yes), devices = \(self.devices)")
                if yes == self.devices {
//                    self.restaurants.append(compiled)
                    return compiled
                }else {
                    return nil
                }
            })
        }
    }
}

使用:

@ObservedObject private var viewModels = restaurantsFirebase()
        db.collection("parties").document(Utilities.code).addSnapshotListener { doc, error in
            if error == nil {
                
                if doc != nil && doc!.exists {
                    if let dev = doc!.get("devices") as? Array<String> {
                        print("devices = \(dev)")
                        devices = dev
                    }
                    if let done = doc!.get("devicesDone") as? Array<String> {
                        print("devicesDone = \(done), devices = \(devices)")
                        if done == devices {
                            self.viewModels.fetchData()
                            showFinal = true
                            results = false
                        }
                    }
                }
            }