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

目前,我通过观察数组,首先添加一个新的post到我的Firebase数组,附加我的新post,然后更新ref:

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

有没有办法跳过观察的步骤 ,并立即更新数组中的post? 假设,例如:

 REF_USER.child(UID + "/posts").addToArray(newPost) 

在Firebase中避免arrays是一个很好的做法,因为它们非常难以处理; 单个元素不能直接访问,也不能更新 – 必须重写。

不知道为什么你要通过你的问题中列出的步骤来添加一个新的职位,但这里有另一个解决scheme:

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

编辑:

这将导致这样的结构

 posts post_id_0: "here's a new post" post_id_1: "another post" post_id_2: "cool post" 

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

另一个编辑。 OP询问如何将其写入用户/ UID /post节点

 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