Adding Firebase Post Overwrites All Other Posts Swift

ぃ、小莉子 提交于 2019-12-23 04:46:07

问题


I have written code that correctly writes a single post to my Firebase database. The issue is that when I add another post it overwrites the post that was there previously. How can I add the posts to the existing array without overwriting?

  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")

    }


回答1:


I was able to resolve the issue by making a minor change to how I was setting the value. It now looks like this:

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


来源:https://stackoverflow.com/questions/56808006/adding-firebase-post-overwrites-all-other-posts-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!