将项目添加到 Swift 中的 Firebase 数组而不先观察数组

leo*_*loo 5 ios firebase swift firebase-realtime-database

目前,我通过首先观察阵列,附加我的新帖子,然后更新参考来向我的 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)
   }
}
Run Code Online (Sandbox Code Playgroud)

有没有办法跳过观察步骤,并立即更新数组中的帖子?假设,类似于:

REF_USER.child(UID + "/posts").addToArray(newPost)
Run Code Online (Sandbox Code Playgroud)

Jay*_*Jay 4

在 Firebase 中避免使用数组通常是一个很好的做法,因为它们非常难以处理;各个元素无法直接访问,也无法更新——必须重写。

不确定为什么您要按照问题中概述的步骤添加新帖子,但这是另一个解决方案:

thisPostRef = postsRef.childByAutoId //create a new post node
thisPostRef.setValue("here's a new post") //store the post in it
Run Code Online (Sandbox Code Playgroud)

编辑:

这将导致这样的结构

posts
  post_id_0: "here's a new post"
  post_id_1: "another post"
  post_id_2: "cool post"
Run Code Online (Sandbox Code Playgroud)

这种结构避免了数组的缺陷。

另一个编辑。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
Run Code Online (Sandbox Code Playgroud)