How to store your favorites with Firebase

I have a backend on firebase, and there is something like post, like on Facebook. Therefore, I need functionality similar to these posts. The question is, how to store your favorites and users who like the post? All help will be appreciated.

+7
ios swift firebase
source share
2 answers

Take this data structure:

{ "posts": { "post_1": { "uid": "user_1", "title": "Cool Post" }, "post_2": { "uid": "user_1", "title": "Another Cool Post" }, "post_3": { "uid": "user_2", "title": "My Cool Post" } }, "postLikes": { "user_1": { "post_3": true }, "user_2": { "post_1": true, "post_2": true } } } 

The location /posts receives all posts. Location /postLikes retrieves all liked posts in posts.

So let's say you are user_1 . To get user_1 messages like, you could write this Firebase database listener:

 let ref = Firebase(url: "<my-firebase-app>") let uid = "user_1" let userRef = ref.childByAppendingPath(uid) userRef.observeEventType(.Value) { (snap: FDataSnapshot!) in print(snap.value) // prints all of the likes // loop through each like for child in snap.children { let childSnap = child as! FDataSnapshot print(childSnap.value) // print a single like } } 

It is important to note the β€œflatness” of the data structure. postLikes not saved under every post . This means that you can get post without getting all your preferences. But, if you want to get both, you can still do this because you know the user ID.

Try giving Firebase data structuring guidance what you read

+12
source share

To add to the comments in the david answer above (I can't add a comment yet) to get a count for likes, you want to use transactional data.

In your firebase you want to configure the "likes" of the child, it looks something like this in the node message:

 { "posts": { "post_1": { "uid": "user_1", "title": "Cool Post" "likes": 0 }, "post_2": { "uid": "user_1", "title": "Another Cool Post" "likes": 0 }, "post_3": { "uid": "user_2", "title": "My Cool Post" "likes": 0 } 

The code in Xcode looks something like the one below. You will add a counter every time a message is liked (the same code, but use "- 1" to not like it).

 self.databaseRef.child("posts").child("post_1").child("likes").runTransactionBlock({ (currentData:FIRMutableData!) in var value = currentData.value as? Int //check to see if the likes node exists, if not give value of 0. if (value == nil) { value = 0 } currentData.value = value! + 1 return FIRTransactionResult.successWithValue(currentData) }) 

Hope this helps someone!

Additional reading for such a counter:

Upvote / Downvote system in Swift through Firebase

Counter counter not updating node in firebase

+6
source share

All Articles