添加Firebase帖子会覆盖所有其他帖子Swift

时间:2019-06-28 13:38:04

标签: swift firebase firebase-realtime-database

我写的代码正确地将单个帖子写到我的Firebase数据库中。问题是,当我添加另一个帖子时,它会覆盖之前的帖子。如何在不覆盖的情况下将帖子添加到现有数组?

  func postToFirebase(imgUrl: String) {
        let post: Dictionary<String, AnyObject> = [
            "caption": postDescription.text! as AnyObject,
            "imageUrl": imgUrl as AnyObject,
            "likes": 0 as AnyObject
        ]

        let firebasePost = DataService.ds.REF_POSTS.childByAutoId()
        firebasePost.setValue(post)
        let userPost = firebasePost.key

        print("Firebase Post: \(String(describing: firebasePost))")


        _ = Auth.auth().addStateDidChangeListener { (auth,user) in
            if let user = user {
                let userId = user.uid
                print("USER: \(String(describing: userId))")
                let newPost = DataService.ds.REF_USERS.child("\(userId)").child("posts")
                //print("NEW POST: \(newPost.child)")
                newPost.setValue([userPost : true])

            }
        }

        postDescription.text = ""
        imageSelected = false
        newPostImage.image = UIImage(named: "icons8-camera-100")

    }

enter image description here

1 个答案:

答案 0 :(得分:1)

我可以通过稍微更改设置值的方式来解决此问题。现在看起来像这样:

let newPost = DataService.ds.REF_USERS.child("\(userId)").child("posts").child(userPost!)
newPost.setValue(true)