Gaurav Wadhwani Gaurav Wadhwani - 2 months ago 29
Swift Question

Working with Firebase and Date Filters

I have a hotel reservation app that shows a swipe-able calendar to the user. Now the end goal is to provide a calendar like interface with small dots below each date that is reserved. For now, I am just trying to print on the console all reservations between start date and end date (where start and end dates are start and end of months respectively).

However, I am unable to get this to work with Firebase. Here's how the data is on Firebase at the moment:

{
"reservations" : {
"-KSgRjwpssoZJWjV9ScM" : {
"checkin" : 1474950600,
"checkout" : 1475116200,
"customer" : "-KMVMMudWJlFeiimtgJl"
}
}
}


And here's my Swift code to retrieve data:

private var ref: FIRDatabaseReference!

// viewdidload:
ref = FIRDatabase.database().reference()
ref.keepSynced(true)

// logic to fetch data
DispatchQueue.global().async {

// Background Processing
// Check Firebase for events between startdate and enddate
print("Fetching Reservations")
print(startDate.timeIntervalSince1970)
print(endDate.timeIntervalSince1970)


self.ref.child("reservations").queryStarting(atValue: startDate.timeIntervalSince1970, childKey: "checkin").observe(.childAdded, with: { (snapshot) -> Void in

print("Data Retrv.\n")
print(snapshot)

})
}


Here's what gets printed onto the console right now:

Fetching Reservations
1469989800.0
1472581800.0
Fetching Reservations
1472668200.0
1475173800.0


As its clearly visible that the data falls within the second range but I still can't get it to show up.

What may be wrong here? Thanks.

Answer

I'v tried with this code and it worked:

let ref = FIRDatabase.database().reference()
let refReservations = ref.child("reservations")

let startDate: Double = 1472668200.0

refReservations
  .queryOrdered(byChild: "checkin")
  .queryStarting(atValue: startDate)
  .observeSingleEvent(of: .value) { (snap: FIRDataSnapshot) in
    print(snap.value)
  }

The difference between your code and mine is I call one query more:

.queryOrdered(byChild: "checkin")
.queryStarting(atValue: startDate)

yours:

.queryStarting(atValue: startDate, childKey: "checkin")