简体   繁体   中英

How to retrieve data from each child in Firebase?

I'm trying to retrieve all the values that I have in each post (post_text, timestamp, username) to be used in a Table View using Swift. I have tried this code but wasn't sure where to go from here to get each value from posts.

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

The JSON Firebase file:



    {
      "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" : "ad@ad.com",
          "posts" : {
            "-KAm_8ShLSKrKKMhNjpm" : {
              "post_text" : "Hello :)",
              "timestamp" : 1455768771004
            }
          },
          "provider" : "password",
          "username" : "ad"
        },
        "b7b7de04-e180-4cac-abd3-57c016640e32" : {
          "email" : "user@user.com",
          "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" : "hello@hi.com",
          "posts" : {
            "-KAqlyZAah6bclwqWi5M" : {
              "post_text" : "Hello",
              "timestamp" : 1455839243184
            }
          },
          "provider" : "password",
          "username" : "hello"
        }
      }
    }
    

How could I do this?

You can just create an object Post that can be initialized by a Dictionary . Then, just fetch the single key with his value.

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

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

    posts.append(post)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM