user809262 user809262 - 3 months ago 88
Swift Question

Firebase and reading nested data using Swift

I am trying to create a simple Instagram style app using Swift and Firebase and I am running into trouble reading comments for each Image post from Firebase.

Firebase Screenshot

A couple questions here:


  • I have the Posts at the top of the tree and then the keys per image under which have data on the comments added by each user. Is it possible to use the username as the key instead of the key generated by childbyAutoId in this instance ?

  • How would I read the userComment and UserName and save them into an Array that I can then display in a TableView ?



Any response is much appreciated. Thanks.

Answer
var postsCommentsDict : NSMutableDictionary = NSMutableDictionary()
var userNameArray : [String] = [String]() 
var userCommentArray : [String] = [String]()
FIRDatabase.database.reference().child("Posts").observeEventType(.Value, withBlock: {(Snapshot) in

if Snapshot.exists(){
    let imageD = Snapshot.value
    let imageD_ID = imageD.key
   //Retrieving the email and image name
     let imageName = imageD["userImage"] as! String
     let userEmail = imageD["userEmail"] as! String
    //Here you are accessing each image ID
    //First Question Alternative Completed

         //To answer the second Question :-

     FIRDatabase.database.reference().child("Posts").child(imageD_ID).child("comments").observeEventType(.Value, withBlock: {(Snapshot) in

  if let commentsDictionary = Snapshot.value {

    for each in commentsDictionary{

      postsCommentsDict.setObject(each["userName"] as! String : each["userComment"] as! String)
               //Saving the userName : UserComment in a dictionary
      userNameArray.append(each["userName"] as! String)
      userCommentArray.append(each["userComment"] as! String)
               //Saving the details in arrays
               //Prefer dictionary over Arrays

    }

} else {

   //no comments to append the arrays

        }

      })

   }
})

Once you are Done Saving the Comments dictionary : How to read it : -

for each in postsCommentsDict{
  let userNm = each.key
  let userComment = each.value
  //username and userComment's retrieved 

}

Please ignore the Typos, if any!...hope this helps..

Comments