在Swift中将项目添加到Firebase数组,而不先观察阵列 [英] Adding items to Firebase array in Swift without observing for array first
问题描述
目前,我通过观察数组,首先添加一个新的帖子到我的Firebase数组,然后添加新的帖子,然后更新ref:
REF_USER.child(UID).observeSingleEventOfType(.Value,withBlock:{snapshot in
if!snapshot.exists(){return}
如果让dict = snapshot.value as?Dictionary< ; String,AnyObject> ;,
let posts = dict [postsas?[String] {
posts.append(newPost)
REF_USER.child(UID +/ posts)。 setValue(posts)
}
}
有没有办法跳过观察的步骤,并立即更新数组中的帖子?假设是这样的:
REF_USER .child(UID +/posts\").addToArray(newPost)
在Firebase中避免使用数组是非常好的做法,因为它们非常难以处理;单个元素不能直接访问,而且可以不更新 - 他们必须重写。
不知道为什么你要通过问题中列出的步骤来添加一个新的职位,但这里有另一个解决方案:
thisPostRef = postsRef.childByAutoId //创建一个新的帖子节点
thisPostRef.setValue(这是一个新帖子)//将帖子存入其中
编辑:
这会产生这样的结构
文章
post_id_0:这是新文章
post_id_1:另一篇文章
post_id_2:cool post
这个结构避免了数组的缺陷。
$ b
另一个编辑。 OP询问如何将其写入用户/ UID /帖子节点
$ $ $ $ $ c $ usersRef = rootRef.childByAppendingPath(users)
thisUserRef = usersRef.childByAppendingPath(users uid)
thisUserPostRef = thisUserRef.childByAutoId //创建一个新的帖子节点
thisUserPostRef.setValue(这是一个新帖子)//将帖子存入它
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_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; 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
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
这篇关于在Swift中将项目添加到Firebase数组,而不先观察阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!