【问题标题】:Finding it difficult to update value in firebase in Swift发现很难在 Swift 中更新 firebase 中的值
【发布时间】:2017-07-27 07:48:13
【问题描述】:

我的 Firebase 数据库如下所示

这里我有一个字段名称user_post。然后我使用 childByAutoId() 添加一个新帖子。然后在里面我根据 postId 插入帖子。现在我想更新 like 并添加新字段 peopleWhoLike。谁能告诉我如何插入更新任何特定帖子的值。顺序是 user_post > childByAutoId() > postId

这是我的代码:

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

【问题讨论】:

  • 添加了更详细的答案。

标签: ios firebase swift3 firebase-realtime-database


【解决方案1】:

例如,您可以通过以下方式一次更新一个值,

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

我所做的是写下我的帖子的关键。创建帖子时,将 childByAutoID 添加到帖子数据中,以便我以后可以引用它。我会将它称为“键”,值将是 childByAutoId 字符串。一旦我有了那个键,我就可以像这样添加一个喜欢,

点击

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

当用户喜欢或不喜欢它时,您可以在根节点创建一个名为“Likes”的新节点,它会获取 postKey 并在 Likes 节点下创建一个子节点,然后添加 userId。当帖子加载时,您将进入 Likes 节点并匹配帖子,然后检查用户是否喜欢。

这里我有用户关注列表,但它可能与点赞相同。当用户保存帖子时在我的应用程序中。我在监视列表下记录了 userId,在 userId 中是保存的 postId。这可能类似于喜欢。然后我只是比较一下,看看是否匹配。

【讨论】:

    猜你喜欢
    • 2016-02-04
    • 1970-01-01
    • 1970-01-01
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 2016-08-25
    • 2015-07-29
    • 2017-04-14
    相关资源
    最近更新 更多