Creating a Beacon application with Ionic

This is a very quick “get going with beacons and Ionic 2” post.

The code can be found in a github repository here.

First create an Ionic app:

ionic start –v2 beacon-starter blank

Now, from the newly created application directory add the cordova beacon plugin:

ionic plugin add cordova-plugin-ibeacon

Next, create a provider (beacon-provider.ts) in a providers folder:

import { Injectable } from ‘@angular/core’;
import { Platform, Events } from ‘ionic-angular’;
import { IBeacon } from ‘ionic-native’;
/*
Generated class for the BeaconProvider provider.

See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class BeaconProvider {

delegate: any;
region: any;

constructor(public platform: Platform, public events: Events) {
}

initialise(): any {
let promise = new Promise((resolve, reject) => {
// we need to be running on a device
if (this.platform.is(‘cordova’)) {

// Request permission to use location on iOS
IBeacon.requestAlwaysAuthorization();

// create a new delegate and register it with the native layer
this.delegate = IBeacon.Delegate();

// Subscribe to some of the delegate’s event handlers
this.delegate.didRangeBeaconsInRegion()
.subscribe(
data => {
this.events.publish(‘didRangeBeaconsInRegion’, data);
},
error => console.error()
);

// setup a beacon region – CHANGE THIS TO YOUR OWN UUID
this.region = IBeacon.BeaconRegion(‘deskBeacon’, ‘F7826DA6-4FA2-4E98-8024-BC5B71E0893E’);

// start ranging
IBeacon.startRangingBeaconsInRegion(this.region)
.then(
() => {
resolve(true);
},
error => {
console.error(‘Failed to begin monitoring: ‘, error);
resolve(false);
}
);
} else {
console.error(“This application needs to be running on a device”);
resolve(false);
}
});

return promise;
}
}

 

Now import this provider into app.module.ts and add it to the providers folder.  Your app.module.ts file should then look like this:

 

import { NgModule } from ‘@angular/core’;
import { IonicApp, IonicModule } from ‘ionic-angular’;
import { MyApp } from ‘./app.component’;
import { HomePage } from ‘../pages/home/home’;
import { BeaconProvider } from ‘../providers/beacon-provider’

@NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [BeaconProvider]
})
export class AppModule { }

 

Next, create a model called beacon-module.ts in a models folder:

export class BeaconModel {

uuid: string;
major: number;
minor: number;
rssi: number;

constructor(public beacon: any) {
this.uuid = beacon.uuid;
this.major = beacon.major;
this.minor = beacon.minor;
this.rssi = beacon.rssi;
}
}

(we don’t really need a model for this app but creating one makes me feel more grown up)

Now change home.ts so it looks like this:

// core stuff
import { Component } from ‘@angular/core’;
import { NavController, Platform, Events } from ‘ionic-angular’;
import { NgZone } from “@angular/core”;

// plugins
import { IBeacon } from ‘ionic-native’;

// providers
import { BeaconProvider } from ‘../../providers/beacon-provider’

// models
import { BeaconModel } from ‘../../models/beacon-model’;

@Component({
selector: ‘page-home’,
templateUrl: ‘home.html’
})
export class HomePage {

beacons: BeaconModel[] = [];
zone: any;

constructor(public navCtrl: NavController, public platform: Platform, public beaconProvider: BeaconProvider, public events: Events) {
// required for UI update
this.zone = new NgZone({ enableLongStackTrace: false });
}

ionViewDidLoad() {
this.platform.ready().then(() => {
this.beaconProvider.initialise().then((isInitialised) => {
if (isInitialised) {
this.listenToBeaconEvents();
}
});
});
}

listenToBeaconEvents() {
this.events.subscribe(‘didRangeBeaconsInRegion’, (data) => {

// update the UI with the beacon list
this.zone.run(() => {

this.beacons = [];

let beaconList = data.beacons;
beaconList.forEach((beacon) => {
let beaconObject = new BeaconModel(beacon);
this.beacons.push(beaconObject);
});

});

});
}

}

and change home.html so it looks like this:

<ion-header>
<ion-navbar>
<ion-title>
My Beacons
</ion-title>
</ion-navbar>
</ion-header>

<ion-content>
<ion-list no-lines>

<ion-item *ngFor=”let beacon of beacons”>
<ion-grid>
<ion-row>
<ion-col>Major</ion-col>
<ion-col>{{beacon.major}}</ion-col>
</ion-row>
<ion-row>
<ion-col>Minor</ion-col>
<ion-col>{{beacon.minor}}</ion-col>
</ion-row>
<ion-row>
<ion-col>RSSI</ion-col>
<ion-col>{{beacon.rssi}}</ion-col>
</ion-row>
</ion-grid>
</ion-item>

</ion-list>
</ion-content>

That’s all there is to it.  You will need to change the UUID in the beacon provider to the UUID of your own beacons.   If you run the app it should detect your beacons and display a list of them on screen (showing major, minor and RSSI):

image1-1

 

Hopefully, that will get you started!  Good luck.

 


I’m a mobile applications developer based in the UK, concentrating primarily on hybrid application development with Ionic but also with native development skills. Please visit www.crossplatformsolutions.co.uk for more information about me and how I may be able to help you with mobile application development, particularly with Ionic but also with other mobile frameworks and technologies.  Thanks for visiting.

 

15 thoughts on “Creating a Beacon application with Ionic

  1. Pingback: Ionic 2 UI not updating after change to model | Ionically Speaking

  2. Frank Travieso

    Thanks. Your code was very helpful to me. But when i try copying the code in to my project and run on android mi code does not request for authorization and i have to give permission to the app manually. How can i solve this?.

    Reply
    1. Christophe

      Hello Richard
      I’ve used your code and deployed on android the list remains empty, there is no beacons detected.
      Facing with blank screen even changing the region UUID references, any idea ?

      //this.region = IBeacon.BeaconRegion(‘deskBeacon’,’f7826da6-4fa2-4e98-8024-bc5b71e0893e’);
      //this.region = IBeacon.BeaconRegion(‘deskBeacon’,’784fabe2-373b-4b72-8d55-33280f4f64e7′);
      //this.region = IBeacon.BeaconRegion(‘deskBeacon’,’e6c56db5-dffb-48d2-b088-40f5a81496ee’);
      this.region = IBeacon.BeaconRegion(‘estimote’, ‘b9407f30-f5f8-466e-aff9-25556b57fe6d’);

      thanks for your support

      Reply
      1. redoc (@redoc_)

        Hi Richard.. thanks for the post. I built an apk out of the code and deployed it on android phone. It just pops a white screen. It does nt go past that.

        I am still investigating on that. If you happen to know any issues with android please throw it here.

        Thanks.

  3. Dylan Gomes

    When i run your app i can see the beacons only 1 problem they go away fast in like 1 or 2 sec and it takes a while before i see them, How do i fix that? and how do i add the beacon his name to see on your screen?

    Reply
  4. Kevin

    Thanks. Your code was very helpful, but somehow it does not work. I got a blank screen, I think the ionViewDidLoad is not fired. is there any suggestion?

    Reply
  5. flyingil

    hello richard
    i’m using this code but it does not get beacons
    in home.ts >> listenToBeaconEvents()
    alert(JSON.stringify(data)); it returns
    {
    “eventType”:”didRangeBeaconslnRegion”,
    “region”:{
    “identifier”:”desk beacon”,
    “uuid”:”xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxx”,
    “typeName”:”BeaconRegion”
    },
    “beacons”:[]
    }

    what’s wrong with this??

    Reply
  6. seesemichaelj

    Thanks for the tutorial! I would look into a code-block/syntax-highlighting WordPress plugin (totally cool if you’re ignore my two cents too; just a suggestion). The single/double quotes are the wrong unicode character and do not paste into code nicely. The lack of tabination also makes it a little difficult to follow for beginners (I am not, but I could see others being discouraged from reading your tutorial). Cheers!

    Reply
  7. Felix

    Hello Richard,
    im trying to call a function when entering a certain region and another function when I’m leaving it. How can I achieve that.
    Thanks for your work!
    Best Regards

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s