Firebase中的嵌套信息 [英] Nested information in Firebase
问题描述
如何访问处于更深层快照级别的信息?我是否总是需要启动另一个查询?为了向您展示我的意思,我有一个我的结构的屏幕截图:
DataStructure
我正在加载我的查询中的所有帖子,我可以阅读作者信息等,但是如何获取选项中的信息?我尝试了下面的内容:
$ b $ pre $ ref $ {$ c $ ref $在
中有{(snapshot:FIRDataSnapshot)如果snapshot.value ==零{
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 =这个帖子没有描述
post.timestamp = snapshotValue [timestamp] as?NSNumber
let options = snapshotValue [options]
print(options)
当我打印选项时,可以看到这些信息,但是当我尝试将其转换为NSDictionary或其他东西o访问它,打印零?我也可以定义一个新的属性,如post.options,如果这可能有帮助?选项并不总是只有0和1,它的变量,所以我需要遍历这些。我怎样才能做到这一点?
继续对原始问题的评论,您可以像下面这样访问选项值:
如果让options = snapshotValue [options] as? [任何] {
选项选项{
如果让optionDict =选项为? [字符串:任何] {
让votes = optionDict [votes] as? Int
让url = optionDict [uri]为?字符串
}
}
}
How can I access information that is in a "deeper" level of the snapshot? Do I always need to start another Query? To show you what I mean, I have a screenshot of my structure: Screenshot of DataStructure
I am loading all the posts in my query, I can read the author information etc, but how can I get the information inside options? I tried the following:
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)
when I print options, I can see the information, but when I try to cast it to NSDictionary or something to access it, it prints nil? I can also define a new attribute like post.options if that may help? Options is not always just 0 and 1, its variable, so I need to iterate through those. How can I achieve that?
Following up the comments on the original question, you can access the option values like this:
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中的嵌套信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!