Using UpdateChildValues to delete from Firebase

前端 未结 2 916
北海茫月
北海茫月 2020-12-01 23:53

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

The Firebase docs state:

\"The simplest way to dele

相关标签:
2条回答
  • 2020-12-02 00:16

    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"
    
    0 讨论(0)
  • 2020-12-02 00:21

    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,...]
    
    0 讨论(0)
提交回复
热议问题