我正在尝试将Firebase数据库中的数据提取到字典中,但我得到的值是零!我试图重构我的数据库,以及观察(.value ...)和观察(.childAdded ...),但没有任何运气。
这是我的firebase数据库结构:
{
"posts" : {
"2017" : {
"Nov" : {
"19" : {
"12:56 PM" : {
"activities" : "jumping, rafting",
"description" : "Hello from the other side",
"location" : "Bucharest, Roamania",
"privacy" : "1",
"title" : "Making papers",
"userID" : "cTq84vE40XhD1EprpxlQUOIwO0q2"
}
}
}
}
},
这是我的提取数据功能:
func fetchPosts() {
refHandle = ref.child("posts").observe(.value, with: { (snapshot) in
if snapshot.childrenCount > 0 {
self.postList.removeAll()
for posts in snapshot.children.allObjects as![DataSnapshot] {
let postObject = posts.value as? [String: AnyObject]
let activities = postObject?["activities"]
let description = postObject?["description"]
let location = postObject?["location"]
let privacy = postObject?["privacy"]
let commentsNr = postObject?["commentsNr"]
let likesNr = postObject?["likesNr"]
let image = postObject?["images"]
let title = postObject?["title"]
let name = postObject?["name"]
let date = postObject?["date"]
let post = Post(title: title as? String, name: name as? String, image: image as? UIImage, info: description as? String, likesNr: likesNr as? Int, privacy: privacy as? Int, location: location as? String, commentsNr: commentsNr as? Int, activities: activities as? String, date: date as? String)
print("A~ \(activities) / \(location)")
self.postList.append(post)
}
}
})
}
}
我做错了什么?我应该重新考虑firebase数据库结构,在程序中轻松访问,还是应该尝试不同的算法来获取数据?
答案 0 :(得分:0)
在作为词典之前,您是否打印了快照包含的内容?
对我来说,您的快照从posts
节点开始。然后,当您选择值观察器时,您的快照将仅包含posts
作为键和所有子值。
如果要保留这样的数据库结构,则需要深入了解节点级别以查询所需的信息。在此示例中,应该起作用的查询可以是:
refHandle = ref.child("posts").child("2017").child("Nov").child("19").child("12:56 PM").observe(.value, with: { (snapshot) in //etc
但我建议您更改数据库结构,因为如果您已阅读有关数据库结构的Firebase文档,那么必须避免使用嵌套数据。您需要展平数据库结构以获得最低级别的节点。比如1级或2级:Structure your database
更新:如果您拥有结构良好的Firebase数据库,那么您将更容易访问您的数据。对于我来说,在不同的节点中分离帖子的时间,这是错误的。只将时间戳作为帖子的属性。你可以从这样的结构开始:
posts
|-idPost
|-idUser
|-activities
|-postDate
|-etc...All the attributes for a post