I have just started on Firebase
.
Here is the JSON
on Firebase
:
{
"messages" : {
"-K2ib4H77rj0LYewF7dP" : {
"name" : "anonymous",
"text" : "Hello"
},
"-K2ib62mjHh34CAUbide" : {
"name" : "anonymous",
"text" : "I am fine"
},
"Test" : {
"name" : "test111",
"text" : "text22"
}
}
}
In Swift, I am observing when an item is added/removed on server, it should reflect in the app. Adding a record works fine. But for removing, I am not sure how to delete the item from the array based on index. Using indexOf
returns a address (I guess array won't remove the object without mapping).
This is the incorrect code I have tried and does not work :
_refHandle = self.ref.child("messages").observe(.childRemoved, with: { [weak self] (snapshot) -> Void in
guard let strongSelf = self else { return }
let values = snapshot.value as? NSDictionary
let indexToBeRemoved = strongSelf.messages.index(where: {
let valuesFilter = $0.value as? NSDictionary
valuesFilter!["name"] as! NSString === values!["name"] as! NSString
return true
})
print(indexToBeRemoved)
strongSelf.messages.remove(at: indexToBeRemoved!)
strongSelf.clientTable.deleteRows(at: [IndexPath(row: indexToBeRemoved!, section: 0)], with: .automatic)
})
indexToBeRemoved
comes out to be 0.
I also tried to simply remove the object using this answer but it returned an address.
Expected result :
Get the index of DataSnapshot object which is to be removed