我编写的代码正确地将一篇文章写到了我的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")

    }

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

最佳答案

我可以通过对设置值的方式做一点小小的更改来解决这个问题。现在看起来是这样的:

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

10-06 13:06
查看更多