我的firebase数据库中的数据库当前以这种方式保存:
{
"messages" : {
"-KOxK41dRvVOjXq0CgZ0" : {
"date" : "2016-08-12 05:58:12 +0000",
"location" : "Seattle, WA",
"score" : 0,
"senderId" : "LylxZpPcmQgSFLGmpemKJDHvqQX2",
"text" : "Yo"
}
}
}
我正在尝试为用户实施按下按钮的方式,分数会上升。我想我可以使用Firebase的setValue
代码只为每条消息的分数值添加一个代码。
以下是我用于此的代码:
super.collectionView(collectionView, didTapMessageBubbleAtIndexPath: indexPath)
let data = self.messages[indexPath.item]
print("They tapped: " + (data.text) + "- " + (data.senderDisplayName))
data.score += 1
messageRef.child("messages.score").setValue(data.score)
print(data.score)
但是我收到以下错误:
*** Terminating app due to uncaught exception 'InvalidPathValidation', reason: '(child:) Must be a non-empty string and not contain '.' '#' '$' '[' or ']''
我假设这是因为我有“messages.score”作为我的孩子,当我应该把其他东西放在那里。我查看了Firebase文档,但无法弄清楚要放什么。
有人知道如何解决我的问题吗?
谢谢!
修改
我尝试了这段代码:
var rootRef : FIRDatabaseReference = FIRDatabase.database().reference()
let senderID = data.senderId
rootRef.child("messages").observeEventType(.Value, withBlock: { (snap) in
if snap.exists(){
for each in snap as! [String:AnyObject]{
let postID = each.key as! String
if let messagesDict = each.value as! [String:AnyObject]{
if senderID == messageDict["senderId"]{
//Checking for the senderID of the user so that you only increment the score of that particular message post
let userScore = messageDict["score"] as! Int
userScore = userScore + 1
rootRef.child("messages").child(postID).child("score").setValue(userScore)
}
}
}
}
})
但是我在编辑器中遇到以下错误:
答案 0 :(得分:0)
使用: -
let rootRef : FIRDatabaseReference = FIRDatabase.database().reference()
var senderID = FIRAuth.auth()!.currentUser!.uid
rootRef.child("messages").observeEventType(.Value, withBlock: { (snap) in
if snap.exists(){
if let messagesDict = snap.value! as? [String : AnyObject]
{
for each in messagesDict as [String : AnyObject]{
let postID = each.0
if let messageDict = each.1 as? [String:AnyObject]{
if senderID == messageDict["senderId"] as! String{
//Checking for the senderID of the user so that you only increment the score of that particular message post
var userScore = messageDict["score"] as! Int
userScore = userScore + 1
rootRef.child("messages").child(postID).child("score").setValue(userScore)
}
}
}
}
}
})