Oguz
Oguz

Reputation: 11

How to retrieve child data from firebase realtime database on Swift 5

I am facing with firebase problem for 2 days and couldn't handle it.

Here is my realtime database

enter image description here

I am getting content, publishdate, source etc. but tags.

I want to get "0:100" value that child of tags. Here is my code:

Could you please help me ?

databaseRef.child("posts").queryOrderedByKey().observe(.childAdded, with: { (snapshot) in
  if let valueDictionary = snapshot.value as? [AnyHashable:String] {
    let newsTitle = valueDictionary["title"]
    let newsImage = valueDictionary["imageUrl"]
    let publishData = valueDictionary["publishData"]
    let content = valueDictionary["content"]
    let tags = valueDictionary["tags"]

    self.news.insert(newsStruct(newsTitle: newsTitle, newsImage: newsImage, publishData: publishData, content: content, tags: tags), at: 0)

    self.tableView.reloadData()
    self.tableViewTagsNews.reloadData()
 }
})

Upvotes: 1

Views: 983

Answers (2)

Jay
Jay

Reputation: 35667

Assuming you have multiple posts like this

posts
   0
      tags
         0: 100
         1: 200
   1
      tags
         0: 100
         1: 200

Here's the code that will iterate over each post, one at a time, read the content and then read the tags and output them to the console.

func readPostTags() {
    let postsRef = self.ref.child("posts")
    postsRef.observe(.childAdded, with: { snapshot in
        let content = snapshot.childSnapshot(forPath: "creation_date").value as! String
        let tagsSnap = snapshot.childSnapshot(forPath: "tags")
        let allChildTagsSnap = tagsSnap.children.allObjects as! [DataSnapshot]
        for tagChildSnap in allChildTagsSnap {
            let key = tagChildSnap.key
            let value = tagChildSnap.value as! Int
            print(content, key, value)
        }
    })
}

and the output

0 100
1 200
0 100
1 200

Keep in mind that .childAdded will leave an observer on that node and notify you of further additions.

Upvotes: 2

Cesare
Cesare

Reputation: 9419

I think it’s because you’re casting the dictionary so its values are Strings only: if let valueDictionary = snapshot.value as? [AnyHashable:String] so the key value pair that does not have a string as its value gets lost in the conversion.

Instead, cast snapshot.value as [String: Any] and then get the tags like this: let tags: Int = valueDictionary[“tags”] ?? 0.

Upvotes: 1

Related Questions