Firebase GeoFire with Swift Tutorial

This tutorial assumes that you have a Firebase project set up and ready to go and are looking to incorporate GeoFire into it. There is a guide on getting started with Firebase, references to these two posts:

Installing with CocoaPods

Add the GeoFire library to your project pod file and run pod install:

Fixing FirebaseDatabase/FIRDatabase.h not found Error

If you open your project (of course the xcworkspace file now we’re dealing with a cocoapods project), in a view controller, import the required libraries:

Try and build your project. You may have a compile error saying “FirebaseDatabase/FIRDatabase.h not found”. This is because the Firebase Database framework isn’t visible to the GeoFire framework, and unsurprisingly the latter needs to know about the former.

To fix this error go and check the Target Membership for Geofire in the FirebaseDatabase.framework target:

Try rebuilding your project, and it should build successfully.

Adding Location Data For GeoFire

In this example we’ll suppose we’re tracking locations of users, of course this could be anything that your app requires that has coordinates (restaurants for example). A great thing about the GeoFire library is that it doesn’t really require much in the way of restructuring your data. GeoFire requires that you add a new node to your database to store the location related data of things. In this example it would make sense to do this at a new node in the root of the database called ‘user_locations’:

This ‘GeoFire’ object is how we’ll update location data for a given key and also how we’ll later query for nearby data.

To set a location for an object you call the setLocation method. For this example, lets suppose we’re responding to a CLLocationManager informing us that a users location has changed:

Here we get the last (the latest) CLLocation object from the array. We then set that location for the currently logged in user.

Query For Nearby Locations

Once we have location data in our database we’ll likely want to start querying our database for nearby data. This is done with the same GeoFire database reference.

There are a few ways you can query your data, the most basic is with a location and a radius. You’ll need a CLLocation object, this is the centre location, and a radius  from this point to search. Assuming we have our users location saved as a property of the view controller, our query might look like this:

We then set up a listener on this object. This should feel familiar to how we observe regular Firebase references:

This completion block will be called every time a user enters our search radius. This is because we passed in the ‘keyEntered’ as our event type. We can also pass in key ‘keyExited’ or keyMoved as our event type. The completion handler receives two values, a key (String) and a location (CLLocation). The key value should most likely be a reference to a child at another node in the database.