I have a dictionary in Firebase called peopleWhoLike
, the key is an auto-id and the value is the uid of the user who liked, I'm trying to loop through the peopleWhoLike
dictionary and find the entry with the current users uid as the value so that I can remove it, but the value is not being removed.
func removeLike(postID: String){
ref.child("posts").child(postID).observe(.value, with: { (snapshot) in
if let info = snapshot.value as? [String : AnyObject]{
if var peopleWhoLike = info["peopleWhoLike"] as? [String : String]{
print("peopleWhoLike - \(peopleWhoLike)")
for person in peopleWhoLike{
if person.value == FIRAuth.auth()!.currentUser!.uid{
peopleWhoLike.removeValue(forKey: person.key)
print("personkey - \(person.key)")
}
}
}
}
})
}
Both print statements print correctly, ie person.key
being the correct key
Any help would be much appreciated thanks!
you have only an snapshot (a copy) of the data there
to remove the value from the firebase database; try this:
//path should be like this (i guess):
let currentUserUid = FIRAuth.auth()!.currentUser!.uid
ref.child("posts")
.child(postId)
.child("peopleWhoLike")
.child(currentUserUid)
.removeValue()
or same:
let currentUserUid = FIRAuth.auth()!.currentUser!.uid
ref.child("posts/\(postId)/peopleWhoLike/\(currentUserUid)").removeValue()
UPDATE
you you like to remove the person key - then you can:
a) iterate over peopleWhoLike and find if it is the user ( but please put this let currentUserUid = FIRAuth.auth()!.currentUser!.uid
outside the loop!
//path should be like this (i guess):
let currentUserUid = FIRAuth.auth()!.currentUser!.uid
// loop and when match `person.value == currentUserUid` then:
ref.child("posts")
.child(postId)
.child("peopleWhoLike")
.child(person.key) //<-- change here
.removeValue()
b) you search in the query. and remove then the resulting node.
ref.child("posts")
.child(postId)
.child("peopleWhoLike")
.startAt(currentUserId)
.endAt(currentUserId)
. [...] do something
i dont know if you can direct call .removeValue()
at this point. but with a SingleEvent and an snapshot you can do snapshot.ref.removeValue()
- doublecheck before you delete. but since this results in a reference you should direct able to call .removeValue()
ref.child("posts")
.child(postId)
.child("peopleWhoLike")
.startAt(currentUserId)
.endAt(currentUserId)
.removeValue()
note: this search takes longer than a direct path
see here doc for query:
https://firebase.googleblog.com/2013/10/queries-part-1-common-sql-queries.html#byemail
https://firebase.google.com/docs/database/ios/read-and-write#delete_data
NOTE:
i would advice you to save it with the userUid
as key because you only need a onliner to delete (see my first codesnippet where you not need to get all data from peopleWhoLike
) and as value just 1 or you can save the current date (then you know when it was liked)