Search code examples
firebaseswift3firebase-realtime-databaseios10

How to trigger a notification in Firebase with a condition in Swift?


I have 2 apps, rider and driver (in the same project in Firebase). If setting up Push Notifications in Firebase, how can I set a condition? For example, if the rider requests a ride, an alert advises the driver to accept or cancel. If the driver accepts the request, a child is added to the database like ref = FIRDatabase.database().reference():

ref.child("riders").child("RydeAccepted").child(usersname).setValue(data)

How would I set it up so that when this happens, a notification is sent to the rider app stating the request has been added or removed?


Solution

  • This possible structure may help and simplify the structure in the question

    drivers
       -Yuiu9jasjdasd
          name: "driver 1"
       -Huuajwiojiejw
          name: "driver 2"
    
    riders
       -Yij99js9skos
          name: "rider 1"
       -Y090jssiisss
          name: "rider 2"
    
    
    rider_driver_requests
       -Yuljai8jsid99jsds
          requested_by_rider: "-Yij99js9skos"
          for_driver: "-Yuiu9jasjdasd"
          driver_response: "Pending"
       -Y99mskksmnjndjnsj
          requested_by_rider: "-Y090jssiisss"
          for_driver: "-Huuajwiojiejw"
          driver_response: "Accepted"
    

    In the above structure, rider_1 has requested a ride from driver_1, but driver_1 has not responded yet (when they do, the driver_response will change from pending to declined or accepted).

    rider_2 has requested a ride from driver_2 and driver two has already accepted.

    Both riders and drivers are observing the rider_driver_requests node and will each be notified of additions, changes or remove events in that node.

    Before you say 'that node is going to get huge!', the reason I structured it like this is that in the future, a rider may not be requesting a specific driver - they may be requesting drivers in an area.

    So all drivers within that area would want to be notified of the request so they would all be observing that node and comparing their current position (long, lat for example) with the position of the rider who requested the ride.