2

My Firebase database looks like this

enter image description here

Here I got a field name user_post. Then I am adding a new post using childByAutoId() . Then inside that I am inserting the post according the postId . Now I want to update the like and add the new field peopleWhoLike. Could anybody tell me how to insert or update a value of any particular post. The sequence is user_post > childByAutoId() > postId

Here is my code:

 let keyToPost = ref.child("user_post").childByAutoId().key ref.child("user_post").queryOrdered(byChild: self.postID).observeSingleEvent(of: .value, with: { (snapshot) in if (snapshot.value as? [String : AnyObject]) != nil { let updateLikes: [String : Any] = ["peopleWhoLike/\(keyToPost)" : FIRAuth.auth()!.currentUser!.uid] ref.child("user_post").child(self.postID).updateChildValues(updateLikes, withCompletionBlock: { (error, reff) in if error == nil { ref.child("user_post").child(self.postID).observeSingleEvent(of: .value, with: { (snap) in if let properties = snap.value as? [String : AnyObject] { if let likes = properties["peopleWhoLike"] as? [String : AnyObject] { let count = likes.count let update = ["Like" : count] ref.child("user_post").child(self.postID).updateChildValues(update) self.likeBtn.isHidden = true self.unlikeBtn.isHidden = false self.likeBtn.isEnabled = true } } }) } }) }//xxx }) ref.removeAllObservers() 
1
  • added a more detailed answer. Commented Mar 7, 2017 at 13:53

1 Answer 1

3

Here is how you can update one value at a time for example,

let ref : FIRDatabaseReference! ref = FIRDatabase.database().reference() ref.child("yourNode").child("subNode").updateChildValues(["yourKey": yourValue]) 

What I did was write the key to my posts. When a post was created a took the childByAutoID and added that to the post data so I could reference it later. I would reference it as "key" and the value would be the childByAutoId string. Once I had that key I would be able to add a like, like this,

on click

ref.child("yourNode").child(postKey).updateChildValues(["key": yourValue]) 

You could make a new node at the root called "Likes" whenever a user likes or unlikes it would take the postKey and create a subNode under the Likes node and then add the userId. When the post would load you would go into the Likes nodes and match the posts and then check it that user has liked or not.

likes example

Here I have user-watchlists but it could be the same as likes. In my app when a user saves a post. I record the userId under watchlists and in the userId is the postId that was saved. This could be similar to likes. Then I just compare and see if there is a match.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.