正在保存的对象
customer: irelyn - items: ["Chicken Bacon Ranch", "BLT"] - total price: 17.30
IM收到错误:
The operation couldn’t be completed. (FirebaseFirestoreSwift.FirestoreEncodingError error 0.)
这是我的密码:
//function to save the order
func saveItem(item: Order, completion: @escaping (Error?) -> ()) {
let db = Firestore.firestore()
let encoder = JSONEncoder()
do {
let data = try encoder.encode(item)
let dictionary = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any] ?? [:]
db.collection("items").addDocument(data: dictionary) { (error) in
completion(error)
}
} catch {
completion(error)
}
}
}
我的“订单”对象模型:
struct Order: Identifiable, Codable {
@DocumentID var id: String?
let customer: String
let total: String
let orderItems: [String]
}
//the menuitem objects -> im storing the name into an array for all the items being ordered in the object above
struct MenuItem: Identifiable, Codable {
var id: String?
var name: String
var description: String
var price: Double
}
View Code:
Button {
//store the menu items
let array: [MenuItem] = appVM.myCart
let menuItems: [String] = array.map { $0.name }
let formatter = NumberFormatter()
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
let price = appVM.totalAmount
let orderTotal = formatter.string(for: price) ?? ""
let user = loginVM.currentUser?.fullName
//store the new order with total, name, and order
let newOrder = Order(customer: user ?? "",total: orderTotal, orderItems: menuItems)
print("customer: \(newOrder.customer) - items: \(newOrder.orderItems) - total price: \(newOrder.total)")
appVM.saveItem(item: newOrder) { (error) in
if let error = error {
print(error.localizedDescription)
} else {
print("Success")
}
}
} label: {
Text("Place My Order!")
.bold()
.padding()
.frame(maxWidth: .infinity)
.background(Color.white)
.cornerRadius(30)
.padding(.horizontal)
.foregroundColor(.orange)
}
数据都是正确创建的,如果数据不能正常工作,它只是上传。尝试了许多解决方案,没有工作。帮助将不胜感激!
2条答案
按热度按时间ljo96ir51#
用途
代替
你会得到一个更好的描述。
encodingIsNotSupported("DocumentID values can only be encoded with Firestore.Encoder")
表示当你
struct
有@DocumentID
时,你必须使用。item
在这种情况下具有类型Order
。不能使用
JSONSerialization
lsmepo6l2#
修复了这个问题,这是由于使用firebase的@documentID作为我的id属性