【问题标题】:Adding items to Firebase array in Swift without observing for array first在 Swift 中将项目添加到 Firebase 数组而不首先观察数组
【发布时间】:2016-05-25 11:23:23
【问题描述】:

目前我通过首先观察数组、附加我的新帖子,然后更新参考来向我的 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)

【问题讨论】:

    标签: ios swift firebase firebase-realtime-database


    【解决方案1】:

    通常最好避免在 Firebase 中使用数组,因为它们非常难以处理;单个元素不能直接访问,也不能更新——它们必须重写。

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

    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 询问如何将其写入 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
    

    【讨论】:

    • 感谢您的回复。上面我写的代码是用来存储我在User表中创建的新帖子的引用。你建议我怎么做?
    • @solistice 模式相同,只是posts节点的父节点是相关用户的UID。我在我的答案中添加了额外的代码 - 代码也可以缩短,但我做的“长手”确实证明了这一原则;它可以组合成一行,然后是 setValue 行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 2012-02-17
    • 1970-01-01
    • 2020-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多