【发布时间】: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