Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using UpdateChildValues to delete from Firebase

I am trying to delete data from several locations in the Firebase database simultaneously.

The Firebase docs state:

"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."

My code is

let childUpdates = [path1 : nil,
                    path2 : nil,
                    path3 : nil,
                    path4 : nil]

    ref.updateChildValues(childUpdates)

All four paths are strings, but I get an error:

"Type of expression is ambiguous without more context."

I'd assume this occurs because of the nil values, since if I replace nil with anything else (such as an Int) the error disappears.

What is the correct way to use updateChildValues to delete data from Firebase? We want it to work in a similar way to the removeValue() function in Firebase. The reason we would prefer to do this is because it can remove from multiple places in one call.

like image 840
Olivia Watkins Avatar asked Jul 19 '16 14:07

Olivia Watkins


2 Answers

So the issue here is that

ref.updateChildValues(childUpdates)

requires a [String: AnyObject!] parameter to updateChildValues, and AnyObject! cannot be a nil (i.e. you can't use AnyObject? which is an optional that could be nil)

However, you can do this

let childUpdates = [path1 : NSNull(),
                    path2 : NSNull(),
                    path3 : NSNull(),
                    path4 : NSNull()]

Because AnyObject! is now an NSNull() object (not nil), and Firebase knows that NSNull is a nil value.

Edit

You can expand on this to also do multi-location updates. Suppose you have a structure

items
   item_0
      item_name: "some item 0"
   item_1
      item_name: "some item 1"

and you want update both item names. Here's the swift code.

func updateMultipleValues() {
    let path0 = "items/item_0/item_name"
    let path1 = "items/item_1/item_name"

    let childUpdates = [ path0: "Hello",
                         path1: "World"
    ]

    self.ref.updateChildValues(childUpdates) //self.ref points to my firebase
}

and the result is

items
   item_0
      item_name: "Hello"
   item_1
      item_name: "World"
like image 180
Jay Avatar answered Oct 23 '22 12:10

Jay


I think this error is coming from the first line you've provided. You need to specify the type of dictionary. So change it to

let childUpdates: [String : AnyObject?] = [path1: nil, path2: nil,...]
like image 1
rigdonmr Avatar answered Oct 23 '22 13:10

rigdonmr