Swift用子字典设置了firebase字典的值



我有一个对象,里面有一个子对象数组。我想把这个对象按原样保存到firebase数据库中。如何在swift中完成这个保存过程?

我试着创建新的字典

-LQTDo9OU9zw84IKnnW3
code: "111"
date: "4/11/2018"
dateAndTime: "2018/11/4/12/18"
description: "Description"
editor: "Burak Akdeniz"
predictions
-0
prediction: "Maç Sonucu 1"
predictionRatio: "2"
startTime: "12 : 18 PM"
status: "Waiting"

let newMatchRef = refMatches.child("platinium").childByAutoId()
let m : Dictionary<String, AnyObject> = [
"code": match.code as AnyObject,
"date": match.date as AnyObject,
"dateAndTime": match.dateAndTime as AnyObject,
"description": match.description as AnyObject,
"editor": match.editor as AnyObject,
"league": match.league as AnyObject,
"matchType": match.matchType as AnyObject,
"predictions": , //<--- HERE I have a predictions array includes prediction objects. This is the point I get error.
"startTime": match.startTime as AnyObject,
"status": match.status as AnyObject,
"team1": match.team1 as AnyObject,
"team2": match.team2 as AnyObject]
print(newMatchRef)
newMatchRef.setValue(m)

我需要将这个对象保存到firebase数据库及其子节点

Firebase的"关键"是始终将父节点和子节点视为键:值对。键总是字符串,但值可以是字符串、数字、布尔和数组。

在这种情况下,您基本上做对了,只需要将数组本身视为一个值。

让我们用两个元素来定义这个数组(每个元素都是一个字典)

let myArray = [
["prediction": "pred 0",
"predictionRatio": "2"],
["preduction": "pred 1",
"predictionRatio": "3"]
]

然后,让我们创建一个dictionary对象,它包含key:value对,并将整个内容写入firebase。

let dict:[String: Any] = [
"code": "1111",
"date": "04/11/2018",
"description": "Description",
"predictions": myArray
]

然后将其写入使用.childByAutoId 创建的引用

let ref = self.ref.child("some_node").childByAutoId()
ref.setValue(dict)

在some_node中的结果看起来像这个

child_by_auto_id_0
code: "1111"
date: "04/11/2018"
description: "some description"
predictions:
0:
"prediction": "pred 0"
"predictionRate": "2"
1:
"prediction": "pred 1"
"predictionRate": "3"

注意,我告诉字典它将获得String:Any的key:value对。如上所述,键总是字符串,但在这种情况下,一些值是字符串,然后一个是数组。"Any"类型处理该问题。

话虽如此,通常最好避免使用Firebase中的数组。使用它们很有挑战性,不容易维护,查询也很好。。。他们就是不喜欢被人质疑。最好使用相同的.childByAutoId方法生成数组的键。它要灵活得多。

predictions:
auto_id_0:
"prediction": "pred 0"
"predictionRate": "2"
auto_id_1:
"prediction": "pred 1"
"predictionRate": "3"

注意,如果你想查询,你可能需要考虑对你的预测节点进行反规范化

child_by_auto_id_0
code: "1111"
date: "04/11/2018"
description: "some description"
predictions
auto_id_0:
"prediction": "pred 0"
"predictionRate": "2"
"parent_node_ref": "child_by_auto_id_0"
auto_id_1:
"prediction": "pred 1"
"predictionRate": "3"
"parent_node_ref": "child_by_auto_id_0"

我假设当前实现的其余部分都很好,如果您将预测行替换为:

"predictions": match.predictions as [[String: String]]

如果上面的代码没有意义或不起作用,请编辑您的问题并显示预测数组&预测数据结构。

最新更新