swift - Getting Invalid Firebase Data error when trying to save to Firebase using Swift
问题描述
Objective: Save Drinks order to Firebase
Problem: Converting [Drink] array to Dictionary
I get the following error message:
ERROR: 'InvalidFirebaseData', reason: '(setValue:withCompletionBlock:) Cannot store object of type vipeeps.Drink at drinksOrdered.0009373. Can only store objects of type NSNumber, NSString, NSDictionary, and NSArray.'
func saveDrinkOrder(orderRef: String, venueName: String, drinksOrder: [Drink], chargeId: String, chargeObject: [String: Any], handler: @escaping(Bool) -> ()){
guard let uid = Auth.auth().currentUser?.uid else { return }
let orderNo = orderRef
let timeStamp = Date().timeIntervalSince1970
let drinksOrdered = Dictionary(uniqueKeysWithValues: drinksOrder.map {($0.posId, $0.self)}) //<---issue here: $0.self if still a Drink object
let venue = venueName
let stripeChargeResponse = chargeObject
let ref = REF_DRINK_ORDERS.child(uid).child(orderNo)
//message node values
let values = [
"dateOrdered": timeStamp,
"venueName": venue,
"timeStamp": Date().timeIntervalSince1970,
"drinksOrdered": drinksOrdered,
"stripeResponse": stripeChargeResponse] as [String : Any]
ref.setValue(values) { (error, dbRef) in
if error != nil {
print(error!.localizedDescription)
handler(false)
return
}
handler(true)
}//end setValue
}//end func
asdf
class Drink {
var posId: String?
var name: String?
var description: String?
var tags: [String]?
var unitPrice: String?
init(dictionary: [String: Any]) {
self.posId = dictionary["posId"] as? String
self.name = dictionary["name"] as? String
self.description = dictionary["description"] as? String
self.unitPrice = dictionary["unitPrice"] as? String
self.tags = dictionary["tags"] as? [String]
}//end init
}//end class
解决方案
I figured it out, probably not the most efficient approach but it works:
I updated my Drink class to return the object as a Dictionary[String:Any]
var asDictionary : [String:Any] { let mirror = Mirror(reflecting: self) let dict = Dictionary(uniqueKeysWithValues: mirror.children.lazy.map({ (label:String?, value:Any) -> (String, Any)? in guard let label = label else { return nil } return (label, value) }).compactMap { $0 }) return dict }
Loop through the [Drinks] array to create a Dictionary to Firebase
var drinksDict = String:Any
for drink in drinksOrder { drinksDict[drink.posId!] = drink.asDictionary
推荐阅读
- angular - 在内部可观察对象的取消/完成时发出
- spring - Spring Data Elasticsearch - 如何暂停刷新?
- birt - Birt:如何生成存储在 Postgres 表中的附件
- html - GatsbyJs - 从 config.js 读取时图像渲染不起作用
- python - 计算字母数字单词的最佳方法是什么?
- c# - 如何避免 C# 程序集依赖传播?
- python - 在 Django 模型中将继承更改为 OneToOne 关系
- mysql - 带有子查询的SQL,高效的方式
- ios - I have some problem about show last saved CoreData data in tableView
- angular - Bazel + Angular + SocketIO 原因:未捕获的 TypeError:XMLHttpRequest 不是构造函数