如何限制Firebase上的星数?

我正在编写一个带有通用Feed的匿名社交媒体应用。 我想将post上的喜欢限制为每个用户一个,但我不知道如何限制每个用户的喜欢。 这是我目前的代码:

class story var text = "" var numberoflikes = 0 var user = Auth.auth().currentuser! iboulet weak var : likebutton : uibutton iboulet weak var: storylabel : uilabel var story: story! { didSet { storylabel.text = story.text likebutton.setTitle(" /("story.numberoflikes)", for: []}} } ibaction func likedidtouch: (_ sender: AnyObject) { story.like() llikebutton.settitle(" \(story.numberoflikes)", for: []}} }} extension story { func like() { if like() set user = false else set user = true numberoflikes += 1 ref.child("numberoflikes").setValue(numberoflikes } } 

为了将每个用户的喜好限制为一个,我需要更改什么?

我的数据库模型,我有:
“故事”>“文字”,“数字电影”

我真的很感激你能给我的任何帮助

我最近创建了一个类似的平台。 我所做的是将用户投票存储在我的数据库中。

投票

在每个用户的节点中,他们对每个post都有自己的投票值。 所以,假设你想拥有如下所示的高亮按钮。 您必须从树中获取该用户的postVotes节点,遍历postVotes对象并根据每个post的投票值分配高亮显示。

在此处输入图像描述

最后,你应该将你在firebase上保留的用户的旧投票与他的新投票进行比较。

 let incrementBy let userVote if (currentVote === newVote * -1) { incrementBy = newVote * 2 userVote = newVote } else if(currentVote === 0) { incrementBy = newVote userVote= newVote } else { incrementBy = newVote * -1 userVote= 0 } // update your totalvote value on your firebase by incrementBy // swap your firebase uservote value on that post with userVote 

有很多方法可以解决这个问题,但这里有两个。 无论哪种方式,从这个Firebase结构开始。

 posts some_post_id post: "I like pizza" votes uid_0: true uid_2: true uid_5: true 

1)通过检查他们的匿名用户ID (UID)是否已存在来查看投票用户是否已经投票

实质上,当用户投票支持post时,捕获他们的uid并将其写入具有真值的投票节点(如果它尚不存在)。

在写作之前,请检查他们是否已经投票

 let thisUid = Auth.auth().currentUser?.uid let postsRef = self.ref.child("posts") let refToCheck = postsRef.child("some_post_id").child("votes").child(thisUid!) refToCheck.observeSingleEvent(of: .value, with: { snapshot in if snapshot.exists() { print("you already voted for this post") } else { print("no uid found, adding a vote") refToCheck.setValue(true) } }) 

请注意,这需要错误检查但function正常。

2)使用Firebase规则允许只在写入节点内不存在uid(key)。 基本上,如果uid已经存在,它将拒绝写入)。 我更喜欢#1,但这是另一种选择。

如果您不熟悉规则,则有很多选项,因此请先查看“ Firebase规则指南” 。