2
votes

I want to notify users that are in the same "room" for changes. The scenario: I have anonymously devices with an id saved with an name. I have rooms with an unique id and name. And I have the link between them based on the device id and room id.

It looks like this:

enter image description here

Every device in the devices rooms "table" linked under the same key should be notified. When data changes under that key. But now the part what I don't get.

I want to get the device name of each device under the devices rooms key. And yes I want to get an update as well when the name changes. How can I do this with the authorization etc?

I have this basic code right now to write all this data to the database:

var ref: DatabaseReference! = Database.database().reference()
     ref.child("devices").child(user!.uid).child("device_name").setValue("iPhone test")

let newRef = ref.child("rooms").childByAutoId()
newRef.child("name").setValue("Room test")                                   
                            ref.child("devicesrooms").child(newRef.key).child(user!.uid).setValue(true)

let ev = ref.child("devicesrooms").child(newRef.key)

ev.observeSingleEvent(of: .childAdded, with: { (DataSnapshot) in
    print("changed")
})
1

1 Answers

3
votes

If you want to know when the name changes you need to use observe and not observeSingleEvent.

I think you need something like that :

var deviceNames = [String: String]()
var deviceHandles = [String: UInt]()

// Listen for added devices
ev.observe(.childAdded, with: { (snapshot) -> Void in
    // Retrieve device key
    let deviceKey = snapshot.key

    // Add observer on device
    var handle: UInt = 0

    handle = ref.child("devices").child(deviceKey).observe(.value, with: { (snapshot) in
        let value = snapshot.value as? NSDictionary
        let deviceName = value?["device_name"] as? String ?? ""

        // Update or Add deviceName and handle in your dictionary
        deviceNames[deviceKey] = deviceName
        deviceHandles[deviceKey] = handle
    })
})

// Listen for removed devices
ev.observe(.childRemoved, with: { (snapshot) -> Void in
    let deviceKey = snapshot.key

    // Remove deviceName from your dictionary
    deviceNames[deviceKey] = nil

    // Retrieve handle from your dictionary
    if let handle = deviceHandles[deviceKey] {
        // Remove observer on device
        ref.child("devices").child(deviceKey).removeObserverWithHandle(handle)
    }

    // Remove handle from your dictionary
    deviceHandles[deviceKey] = nil
})

Here the Firebase Realtime Database documentation.