Firebase Remove Snapshot Children Swift

Firebase remove snapshot children swift

Hello there i finally find a solution:

let profile = FIRDatabase.database().reference().child("barcodes")
profile.observeEventType(.Value, withBlock: { (snapshot) -> Void in

if snapshot.exists(){

for item in snapshot.children {
if item.value["codigo"]as! String == barcodes[index].code{

item.ref.child(item.key!).parent?.removeValue()

}
}
}
})

Thanks a lot!

how to delete child record from firebase in swift?

https://firebase.google.com/docs/database/ios/read-and-write

"The simplest way to delete data is to call removeValue on a reference to the location of that data."

Firebase - Swift - Delete a child UID from a snapshot

I think you need to reach the child that you want to remove using the following code and then remove it.

Edit1:

Since inside staffUsers we have keys inside which studentSession1List is present inside which the value (studentUID) is present that we want to remove, so inside your already written code I have added the new code, please check

let dataref = Database.database().reference()

dataref.child("staffUsers").queryOrdered(byChild: "studentSession1List").observe(.value, with: { (snapshot) in

for snap in snapshot.children {
guard let studentUID = Auth.auth().currentUser?.uid else { return }

let snapDataSnapshot = snap as! DataSnapshot

var snapValues = snapDataSnapshot.value as? [String: AnyObject]

if var snapWithReg = snapValues?["studentSession1List"] as? [String: Bool] {

//Added code here
dataref.child("staffUsers").child(snapDataSnapshot.key).child("studentSession1List").child(studentUID).removeValue(completionBlock: { (error, ref) in
if error != nil {
print("Error: \(error)")
return
}
print("Removed successfully")

})

}

}

}) { (error) in
print(error.localizedDescription)

}

Edit2:

To delete the code once , we can use observeSingleEvent

observeSingleEvent(of: .value, with: { (snapshot) in

}, withCancel: nil)

How to remove a firebase child node from a specific UICollectionViewCell - Swift

This is how I managed to solve the question I had asked.... hope it helps :)

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: PostsCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "postsCell", for: indexPath) as! PostsCollectionViewCell

cell.set(post: postsuser[indexPath.row])
cell.deletePostButton.addTarget(self, action: #selector(buttonAction(sender:)), for: .touchUpInside)
cell.deletePostButton.tag = indexPath.row
return cell
}

@objc func buttonAction(sender: UIButton) {

ProgressHUD.show("Un momento", interaction: true)
let uid = Auth.auth().currentUser?.uid
Database.database().reference().child("posts").queryOrdered(byChild: "author/userid").queryEqual(toValue: uid!).observe(.value) { (snapshot) in
if let posts = snapshot.value as? [String: AnyObject] {
if let posts = snapshot.value as? [String: AnyObject] {
for (key, postReference) in posts {
if let post = postReference as? [String: Any], let timestamp = post["timestamp"] as? TimeInterval, timestamp == self.postsuser[sender.tag].timestampDouble {

Database.database().reference().child("posts").child(key).removeValue(completionBlock: { (error, _) in
DispatchQueue.main.async {
ProgressHUD.showSuccess("Tu imagen ha sido borrada...")
self.postsuser.remove(at: sender.tag)
self.postsCollectionView.reloadData()
self.refresher.endRefreshing()
}
})
}
}
}
}
}
}

Remove an entire child from Firebase using Swift

I understand you don't have access to the key of the node you want do delete. Is that right? Why not? If you use the "observe()" function on a FIRDatabaseQuery object, each returned object should come with a key and a value.

Having a key it is easy to remove a node, as stated in the Firebase official guides.

From the linked guide,

Delete data

The simplest way to delete data is to call removeValue on a reference
to the location of that data.

You can also delete by specifying nil as the value for another write
operation such as setValue or updateChildValues. You can use this
technique with updateChildValues to delete multiple children in a
single API call.

So, you could try:

FirebaseDatabase.Database.database().reference(withPath: "Forum").child(key).removeValue()

or

FirebaseDatabase.Database.database().reference(withPath: "Forum").child(key).setValue(nil)

If you can't get the key in any way, what you said about "iterating" through the children of the node could be done by using a query. Here's some example code, supposing you want all forum posts by Jonahelbaz:

return FirebaseDatabase.Database.database().reference(withPath: "Forum").queryOrdered(byChild: "username").queryEqual(toValue: "Jonahelbaz").observe(.value, with: { (snapshot) in
if let forumPosts = snapshot.value as? [String: [String: AnyObject]] {
for (key, _) in forumPosts {
FirebaseDatabase.Database.database().reference(withPath: "Forum").child(key).removeValue()
}
}
})

Here you create a sorted query using as reference "username" then you ask only for the forum posts where "username" are equal to Johanelbaz. You know the returned snapshot is an Array, so now you iterate through the array and use the keys for deleting the nodes.

This way of deleting isn't very good because you might get several posts with the same username and would delete them all. The ideal case would be to obtain the exact key of the forum post you want to delete.



Related Topics



Leave a reply



Submit