简体   繁体   English

在Swift中向Firebase数组添加项目而不首先观察数组

[英]Adding items to Firebase array in Swift without observing for array first

Currently I add a new post to my Firebase array by observing for the array first, appending my new post, and then updating the ref: 目前,我首先通过观察数组,附加新帖子,然后更新ref来向我的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)
   }
}

Is there a way to skip the step of observing , and straight away update posts in an array? 有没有办法跳过观察步骤 ,并立即更新数组中的帖子? Hypothetically, something like: 假设,像:

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

It's generally good practice to avoid array's in Firebase as they are super hard to deal with; 通常很好的做法是避免使用Firebase中的数组,因为它们非常难以处理; the individual elements cannot be accessed directly and they cannot be updated - they have to be re-written. 单个元素无法直接访问,无法更新 - 必须重新编写。

Not sure why you are going through the steps outlined in your question to add a new post but here's another solution: 不确定为什么要通过问题中列出的步骤添加新帖子,但这是另一种解决方案:

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

Edit: 编辑:

This will result in a structure like this 这将产生这样的结构

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

This structure avoids the pitfalls of arrays. 这种结构避免了数组的缺陷。

Another edit. 另一个编辑。 The OP asks how to write it to the users/UID/posts node 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM