5

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)
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
leonardloo
  • 1,753
  • 3
  • 20
  • 31

1 Answers1

4

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
Jay
  • 34,438
  • 18
  • 52
  • 81
  • Thanks for the reply. The above code I wrote is to store the reference of the new post I created in the User table. How do you suggest I can do that? – leonardloo May 25 '16 at 15:51
  • @solistice It's the same pattern, just the parent node to the posts node is the UID of the user in question. I added additional code to my answer - the code could be shortened as well but I did it 'long hand' do demonstrate the principle; it could be combined into a single line and then the setValue line. – Jay May 25 '16 at 17:16