2016-09-17 83 views
0

接收火力地堡的AutoID我有一個firebase結構,看起來像這樣: enter image description here在tableViewController

藍色一個名爲feedPosts,綠色的是用戶id,沒有顏色的一個是自動識別火力創建附加數據橙色的說內容:「用戶發帖字符串在這裏」

我的問題是,我不知道如何獲得firebase autoId,以便我可以顯示用戶在我的tableViewController中發佈的內容。我需要將數據追加到userId,以便用戶可以發佈多個帖子 - 我只是不知道如何獲得tableViewController中的密鑰。幫我?

+0

你知道那個autoID是什麼嗎?否則,它會愚蠢的檢索整個數據,通過每個自動ID循環和檢索單個數據節點。 – Dravidian

+0

不,我事先不知道autoID是什麼..你能給我一個例子來處理嗎? –

回答

0

如果你的JSON是這樣的: -

foodItems{ 
     uid1 :{ 
      autoID1 :{ 
       content : "This is a String" 
     } 
     } 
    } 

爲了獲取其中含有的content : "This is a String"

雨燕2.3

let parentRef = FIRDatabase.database().reference().child("foodItems/\(FIRAuth().auth()!.currentUser!.uid)").queryOrderedByChild("content").queryEqualToValue("This is a String") 

    parentRef.observeSingleEventOfType(.Value, withBlock:{(snap) in 

     if let snapContainingContent = snap.value as? [String:AnyObject]{ 

     for each in snapContainingContent{ 
      print(each.0)//your autoID 
      print(each.1)//your content String 
      if let autoDict = each.1 as? NSDictionary{ 

        print(autoDict["content"]!) 
        print(autoDict.allKeys(for: "This is a String")[0]) 


       } 
      } 

     } 

}) 

斯威夫特3

的自動識別
let parentRef = FIRDatabase.database().reference().child("Posts/foodItems/uid1").queryOrdered(byChild: "content").queryEqual(toValue: "This is a String") 

    parentRef.observeSingleEvent(of: .value, with:{(snap) in 

     if let snapContainingContent = snap.value as? [String:AnyObject]{ 

      for each in snapContainingContent{ 
       print(each.0)//your autoID 
       print(each.1)//your content String 
       if let autoDict = each.1 as? NSDictionary{ 

        print(autoDict["content"]!) 
        print(autoDict.allKeys(for: "This is a String")[0]) 
       } 

      } 

     } 

    }) 
+0

但是,這隻會顯示我的代碼的特定部分?我想顯示所有的內容:「用字符串」 - 是不是可能? –

+0

我編輯了我的答案......這是你用autoID得到的最好的答案。另一種方法是遍歷整個節點以搜索該子節點中的特定內容:)快樂編碼 – Dravidian

1

最簡單的解決方案是更改結構以匹配您試圖獲取的數據。這裏就是你現在

feedPosts 
    -fbUserId0 
    -autoIdForThisPost1 
     content: "users post string is here" 
    -fbUserId1 
    -autoIdForThisPost1 
     content: "users post string is here" 

它改變這種

feedPosts 
    -autoIdForThisPost0 
     post_by_uid: "-fbUserId0" 
     content: "users post string is here" 
    -autoIdForThisPost1 
     post_by_uid: "-fbUserId1" 
     content: "users post string is here" 

然後你就可以對所有通過-fbUserId1職位的查詢。這將返回將包含內容的每個帖子節點以及作爲autoId的帖子的KEY。

這也是可擴展的,因爲您還可以存儲例如關於帖子的時間戳,或者甚至可以存儲這是迴應的帖子。

另一個優點是它使整個結構更扁平(扁平更好!在Firebase中非常重要)並且更具查詢能力。

+0

我要試着去做 - 這聽起來像是最好的解決方案!我如何查詢userId? –

+0

@ D.Finna在這裏查看指南[檢索數據](https://firebase.google.com/docs/database/ios/retrieve-data),並在Filtering Data部分查看queryEqualToValue。 – Jay

+0

謝謝!這聽起來像我可以使用的:-)我會毫無疑問地看看! –