Ios 更新Firestore的计数器

Ios 更新Firestore的计数器,ios,swift,firebase,google-cloud-firestore,Ios,Swift,Firebase,Google Cloud Firestore,我想有一个计数器,每次我点击按钮都计数 func configureButton() -> UIButton{ button.setTitle("drink", for: .normal) button.setImage(#imageLiteral(resourceName: "beer-2288121_640").withRenderingMode(.alwaysOriginal), for: .normal) butto

我想有一个计数器,每次我点击按钮都计数

 func configureButton() -> UIButton{
    button.setTitle("drink", for: .normal)
    button.setImage(#imageLiteral(resourceName: "beer-2288121_640").withRenderingMode(.alwaysOriginal), for: .normal)
    button.addTarget(self, action: #selector(handleDrinkButton), for: .touchUpInside)
    button.backgroundColor = .black
    button.imageView?.contentMode = .scaleAspectFill
    
    return button
}
因此,我有以下代码来创建按钮

 func configureButton() -> UIButton{
    button.setTitle("drink", for: .normal)
    button.setImage(#imageLiteral(resourceName: "beer-2288121_640").withRenderingMode(.alwaysOriginal), for: .normal)
    button.addTarget(self, action: #selector(handleDrinkButton), for: .touchUpInside)
    button.backgroundColor = .black
    button.imageView?.contentMode = .scaleAspectFill
    
    return button
}
我还有一个计数器的公共变量

var beer: Int?
然后我想获取数据并将其推送到Firebase

  @objc func handleDrinkButton() {
    
   var db = Firestore.firestore()
   
    let userID = Auth.auth().currentUser?.uid
   
    self.beer =  db.collection("users").document(userID!).collection("beer") as! Int
      
        self.beer! += 1
        
        Firestore.firestore().collection("users").document(userID!).updateData(["beer": self.beer])

      // ...
      }){ (error) in
        print(error.localizedDescription)
    }
}

但数据没有改变


我不知道我是否将数字增加为false或以错误的方式读取和写入数据。

您的集合中的
beer
不是集合,而是文档中的一个字段

如果要增加该字段的值,Firestore有一个内置的
increment
操作,使此操作更加容易:

db.collection("users").document(userID!).updateData([
    "beer": FieldValue.increment(Int64(1))
])
另见:

  • 有关的文档

您的代码正在从实时数据库读取,然后写入Cloud Firestore。这是故意的吗?谢谢,我已经编辑了FireStore的评论,但我认为将用户数据指定为整数是错误的。我收到以下错误消息:无法将“CollectionReference”类型的值分配给“Int”类型,可能类似于self.beer=dbRef.collection(“beer”)之类的值?Int??0自助啤酒!+=嗨,马克。你对这件事有进一步的了解吗?我试图在下面给出一个答案。你有机会阅读并尝试一下吗?如果我的答案有用,请单击向上投票按钮(▲) 在它的左边(您可能还没有足够的声誉)。如果它回答了您的问题,请单击复选标记(✓) 接受它。这样别人就会知道你已经得到了(足够的)帮助。也请参见