我刚开始使用Firebase进行Swift编程。我设法使用以下内容从Json获取一些数据:
let ref = FIRDatabase.database().reference()
ref.child("Posts").child("1").child("Post").child("Like").observeSingleEvent(of: .value, with: { (Snapshot) in
let Value = Snapshot.value as? Int
print(Value!)
})
但是,我试图先获取整个对象,然后再获取每个元素的值。所以这是我的尝试,但我的应用程序一直被终止:
let ref = FIRDatabase.database().reference()
ref.child("Posts").child("1").child("Post").observeSingleEvent(of: FIRDataEventType.childAdded, with: { (snapshot) in
print(snapshot.children.value(forKey: "Like") as? Int)
print(snapshot.children.value(forKey: "Image") as? String)
})
知道我哪里弄错了吗? 这是我的Json:
{
"Posts": {
"1": {
"Post": {
"Poster_ID": "ID",
"Post_Time_stamp": "12:12:12AM",
"Image": "img.png",
"Video": "video.mov",
"Like": "3",
"Dislike": "0",
"Massage": {
"Massage_ID": "MSG_ID",
"Massager": "id",
"Massage_Time_stamp": "12:12:12PM",
"Massage_content": "comment"
}
}
},
"2": {
"Post": {
"Poster_ID": "ID",
"Post_Time_stamp": "12:12:12AM",
"Image": "img.png",
"Video": "video.mov",
"Like": "3",
"Dislike": "0",
"Massage": {
"Massage_ID": "MSG_ID",
"Massager": "id",
"Massage_Time_stamp": "12:12:12PM",
"Massage_content": "comment"
}
}
}
},
"User": {
"1": {
"User_name": "name",
"User_pass": "pass",
"User_avatar": "img.png"
},
"2": {
"User_name": "name",
"User_pass": "pass",
"User_avatar": "img.png"
}
}
}
答案 0 :(得分:2)
首先尝试打印snapshot
,看看是否可以检索任何内容,请尝试此操作
将FIRDataEventType用作.value
而不是.childAdded
。由于.childAdded
仅在将子节点添加到该引用节点时触发,因此.value
将当前值检索为该参考点。
let ref = FIRDatabase.database().reference()
ref.child("Posts").child("1").child("Post").observeSingleEvent(of: .value, with: { (snapshot) in
print(snapshot)
print(snapshot.children.value(forKey: "Like") as? Int)
print(snapshot.children.value(forKey: "Image") as? String)
})
答案 1 :(得分:1)
如果您想要获取帖子对象,则需要访问value
,同时注意childAdded
事件,而不是let ref = FIRDatabase.database().reference()
ref.child("Posts").child("1").child("Post")
.observeSingleEvent(of: .value, with: { (snapshot) in
if let dict = snapshot.value as? [String:Any] {
print(dict["Like"] as? Int ?? 0)
}
})
。
$(".framed-content").mCustomScrollbar({
theme: "dark-2",
scrollButtons:{ enable: true },
});