2016-04-25 86 views
2

我想排序在不同的標籤字典中的每個項目(在我的例子:投票在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 
    }) 

} 

任何線索都會非常有用!

謝謝你的時間!

FireBase

回答

2

鑑於你的火力地堡結構看起來像這樣

​​

和一些代碼來閱讀所有的帖子節點和顯示自己的孩子。快照返回一組鍵:值對這樣使用密鑰來訪問值

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 
} 
+0

感謝您的這個答案,我可以做到這一點,但我想訪問只是一個特定節點(根據所選節點的節點ID而改變),並且在該節點中,我希望能夠檢索不同的子節點。是否有可能獲得一個變量,將根據選定的帖子更改密鑰?爲了讓我能夠找回路徑,或者我應該以其他方式做到這一點? –

+0

@PierreDepingon我不確定我完全理解這個問題。我想你在問什麼;如果用戶選擇了一個帖子(在UI中),您想要從Firebase中發佈子帖子? – Jay

+0

對不起,是的,確切的! –

0

此外,您詢問了有關您的問題的排序問題。爲此,您可以獲取數據庫引用的查詢。例如:

postsRef = rootRef.childByAppendingPath("posts") 
let orderedQuery = postsRef.queryOrdered(byChild: "votes") 

然後您可以使用查詢代替參考,爲您的觀察家

orderedQuery.observeSingleEventOfType(.value, with: { (snapshot) -> Void in 
// ...