Kika_Fortez
Kika_Fortez

Reputation: 314

Firebase remove snapshot children swift

I am using Firebase as my Database... enter image description here

Then i want to delete the "codigo" key value. This is my if statement:

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


            for item in snapshot.children {

                if item.value["codigo"]as! String == barcodes[indexPath.row].code{
                    print("HERE")

                item.removeValue!()


                }


            }

but it crashes at item.removeValue().

Upvotes: 0

Views: 5006

Answers (3)

Kika_Fortez
Kika_Fortez

Reputation: 314

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!

Upvotes: 3

Dravidian
Dravidian

Reputation: 9955

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

        if let item = snapshot.value as? [String:AnyObject]{
          for each in item.1 as [String : AnyObject]{

           let barcodeKey = each.0
            if each.1["codigo"] as! String == barcodes[indexPath.row].code{

                  FIRDatabase.database().reference().child("barcodes").child(barcodeKey)child("codigo").removeValue()

                 }
            }
          }
        }

Upvotes: 0

Frank van Puffelen
Frank van Puffelen

Reputation: 600126

You cannot remove a snapshot. But you can get the reference that the snapshot comes from and remove that:

let profile = FIRDatabase.database().reference().child("barcodes")
profile.observeEventType(.Value, withBlock: { (snapshot) -> Void in
   for item in snapshot.children {
       if item.value["codigo"]as! String == barcodes[indexPath.row].code{
           print("HERE")
           item.ref.removeValue!()
       }
   }
})

Upvotes: 4

Related Questions