检索字典从Firebase斯威夫特
问题描述:
我想排序在不同的标签字典中的每个项目(在我的例子:投票在firebase去指定“选票标签”,文本在“textlabel”...),我试过这样做,但我真的得到股票。我想我的问题是,因为每一个岗位有一个新的关键,我不知道如何直接去儿童检索字典从Firebase斯威夫特
var posts: [String: AnyObject] = [String: AnyObject]()
@IBAction func save(sender: AnyObject) {
let titre = Titre.text
let soustitre = SousTitre.text
let text = Text.text
let newPosts: Dictionary<String, AnyObject> = [
"titre": titre!,
"soustitre": soustitre!,
"text": text!,
"votes": votes
]
ref.childByAppendingPath(current).childByAppendingPath("Posts").childByAutoId().setValue(newPosts)
ref.childByAppendingPath(current).observeEventType(.ChildAdded, withBlock: { snapshot in
print(snapshot.value)
从这里我真的迷路了,我找到一个教程这个部分,但要很荣幸,我没有得到它。
var posts = [NSDictionary]()
for item in snapshot.children{
let child = item as! FDataSnapshot
let dict = child.value as! NSDictionary
posts.append(dict)
}
self.TextLabel.text = snapshot
})
}
任何线索都会非常有用!
谢谢你的时间!
答
鉴于你的火力地堡结构看起来像这样
和一些代码来阅读所有的帖子节点和显示自己的孩子。快照返回一组键:值对这样使用密钥来访问值
let myRootRef = Firebase(url:"https://jaytest.firebaseio.com")
let postsRef = myRootRef.childByAppendingPath("posts"
postsRef.observeSingleEventOfType(.Value, withBlock { snapshot in
for child in snapshot.children {
if let title = child.value["title"] as? String {
print(title)
}
if let text = child.value["text"] as? String {
print(text)
}
if let title = child.value["vote"] as? String {
print(vote)
}
}
}
输出
some title
some text
some vote
another title
another text
another vote
yet another title
yet another text
yet another vote
基于更多的信息
,问题是:
如何从Firebase中的帖子检索特定的子数据。
假设我们有一个tableview列出我们的帖子。每个帖子的关键字(node_0,node_1 & node_2)应存储在与tableView匹配的数组中(它可以用作数据源)
当用户点击或点击某一行时,例如查找第1行,数组中的数据。在这种情况下,假定他们挖掘第1行中的tableView:
VAR theKey = myArray的[1] //返回一个名为“node_1”
现在我们有钥匙键,从火力地堡获得的数据是一个'快照'
postsRef = rootRef.childByAppendingPath("posts")
thisPostRef = postsRef.childByAppendingPath(theKey)
thisPostRef.observeSingleEventOfType(.Value withBlock { snapshot in
let title = snapshot.value["title"] //title = another title
let text = snapshot.value["text"] // text = another text
let vote = snapshot.value["vote"] //vote = another vote
}
答
此外,您询问了有关您的问题的排序问题。为此,您可以获取数据库引用的查询。例如:
postsRef = rootRef.childByAppendingPath("posts")
let orderedQuery = postsRef.queryOrdered(byChild: "votes")
然后您可以使用查询代替参考,为您的观察家
orderedQuery.observeSingleEventOfType(.value, with: { (snapshot) -> Void in
// ...
感谢您的这个答案,我可以做到这一点,但我想访问只是一个特定节点(根据所选节点的节点ID而改变),并且在该节点中,我希望能够检索不同的子节点。是否有可能获得一个变量,将根据选定的帖子更改密钥?为了让我能够找回路径,或者我应该以其他方式做到这一点? –
@PierreDepingon我不确定我完全理解这个问题。我想你在问什么;如果用户选择了一个帖子(在UI中),您想要从Firebase中发布子帖子? – Jay
对不起,是的,确切的! –