如何将Firestore文档ID添加到模型中,然后添加到数组中?

时间:2020-01-26 12:57:43

标签: swift google-cloud-firestore

我有一个结构“ Order”,其中包含一个名为orderId的字段:

protocol OrderSerializable {
    init?(dictionary:[String:Any])
}

struct Order {
    var orderId: String
    var status: Int
    var currentTotal: Double

    var Dictionary:[String : Any] {
        return [
            "orderId": orderId,
            "status": status,
            "currentTotal": currentTotal
        ]
    }
}

extension Order : OrderSerializable {
    init?(dictionary: [String : Any]) {
        guard let orderId = dictionary["orderId"] as? String,
        let status = dictionary["status"] as? Int,
        let currentTotal = dictionary["currentTotal"] as? Double

        else { return nil }

        self.init(orderId: orderId, status: status, currentTotal: currentTotal)
    }
}

我需要将Firestore文档ID添加到模型数组中的orderId字段,即“ ordersArray”。我将如何去做?

到目前为止,这是我的查询代码,我已指出需要的行:

orderRef.getDocuments() {
            querySnapshot, error in
            if let error = error {
                print("\(error.localizedDescription)")
            } else {
                guard let documents = querySnapshot?.documents else { return }
                for document in documents {
                    let orderDictionary = document.data() as [String : Any]
                    let order = Order(dictionary: orderDictionary)
                    // Here I want to append the firestore documentId to order.orderId before appending it to the array
self.ordersArray.append(order!)

                }
                DispatchQueue.main.async {
                    self.ordersTableView?.reloadData()
                }
            }
        }

谢谢。

不同的错误 enter image description here

1 个答案:

答案 0 :(得分:1)

修改扩展名以接受documentId作为附加参数,并将其传递给创建的Order对象。

protocol OrderSerializable {
    init?(dictionary:[String:Any], id: String)
}
extension Order : OrderSerializable {
    init?(dictionary: [String : Any], id: String) {
        guard let status = dictionary["status"] as? Int,
        let currentTotal = dictionary["currentTotal"] as? Double
        else { return nil }

        self.init(orderId: id, status: status, currentTotal: currentTotal)
    }
}

然后,在创建每个订单时,将documentId作为id参数。

orderRef.getDocuments() {
            querySnapshot, error in
            if let error = error {
                print("\(error.localizedDescription)")
            } else {
                guard let documents = querySnapshot?.documents else { return }
                for document in documents {
                    let orderDictionary = document.data() as [String : Any]
                    let order = Order(dictionary: orderDictionary, id: document.documentId)
                    self.ordersArray.append(order!)

                }
                DispatchQueue.main.async {
                    self.ordersTableView?.reloadData()
                }
            }
        }

或者,您可以将orderId直接存储在文档本身中,以便将其与字典一起传递,从而避免了使用documentId的需要。