• Stars
    star
    440
  • Rank 99,050 (Top 2 %)
  • Language
    Objective-C
  • License
    MIT License
  • Created over 10 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

GeoFire for Objective-C - Realtime location queries with Firebase

GeoFire for iOS — Realtime location queries with Firebase

GeoFire is an open-source library for iOS that allows you to store and query a set of keys based on their geographic location.

At its heart, GeoFire simply stores locations with string keys. Its main benefit however, is the possibility of querying keys within a given geographic area - all in realtime.

GeoFire uses the Firebase database for data storage, allowing query results to be updated in realtime as they change. GeoFire selectively loads only the data near certain locations, keeping your applications light and responsive, even with extremely large datasets.

A compatible GeoFire client is also available for Java and JavaScript.

Integrating GeoFire with your data

GeoFire is designed as a lightweight add-on to Firebase. However, to keep things simple, GeoFire stores data in its own format and its own location within your Firebase database. This allows your existing data format and security rules to remain unchanged and for you to add GeoFire as an easy solution for geo queries without modifying your existing data.

Example Usage

Assume you are building an app to rate bars and you store all information for a bar, e.g. name, business hours and price range, at /bars/<bar-id>. Later, you want to add the possibility for users to search for bars in their vicinity. This is where GeoFire comes in. You can store the location for each bar using GeoFire, using the bar IDs as GeoFire keys. GeoFire then allows you to easily query which bar IDs (the keys) are nearby. To display any additional information about the bars, you can load the information for each bar returned by the query at /bars/<bar-id>.

Upgrading GeoFire

Upgrading from Geofire 1.x to 2.x

With the expansion of Firebase at Google I/O 2016 and onwards, we've added a number of new features to Firebase, and have changed initialization to incorporate them more easily. See our setup instructions for more info on installing and initializing the Firebase SDK.

Upgrading from GeoFire 1.0.x to 1.1.x

With the release of GeoFire for iOS 1.1.0, this library now uses the new query functionality found in Firebase 2.0.0. As a result, you will need to upgrade to Firebase 2.x.x and add a new .indexOn rule to your Security and Firebase Rules to get the best performance. You can view the updated rules here and read our docs for more information about indexing your data.

Downloading GeoFire for iOS

If you're using CocoaPods, add the following to your Podfile:

pod 'GeoFire', '~> 4.0'

Using GeoFire with Swift

GeoFire supports Swift out of the box! In order to use GeoFire and Swift from CocoaPods, add the use_frameworks! line to your Podfile, like so:

use_frameworks!

pod 'GeoFire', '~> 4.0'

Getting Started with Firebase

GeoFire uses Firebase Realtime Database to store location data. You can sign up here for a free account.

GeoFire for iOS Quickstart

See the examples/SFVehicles folder for a working example of a project using GeoFire via CocoaPods.

GeoFire

A GeoFire object is used to read and write geo location data to your Firebase database and to create queries. To create a new GeoFire instance you need to attach it to a Firebase database reference:

Objective-C
FIRDatabaseRef *geofireRef = [[FIRDatabase database] reference];
GeoFire *geoFire = [[GeoFire alloc] initWithFirebaseRef:geofireRef];
Swift
let geofireRef = Database.database().reference()
let geoFire = GeoFire(firebaseRef: geofireRef)

Note that you can point your reference to anywhere in your Firebase database, but don't forget to set up security rules for GeoFire.

Setting location data

In GeoFire you can set and query locations by string keys. To set a location for a key simply call the setLocation:forKey method:

Objective-C
[geoFire setLocation:[[CLLocation alloc] initWithLatitude:37.7853889 longitude:-122.4056973]
              forKey:@"firebase-hq"];
Swift
geoFire.setLocation(CLLocation(latitude: 37.7853889, longitude: -122.4056973), forKey: "firebase-hq")

Alternatively a callback can be passed which is called once the server successfully saves the location:

Objective-C
[geoFire setLocation:[[CLLocation alloc] initWithLatitude:37.7853889 longitude:-122.4056973]
              forKey:@"firebase-hq"
 withCompletionBlock:^(NSError *error) {
     if (error != nil) {
         NSLog(@"An error occurred: %@", error);
     } else {
         NSLog(@"Saved location successfully!");
     }
 }];
Swift
geoFire.setLocation(CLLocation(latitude: 37.7853889, longitude: -122.4056973), forKey: "firebase-hq") { (error) in
  if (error != nil) {
    print("An error occured: \(error)")
  } else {
    print("Saved location successfully!")
  }
}

To remove a location and delete the location from your database simply call:

Objective-C
[geoFire removeKey:@"firebase-hq"];
Swift
geoFire.removeKey("firebase-hq")

Retrieving a location

Retrieving locations happens with callbacks. If the key is not present in GeoFire, the callback will be called with nil. If an error occurred, the callback is passed the error and the location will be nil.

Objective-C
[geoFire getLocationForKey:@"firebase-hq" withCallback:^(CLLocation *location, NSError *error) {
    if (error != nil) {
        NSLog(@"An error occurred getting the location for \"firebase-hq\": %@", [error localizedDescription]);
    } else if (location != nil) {
        NSLog(@"Location for \"firebase-hq\" is [%f, %f]",
              location.coordinate.latitude,
              location.coordinate.longitude);
    } else {
        NSLog(@"GeoFire does not contain a location for \"firebase-hq\"");
    }
}];
Swift
geoFire.getLocationForKey("firebase-hq") { (location, error) in
  if (error != nil) {
    print("An error occurred getting the location for \"firebase-hq\": \(error.localizedDescription)")
  } else if (location != nil) {
    print("Location for \"firebase-hq\" is [\(location.coordinate.latitude), \(location.coordinate.longitude)]")
  } else {
    print("GeoFire does not contain a location for \"firebase-hq\"")
  }
}

Geo Queries

GeoFire allows you to query all keys within a geographic area using GFQuery objects. As the locations for keys change, the query is updated in realtime and fires events letting you know if any relevant keys have moved. GFQuery parameters can be updated later to change the size and center of the queried area.

Objective-C
CLLocation *center = [[CLLocation alloc] initWithLatitude:37.7832889 longitude:-122.4056973];
// Query locations at [37.7832889, -122.4056973] with a radius of 600 meters
GFCircleQuery *circleQuery = [geoFire queryAtLocation:center withRadius:0.6];

// Query location by region
MKCoordinateSpan span = MKCoordinateSpanMake(0.001, 0.001);
MKCoordinateRegion region = MKCoordinateRegionMake(center.coordinate, span);
GFRegionQuery *regionQuery = [geoFire queryWithRegion:region];

Swift

let center = CLLocation(latitude: 37.7832889, longitude: -122.4056973)
// Query locations at [37.7832889, -122.4056973] with a radius of 600 meters
var circleQuery = geoFire.queryAtLocation(center, withRadius: 0.6)

// Query location by region
let span = MKCoordinateSpanMake(0.001, 0.001)
let region = MKCoordinateRegionMake(center.coordinate, span)
var regionQuery = geoFire.queryWithRegion(region)

Receiving events for geo queries

There are three kinds of events that can occur with a geo query:

  1. Key Entered: The location of a key now matches the query criteria.
  2. Key Exited: The location of a key no longer matches the query criteria.
  3. Key Moved: The location of a key changed but the location still matches the query criteria.

Key entered events will be fired for all keys initially matching the query as well as any time afterwards that a key enters the query. Key moved and key exited events are guaranteed to be preceded by a key entered event.

To observe events for a geo query you can register a callback with observeEventType:withBlock::

Objective-C
FIRDatabaseHandle queryHandle = [query observeEventType:GFEventTypeKeyEntered withBlock:^(NSString *key, CLLocation *location) {
    NSLog(@"Key '%@' entered the search area and is at location '%@'", key, location);
}];
Swift
var queryHandle = query.observeEventType(.KeyEntered, withBlock: { (key: String!, location: CLLocation!) in
  print("Key '\(key)' entered the search area and is at location '\(location)'")
})

To cancel one or all callbacks for a geo query, call removeObserverWithFirebaseHandle: or removeAllObservers:, respectively.

Waiting for queries to be "ready"

Sometimes you want to know when the data for all the initial keys has been loaded from the server and the corresponding events for those keys have been fired. For example, you may want to hide a loading animation after your data has fully loaded. GFQuery offers a method to listen for these ready events:

Objective-C
[query observeReadyWithBlock:^{
    NSLog(@"All initial data has been loaded and events have been fired!");
}];
Swift
query.observeReadyWithBlock({
  print("All initial data has been loaded and events have been fired!")
})

Note that locations might change while initially loading the data and key moved and key exited events might therefore still occur before the ready event was fired.

When the query criteria is updated, the existing locations are re-queried and the ready event is fired again once all events for the updated query have been fired. This includes key exited events for keys that no longer match the query.

Updating the query criteria

To update the query criteria you can use the center and radius properties on the GFQuery object. Key exited and key entered events will be fired for keys moving in and out of the old and new search area, respectively. No key moved events will be fired as a result of the query criteria changing; however, key moved events might occur independently.

Deployment

  • git pull to update the master branch
  • tag and push the tag for this release
  • ./build.sh to build a binary
  • From your macbook that already has been granted permissions to Firebase CocoaPods, do pod trunk push
  • Update firebase-versions with the changelog for this release.
  • Add the compiled target/GeoFire.framework.zip to the release

Contributing

If you'd like to contribute to GeoFire for iOS, you'll need to run the following commands to get your environment set up:

$ git clone https://github.com/firebase/geofire-objc.git
$ cd geofire-objc
$ pod install
$ open Geofire.xcworkspace

More Repositories

1

functions-samples

Collection of sample apps showcasing popular use cases using Cloud Functions for Firebase
JavaScript
12,063
star
2

flutterfire

🔥 A collection of Firebase plugins for Flutter apps.
Dart
8,671
star
3

quickstart-android

Firebase Quickstart Samples for Android
Java
8,563
star
4

firebase-js-sdk

Firebase Javascript SDK
TypeScript
4,830
star
5

quickstart-js

Firebase Quickstart Samples for Web
HTML
4,818
star
6

FirebaseUI-Android

Optimized UI components for Firebase
Java
4,628
star
7

firebaseui-web

FirebaseUI is an open-source JavaScript library for Web that provides simple, customizable UI bindings on top of Firebase SDKs to eliminate boilerplate code and promote best practices.
JavaScript
4,558
star
8

firebase-tools

The Firebase Command Line Tools
TypeScript
3,994
star
9

firebase-ios-sdk

Firebase iOS SDK
Objective-C
3,583
star
10

quickstart-ios

Firebase Quickstart Samples for iOS
Swift
2,773
star
11

firebase-android-sdk

Firebase Android SDK
Java
2,244
star
12

codelab-friendlychat-web

The source for the Firebase codelab for building a cross-platform chat app
JavaScript
1,749
star
13

firebase-admin-node

Firebase Admin Node.js SDK
TypeScript
1,621
star
14

FirebaseUI-iOS

iOS UI bindings for Firebase.
Objective-C
1,507
star
15

geofire-js

GeoFire for JavaScript - Realtime location queries with Firebase
TypeScript
1,443
star
16

firebaseui-web-react

React Wrapper for firebaseUI Web
JavaScript
1,262
star
17

firebase-admin-go

Firebase Admin Go SDK
Go
1,142
star
18

superstatic

Superstatic: a static file server for fancy apps.
JavaScript
1,097
star
19

firebase-functions

Firebase SDK for Cloud Functions
TypeScript
1,024
star
20

firebase-admin-python

Firebase Admin Python SDK
Python
1,019
star
21

quickstart-nodejs

JavaScript
895
star
22

extensions

Source code for official Firebase extensions
TypeScript
892
star
23

quickstart-unity

Firebase Quickstart Samples for Unity
C#
775
star
24

snippets-android

Android snippets for firebase.google.com
Java
762
star
25

snippets-web

Web snippets for firebase.google.com
JavaScript
749
star
26

genkit

An open source framework for building AI-powered apps with familiar code-centric patterns. Genkit makes it easy to develop, integrate, and test AI features with observability and evaluations. Genkit works with various models and platforms.
TypeScript
701
star
27

geofire-java

GeoFire for Java - Realtime location queries with Firebase
Java
671
star
28

firebase-admin-java

Firebase Admin Java SDK
Java
527
star
29

friendlyeats-web

JavaScript
467
star
30

snippets-node

Node.js snippets for firebase.google.com
JavaScript
369
star
31

firebase-admin-dotnet

Firebase Admin .NET SDK
C#
367
star
32

quickstart-testing

Samples demonstrating how to test your Firebase app
TypeScript
335
star
33

firebase-tools-ui

A local-first UI for Firebase Emulator Suite.
TypeScript
269
star
34

friendlyeats-android

Cloud Firestore Android codelab
Kotlin
261
star
35

codelab-friendlychat-android

Firebase FriendlyChat codelab
Kotlin
243
star
36

firebase-cpp-sdk

Firebase C++ SDK
C++
230
star
37

quickstart-java

Quickstart samples for Firebase Java Admin SDK
Java
224
star
38

firebase-functions-test

TypeScript
211
star
39

quickstart-cpp

Firebase Quickstart Samples for C++
C++
190
star
40

fastlane-plugin-firebase_app_distribution

fastlane plugin for Firebase App Distribution. https://firebase.google.com/docs/app-distribution
Ruby
166
star
41

friendlypix-ios

Friendly Pix iOS is a sample app demonstrating how to build an iOS app with the Firebase Platform.
Swift
166
star
42

quickstart-flutter

Dart
138
star
43

firebase-functions-python

Python
136
star
44

geofire-android

GeoFire for Android apps
Java
133
star
45

firebase-unity-sdk

The Firebase SDK for Unity
C#
128
star
46

friendlyeats-ios

Swift
127
star
47

snippets-ios

iOS snippets used in firebase.google.com
Objective-C
121
star
48

firebaseopensource.com

Source for firebase open source site
TypeScript
118
star
49

quickstart-python

Jupyter Notebook
115
star
50

FirebaseUI-Flutter

Dart
102
star
51

codelab-friendlychat-ios

Swift
68
star
52

snippets-rules

Snippets for security rules on firebase.google.com
TypeScript
45
star
53

emulators-codelab

JavaScript
44
star
54

oss-bot

Robot friend for open source repositories
TypeScript
36
star
55

firebase-bower

Firebase Web Client
JavaScript
35
star
56

snippets-flutter

Dart
30
star
57

snippets-go

Golang snippets for firebase docs
Go
24
star
58

snippets-java

Java snippets for firebase.google.com
Java
17
star
59

firebase-docs

TypeScript
16
star
60

abseil-cpp-SwiftPM

C++
13
star
61

firebase-testlab-instr-lib

Java
13
star
62

snippets-cpp

C++ snippets for firebase.google.com
C++
12
star
63

SpecsStaging

SpecsStaging
11
star
64

SpecsTesting

Ruby
11
star
65

rtdb-to-csv

JavaScript
11
star
66

appquality-codelab-ios

Firebase iOS App Quality Codelab
Objective-C
11
star
67

level-up-with-firebase

C#
9
star
68

boringSSL-SwiftPM

C++
8
star
69

firestore-bundle-builder

TypeScript
7
star
70

.github

Default configuration for Firebase repos
6
star
71

nginx

This repo is a PUBLIC FORK
C
6
star
72

SpecsDev

6
star
73

snippets-python

Python snippets for firebase.google.com
4
star
74

firebase-release-dashboard

JavaScript
4
star
75

ok

HTTPS CDN Proxy Healthy Check
4
star
76

grpc-SwiftPM

C++
3
star
77

crashlytics-testapps

Java
2
star
78

data-connect-ios-sdk

Swift
2
star
79

.allstar

1
star