Firebase中的嵌套信息

我如何访问处于“更深层”快照级别的信息? 我是否总是需要启动另一个查询? 为了向您展示我的意思,我有一个结构的屏幕截图:DataStructure的屏幕截图

我正在加载我的查询中的所有post,我可以阅读作者信息等,但我怎么能得到选项内的信息? 我尝试了以下内容:

ref.child("posts").child("details").observe(.childAdded, with: { (snapshot:FIRDataSnapshot) in if snapshot.value == nil { return } let post = Post() guard let snapshotValue = snapshot.value as? NSDictionary else { return } post.postID = snapshot.key post.title = snapshotValue["title"] as? String post.postDescription = snapshotValue["description"] as? String if (post.postDescription == ""){ post.postDescription = "No description has been entered for this post.." } post.timestamp = snapshotValue["timestamp"] as? NSNumber let options = snapshotValue["options"] print(options) 

当我打印选项,我可以看到的信息,但是当我试图将其转换为NSDictionary或其他东西来访问它,打印零? 我也可以定义一个新的属性,如post.options,如果这可能有帮助? 选项并不总是只有0和1,它的variables,所以我需要遍历这些。 我怎样才能做到这一点?

继续关于原始问题的评论,您可以像这样访问选项值:

 if let options = snapshotValue["options"] as? [Any] { for option in options { if let optionDict = option as? [String:Any] { let votes = optionDict["votes"] as? Int let url = optionDict["uri"] as? String } } } 

这里有一个非常简单的答案,将与Firebase结构一起使用(请注意,Firebase数组只能在特定情况下使用,一般应避免使用)。

给定一个结构

 posts post_id_0 caption: "some caption" comment: "some comment" options: 0: votes: "10" url: "some url" 1: votes: "20" url: "some url" 

请注意,该结构与OP类似,因为选项子节点是Firebase数组,其中每个索引还包含子节点。 所以关键是索引(0,1,2),每个子项都是key:values对(votes:value和url:value)的字典,

下面的代码将在这个特定节点中读取,打印标题和注释,然后迭代ARRAY选项并打印数组中每个子项的投票和URL

 ref.child("posts").child("post_id_0") .observeSingleEvent(of: .value, with: { snapshot in //treat the whole node as a dictionary let postDict = snapshot.value as! [String: Any] //and since it's a dictionary, access each child node as such let caption = postDict["caption"] as! String let comment = postDict["comment"] as! String print("caption: \(caption) comment: \(comment)") //the options child node is an array of indexes, each with // a dictionary of child nodes let options = postDict["options"] as! [[String:Any]] //array of dictionaries //now iterate over the array for option in options { let votes = option["votes"] //each option child is a dict let url = option["url"] print("votes \(votes!) url: \(url!)") } }) 

请注意,我们以这种方式指示选项子节点的结构

 let options = postDict["options"] as! [[String:Any]] 

它是key:value(String:Any)字典的数组

必须读入整个选项节点才能使用它,这一点非常重要。 如果有10k个孩子,那么效率会非常低。 这也是不可查询的,所以如果你想要统计有多less重复的url,那么整个节点必须被读入然后parsing。

更好的select是使用childByAutoId来创build节点键名称

 posts post_id_0 caption: "some caption" comment: "some comment" options: -Yuijjismisdw votes: "10" url: "some url" -YJ989jijdmfm votes: "20" url: "some url" 

Yuijjismisdw是用childByAutoId创build的。