2017-03-07 44 views
1

更新火力值我的火力地堡數據庫看起來像這樣發現很難在斯威夫特

enter image description here

這裏我有一個字段名user_post。然後我使用childByAutoId()添加一個新帖子。然後在裏面,我插入帖子根據postId。現在我想更新,如,並添加新字段peopleWhoLike。有誰可以告訴我如何插入更新任何特定職位的值。順序是 user_post>childByAutoId()>帖子ID

這裏是我的代碼:

let keyToPost = ref.child("user_post").childByAutoId().key 

ref.child("user_post").queryOrdered(byChild: self.postID).observeSingleEvent(of: .value, with: { (snapshot) in 

     if (snapshot.value as? [String : AnyObject]) != nil { 

      let updateLikes: [String : Any] = ["peopleWhoLike/\(keyToPost)" : FIRAuth.auth()!.currentUser!.uid] 

      ref.child("user_post").child(self.postID).updateChildValues(updateLikes, withCompletionBlock: { (error, reff) in 

       if error == nil { 
        ref.child("user_post").child(self.postID).observeSingleEvent(of: .value, with: { (snap) in 
         if let properties = snap.value as? [String : AnyObject] { 
          if let likes = properties["peopleWhoLike"] as? [String : AnyObject] { 
           let count = likes.count 

           let update = ["Like" : count] 
           ref.child("user_post").child(self.postID).updateChildValues(update) 

           self.likeBtn.isHidden = true 
           self.unlikeBtn.isHidden = false 
           self.likeBtn.isEnabled = true 
          } 
         } 
        }) 
       } 
      }) 

     }//xxx 


    }) 

    ref.removeAllObservers() 
+0

添加了更詳細的答案。 – Ro4ch

回答

2

這裏是你如何能在一個時間,例如更新一個值,

let ref : FIRDatabaseReference! 
    ref = FIRDatabase.database().reference() 
    ref.child("yourNode").child("subNode").updateChildValues(["yourKey": yourValue]) 

我所做的是寫我的帖子的關鍵。創建帖子後,取出childByAutoID並將其添加到帖子數據中,以便稍後參考。我會將它引用爲「key」,值將是childByAutoId字符串。有一次,我那個鍵我將能夠加入像,像這樣,

上點擊

ref.child("yourNode").child(postKey).updateChildValues(["key": yourValue]) 

你可以做的稱爲根的新節點「喜歡」只要用戶喜歡或unlikes它將採用postKey並在Likes節點下創建一個子節點,然後添加userId。當帖子加載時,你會進入Likes節點並匹配帖子,然後檢查用戶是否喜歡。

likes example

這裏我有用戶監視列表,但它可能是一樣的喜歡。在我的應用程序中,當用戶保存帖子時。我在watchlist中記錄userId,userId是保存的postId。這可能類似於喜歡。然後我只是比較一下,看看是否有匹配。