Adding items to Firebase array in Swift without observing for array first

前端 未结 1 1623
旧巷少年郎
旧巷少年郎 2021-01-19 10:24

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).obser         


        
1条回答
  •  别那么骄傲
    2021-01-19 10:59

    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
    

    0 讨论(0)
提交回复
热议问题