如何使用Firebase存储喜欢的内容

Zha*_*nes 9 ios firebase swift

我有一个关于firebase的后端,有像Facebook这样的帖子.所以我需要喜欢这些帖子的功能.问题是如何存储喜欢帖子的喜欢和用户?所有帮助将不胜感激

Dav*_*ast 13

采用这种数据结构:

{
   "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         
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

该位置/posts检索所有帖子.该位置/postLikes检索帖子上的所有喜欢.

所以,让我们说你是user_1.要获得帖子user_1,您可以编写此Firebase数据库侦听器:

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
  }
}
Run Code Online (Sandbox Code Playgroud)

这里需要注意的重要一点是数据结构的"平坦性".postLikes没有存储在每个post.这意味着您可以在post不获取所有喜欢的情况下检索.但是,如果你想同时获得两者,你仍然可以这样做,因为你知道用户的id.

尝试提供有关结构化数据的Firebase指南


gk1*_*103 7

要添加到david的答案中的评论,上面(我还不能添加评论)来获取喜欢的计数,你想要使用交易数据.

在你的firebase中,你想设置一个"喜欢"的孩子,在post节点看起来像这样:

{
   "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
      }
Run Code Online (Sandbox Code Playgroud)

Xcode中的代码看起来类似于下面的代码.每次收到帖子时你都会添加一个计数器(相同的代码,但使用" - 1"不同).

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)

                            })
Run Code Online (Sandbox Code Playgroud)

希望这有助于某人!

这种计数器的附加读物:

Swift中的Upvote/Downvote系统通过Firebase

追随者计数器不更新firebase中的节点