Arkelyan Arkelyan - 1 month ago 12
iOS Question

How to query/check for specific key/value pair in FIrebase using Swift3

In my app I want to check if a specific order already exists. I'm struggling on how to do this type of query.

How can I check if a particular order exists in the child("orders")? For instance I want to query to see if order 2 exists

DB_name

--users

----UserID

------Orders

--------Order1

----------OrderItem1

----------OrderItem2

----------OrderItem3

--------Order2

----------OrderItem1

----------OrderItem2

----------OrderItem3

--------Order3

----------OrderItem1

----------OrderItem2

----------OrderItem3

Answer

You'll need three things:

First, a reference to that child. There are a couple ways to get one, but I find the following format easy to read:

FIRDatabase.database()
    .reference()
    .child("users")
    .child("userID")
    .child("Orders")
    .child("Order2")

Second, the value of that child in the form of a FIRDataSnapshot. We get values by observing "events" of type value. Check out observeSingleEventOfType:withBlock: for the simplest approach.

Third, evaluate the FIRDataSnapshot we get back from the observer to see what the value actually is. If you simply want to know whether it exists, the exists method is quite useful.

Putting it all together, we get the following:

FIRDatabase.database()
    .reference()
    .child("users")
    .child("userID")
    .child("Orders")
    .child("Order2")
    .observeSingleEvent(of: .value) { (snapshot) in
        print("Exists: \(snapshot.exists())")
    }
Comments