问题
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