2016-02-19 100 views
0

我試圖檢索我在每個帖子(post_text,時間戳,用戶名)中使用Swift的表視圖中使用的所有值。我試過這段代碼,但不知道該從哪裏去從帖子中獲取每個值。如何從Firebase中的每個孩子檢索數據?

ref.observeEventType(.Value, withBlock: { snapshot in 
     self.posts = snapshot.value.objectForKey("posts") as! [String: String] 
     print(self.posts) 
     self.tableView.reloadData() 
}) 

的JSON文件火力地堡:

 


    { 
     "posts" : { 
     "-KAqlyZ71SNZfZ4Zbs27" : { 
      "post_text" : "Hello", 
      "timestamp" : 1455839242909, 
      "username" : "hello" 
     }, 
     "-KAqmD6HPbhAVkjT54-k" : { 
      "post_text" : "Hi", 
      "timestamp" : 1455839306600, 
      "username" : "user7" 
     }, 
     "-KAr9ATmAjObiTsn4yUC" : { 
      "post_text" : "Hi", 
      "timestamp" : 1455845587135, 
      "username" : "user7" 
     }, 
     "-KArIBlnKSJWGhD9Me6T" : { 
      "post_text" : "Dddd", 
      "timestamp" : 1455847983983 
     } 
     }, 
     "users" : { 
     "5476cde6-b343-476d-abb7-8131d3766ba7" : { 
      "email" : "[email protected]", 
      "posts" : { 
      "-KAm_8ShLSKrKKMhNjpm" : { 
       "post_text" : "Hello :)", 
       "timestamp" : 1455768771004 
      } 
      }, 
      "provider" : "password", 
      "username" : "ad" 
     }, 
     "b7b7de04-e180-4cac-abd3-57c016640e32" : { 
      "email" : "[email protected]", 
      "posts" : { 
      "-KAqmD6HPbhAVkjT54-l" : { 
       "post_text" : "Hi", 
       "timestamp" : 1455839306869 
      }, 
      "-KAr9ATq-MEkYmAr2SB_" : { 
       "post_text" : "Hi", 
       "timestamp" : 1455845587513 
      }, 
      "-KArIBlxY-FvbsmgF5bI" : { 
       "post_text" : "Dddd", 
       "timestamp" : 1455847985342 
      } 
      }, 
      "provider" : "password", 
      "username" : "user7" 
     }, 
     "fb67da22-e0dd-4ced-873b-53a588d78feb" : { 
      "email" : "[email protected]", 
      "posts" : { 
      "-KAqlyZAah6bclwqWi5M" : { 
       "post_text" : "Hello", 
       "timestamp" : 1455839243184 
      } 
      }, 
      "provider" : "password", 
      "username" : "hello" 
     } 
     } 
    } 
 

我怎麼能這樣做?

+0

下面將會回答一些問題,但這裏有一個很好的教程:http://www.raywenderlich.com/109706/firebase-tutorial-getting-started。您可能也有興趣使用FirebaseUI爲您完成繁重工作:https://github.com/firebase/firebaseui-ios#firebasetableviewdatasource –

回答

0

您可以創建一個可由Dictionary初始化的對象Post。然後,只需用他的價值獲取單個密鑰。

var posts : [Post] = []() 
json.forEach { (key, dictionary) -> in 

    let post = Post(
     key: key, 
     dictionary: dictionary 
    ) 

    posts.append(post) 
} 
相關問題