目前,我通过首先观察数组,附加我的新帖子,然后更新引用来向我的 Firebase 数组添加一个新帖子:
REF_USER.child(UID).observeSingleEventOfType(.Value, withBlock: { snapshot in
if !snapshot.exists() {return}
if let dict = snapshot.value as? Dictionary<String, AnyObject>,
let posts = dict["posts" as? [String] {
posts.append(newPost)
REF_USER.child(UID + "/posts").setValue(posts)
}
}
有没有办法跳过观察步骤,并立即更新数组中的帖子?假设,类似:
REF_USER.child(UID + "/posts").addToArray(newPost)
在 Firebase 中避免使用数组通常是一个很好的做法,因为它们非常难以处理;各个元素无法直接访问,也无法更新——必须重写。
不确定为什么您要按照问题中概述的步骤添加新帖子,但这是另一个解决方案:
thisPostRef = postsRef.childByAutoId //create a new post node
thisPostRef.setValue("here's a new post") //store the post in it
Edit:
这将导致这样的结构
posts
post_id_0: "here's a new post"
post_id_1: "another post"
post_id_2: "cool post"
这种结构避免了数组的缺陷。
另一个编辑。 OP询问如何将其写入users/UID/posts节点
usersRef = rootRef.childByAppendingPath("users")
thisUserRef = usersRef.childByAppendingPath(the users uid)
thisUserPostRef = thisUserRef.childByAutoId //create a new post node
thisUserPostRef.setValue("here's a new post") //store the post in it
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)