如何限制Firebase的星数? [英] how to limit star-count on Firebase?

查看:42
本文介绍了如何限制Firebase的星数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个具有通用供稿的匿名社交媒体应用程序.我想将帖子的喜欢数限制为每个用户一个,但是我不知道如何限制每个用户的喜欢数.这是我当前的代码:

I am writing an anonymous social media app with a universal feed. I want to limit the likes on a post to one per user, but I don't know how to limit the likes of each user. This is my current code:

    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
}
}

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

What do I need to change in order to limit the likes of each user to one?

我的数据库模型,我有:
"stories">文本",喜欢数目"

my database model, i have:
"stories"> "text", "numberoflikes"

非常感谢您可以为此提供的任何帮助

I would really appreciate any help you can give me on this

推荐答案

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

There's many way to approach this but here are two. Either way, start with this Firebase structure.

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

1)检查有投票权的用户是否已经投票,查看他们的匿名用户ID (UID)已存在

1) See if the voting user has already voted by checking to see if their Anonymous User Id (UID) already exists

本质上,当用户对帖子进行投票时,请捕获其uid,并将其写入具有正确值(如果尚不存在)的votes节点.

In essence, when a user votes for a post, capture their uid and write it to the votes node with a true value if it doesn't already exist.

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

Before writing, check to see if they already voted

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)
    }
})

请注意,这需要进行错误检查,但可以正常工作.

note this needs error checking but is functional.

2)使用Firebase规则允许仅在表决节点中不存在uid(密钥)的写入操作.本质上,如果uid已经存在,它将拒绝写入.我更喜欢#1,但这是另一种选择.

2) Use Firebase Rules to allow a write only the uid (key) doesn't already exist within the votes node. Essentially it will deny the write if the uid already exists). I like #1 better but that is an alternative.

如果您不熟悉规则,则有很多选择,因此请查看 Firebase规则指南优先.

If you are not familiar with rules there are a lot of options so take a look a the Firebase Rules Guide first.

这篇关于如何限制Firebase的星数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆