如何使用Swift将自定义对象添加到Firestore中的子集合?

时间:2019-03-25 20:35:32

标签: swift google-cloud-firestore

当我尝试将自定义类修饰符添加到Firestore时,由于无法识别类修饰符而崩溃。如何解决此问题,以便可以在子集合lineItems中映射Modifier对象数组?堆栈溢出要我添加更多文本。除了不知道如何将对象Modifier类上传到Firestore之外,我无话可说。有人可以指出我正确的方向吗?

public func uploadTransactionData(_ menuItems: [MenuItem], tip: Int, tax: Int, rewardAmountApplied: Int, totalPaidFromCredit: Int, discountAmount: Int, subTotal: Int, balanceId: String, locationId: String, completion: @escaping ((String?) -> ())) {
    guard let userId = Auth.auth().currentUser?.uid else { completion(nil); return }
    let utilitiesManager = UtilitiesManager()
    let timestamp = utilitiesManager.timestamp()
    let orderRef = Firestore.firestore().collection("order").document()

    for menuItem in menuItems {
        let lineItemsRef = orderRef.collection("line_items").document()
        let lineItemId = lineItemsRef.documentID
        guard let modifierKeys = menuItem.modifierKeys as? [String]?,
           // let modifiers = menuItem.modifiers as? [Modifier]?,
            let toppings = menuItem.toppings as? [String]? else { continue }
        let lineItemParams: [String: Any] = ["base_item_price": menuItem.basePrice,
                                     "category": menuItem.category,
                                     "description": menuItem.description,
                                     "item_id": menuItem.itemId,
                                     "modifierKeys": modifierKeys,
                                   //  "modifiers": modifiers,
                                     "name": menuItem.name,
                                     "photoUrl": menuItem.photoUrl,
                                     "quantity": menuItem.quantity,
                                     "size": menuItem.size,
                                     "sizeAddOnPrice": menuItem.sizeAddOnPrice,
                                     "toppings": toppings,
                                     "toppingsAddOnPrice": menuItem.toppingsAddOnPrice,
                                     "total_mod_price": menuItem.totalModPrice,
                                     "total_price": menuItem.totalPrice,
                                     "unit_price": menuItem.unitPrice
        ]
        lineItemsRef.setData(lineItemParams)
        { err in
            if let e = err {
                print("$-- error uploading transaction data \(e)")
                completion(nil)
            } else {
                completion(nil)
            }
        }
    }

    completion(orderId)
}

这是Modifier类:

struct Modifier: Codable {

    let type: String
    let itemModifierGroupId: String
    let name: String
    let price: Int

    private enum CodingKeys: String, CodingKey {
        case type
        case itemModifierGroupId = "item_modifier_group_id"
        case name
        case price
    }
}

0 个答案:

没有答案