Search code examples
iosswiftfirebasefirebase-realtime-databaseobservers

How to observe the removal of a model from the Firebase Database?


I use Firebase Database, I have a list of cards, I need to monitor some cards if they are deleted. I tried to do this with ref.observe (.childRemoved), but this is not appropriate for my case, since some data can be deleted by the cardholder, and then this block will fire several times, I need to watch if the entire card was deleted. How can I do that?

My reference

    let ref = FIRDatabase.database().reference().child(MainGateways.cards.rawValue).child(card.id) 

My cards structure

"cards": {
   "-Khv9rUVwErNHBzXcruO": {
      "additionalInfo": {
          "note": ""
      },
      "dateProperties": {
          "day": "Flex",
          "isFlexDate": true,
          "isFlexTime": true,
          "iso8601": "",
          "time": ""
      },
      "interestedUsers": {
          "NfM26A2YcPUFz8rfYa23Kr3mjCO2": {
              "isApproved": false,
              "isNew": true,
              "isoDate": "2017-04-17T13:08:41+04:00",
              "userID": "NfM26A2YcPUFz8rfYa23Kr3mjCO2",
              "userItchableName": "Alexsander K."
          }
      },
      "isNewPendingRequest": true,
      "isPrivateStatus": false,
      "isTest": false,
      "ownerID": "1Cix149ThIOG1ULPVjyy0LyTxbe2",
      "peopleProperties": {
          "availableSeats": 1,
          "numberOfPeople": 1,
          "numberOfPeopleDescription": "1 person"
      },
      "title": "Genius Lounge and Sake Bar",
      "userName": "Tim C.",
      "version": 1
  },

I also tried to make such a link, but then this block works if any card was removed from the list.

    guard let ref = FIRDatabase.database().reference().child(MainGateways.cards.rawValue).child(card.id).parent else { return }

Solution

  • Look into Cloud Functions for Firebase. Using that, you can write JavaScript code that acts in response to database changes at the path you specify. This allows you to write logic independent of the client app to react to changes in the database.