Firebase remove snapshot children swift

北战南征 提交于 2019-12-23 05:11:42

问题


I am using Firebase as my Database...

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().


回答1:


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!()
       }
   }
})



回答2:


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!




回答3:


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()

                 }
            }
          }
        }


来源:https://stackoverflow.com/questions/38997678/firebase-remove-snapshot-children-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!