2016-08-14 140 views
1

在我火力數據庫的數據庫數據的故障設定值目前保存在這種方式:斯威夫特:使用火力地堡

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

但正在以下錯誤在編輯器:

errors

+1

使用「分數」而不是「messages.score」。 –

+0

Alsi更好地在交易中這樣做,以避免與多位作家同時嘗試設置分數的競爭條件。 –

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

運行時沒有錯誤!除非我認爲這是一個無限循環哈哈,除非我退出應用程序,否則在點擊按鈕之後點數永遠不會加起來 –

+0

讓我們[在聊天中繼續討論](http://chat.stackoverflow.com/rooms/) 120943 /討論-之間-德拉威和 - 阿哈德-警長)。 – Dravidian

相關問題