• Stars
    star
    375
  • Rank 114,096 (Top 3 %)
  • Language
    Objective-C
  • License
    MIT License
  • Created over 9 years ago
  • Updated over 6 years ago

Reviews

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

Repository Details

๐Ÿ“ก iBeacon support for React Native

react-native-ibeacon

iBeacon support for React Native. The API is very similar to the CoreLocation Objective-C one with the only major difference that regions are plain JavaScript objects. Beacons don't work in the iOS simulator.

Looking for an Android version? Try out

Support

This module supports all iBeacon-compatible devices. Personally, I had the best experience with Estimote beacons, but all devices that support the iBeacon specification should work.

Installation

Install using npm with npm install --save react-native-ibeacon. React Native >=0.4.0 is needed.

You then need to add the Objective C part to your XCode project. Drag RNBeacon.xcodeproj from the node_modules/react-native-ibeacon folder into your XCode project. Click on the your project in XCode, goto Build Phases then Link Binary With Libraries and add libRNBeacon.a and CoreLocation.framework.

NOTE: Make sure you don't have the RNBeacon project open separately in XCode otherwise it won't work.

Usage

var React = require('react-native');
var {DeviceEventEmitter} = React;

var Beacons = require('react-native-ibeacon');

// Define a region which can be identifier + uuid,
// identifier + uuid + major or identifier + uuid + major + minor
// (minor and major properties are numbers)
var region = {
	identifier: 'Estimotes',
	uuid: 'B9407F30-F5F8-466E-AFF9-25556B57FE6D'
};

// Request for authorization while the app is open
Beacons.requestWhenInUseAuthorization();

Beacons.startMonitoringForRegion(region);
Beacons.startRangingBeaconsInRegion(region);

Beacons.startUpdatingLocation();

// Listen for beacon changes
var subscription = DeviceEventEmitter.addListener(
  'beaconsDidRange',
  (data) => {
  	// data.region - The current region
  	// data.region.identifier
  	// data.region.uuid

  	// data.beacons - Array of all beacons inside a region
  	//	in the following structure:
  	//	  .uuid
  	//	  .major - The major version of a beacon
  	//	  .minor - The minor version of a beacon
  	//	  .rssi - Signal strength: RSSI value (between -100 and 0)
  	// 	  .proximity - Proximity value, can either be "unknown", "far", "near" or "immediate"
  	//	  .accuracy - The accuracy of a beacon
  }
);

It is recommended to set NSLocationWhenInUseUsageDescription in your Info.plist file.

Background mode

For background mode to work, a few things need to be configured: In the Xcode project, go to Capabilities, switch on "Background Modes" and check both "Location updates" and "Uses Bluetooth LE accessories".

bgmode

Then, instead of using requestWhenInUseAuthorization the method requestAlwaysAuthorization.

Beacons.requestAlwaysAuthorization();

Here, it's also recommended to set NSLocationAlwaysUsageDescription in your Info.plist file.

Finally when killed or sleeping and a beacon is found your whole app wont be loaded, just the didFinishLaunchingWithOptions:(NSDictionary *)launchOptions delegate so you need to act on it there like:

  // a region we were scanning for has appeared, ask to open us
  if([launchOptions objectForKey:@"UIApplicationLaunchOptionsLocationKey"])
  {
    //pop a notification to ask user to open, or maybe reload your scanner with delegate so that code fires
  }

Methods

To access the methods, you need import the react-native-ibeacon module. This is done through var Beacons = require('react-native-ibeacon').

Beacons.requestWhenInUseAuthorization

Beacons.requestWhenInUseAuthorization();

This method should be called before anything else is called. It handles to request the use of beacons while the application is open. If the application is in the background, you will not get a signal from beacons. Either this method or Beacons.requestAlwaysAuthorization needs to be called to receive data from beacons.

Beacons.requestAlwaysAuthorization

Beacons.requestAlwaysAuthorization();

This method should be called before anything else is called. It handles to request the use of beacons while the application is open or in the background. Either this method or Beacons.requestWhenInUseAuthorization needs to be called to receive data from beacons.

Beacons.getAuthorizationStatus

Beacons.getAuthorizationStatus(function(authorization) {
  // authorization is a string which is either "authorizedAlways",
  // "authorizedWhenInUse", "denied", "notDetermined" or "restricted"
});

This methods gets the current authorization status. While this methods provides a callback, it is not executed asynchronously. The values authorizedAlways and authorizedWhenInUse correspond to the methods requestWhenInUseAuthorization and requestAlwaysAuthorization respectively.

Beacons.startMonitoringForRegion

var region = {
  identifier: 'Estimotes',
  uuid: 'B9407F30-F5F8-466E-AFF9-25556B57FE6D'
};

Beacons.startMonitoringForRegion(region);

When starting monitoring for beacons, we need to define a region as the parameter. The region is an object, which needs to have at least two values: identifier and uuid. Additionally, it can also have a major, minor version or both. Make sure to not re-use the same identifier. In that case, we won't get the data for the beacons. The corresponding events are regionDidEnter and regionDidExit.

Beacons.startRangingBeaconsInRegion

var region = {
  identifier: 'Estimotes',
  uuid: 'B9407F30-F5F8-466E-AFF9-25556B57FE6D'
};

Beacons.startRangingBeaconsInRegion(region);

When ranging for beacons, we need to define a region as the parameter. The region is an object, which needs to have at least two values: identifier and uuid. Additionally, it can also have a major, minor version or both. Make sure to not re-use the same identifier. In that case, we won't get the data for the beacons. The corresponding events are beaconsDidRange. The event will fire in every interval the beacon sends a signal, which is one second in most cases. If we are monitoring and ranging for beacons, it is best to first call startMonitoringForRegion and then call startRangingBeaconsInRegion.

Beacons.startUpdatingLocation

Beacons.startUpdatingLocation();

This call is needed for monitoring beacons and gets the initial position of the device.

Beacons.stopUpdatingLocation

Beacons.stopUpdatingLocation();

This method should be called when you don't need to receive location-based information and want to save battery power.

Beacons.shouldDropEmptyRanges

Beacons.shouldDropEmptyRanges(true);

Call this method to stop sending the beaconsDidRange event when the beacon list is empty. This can be useful when listening to multiple beacon regions and can reduce cpu usage by 1-1.5%.

Events

To listen to events we need to call DeviceEventEmitter.addListener (var {DeviceEventEmitter} = require('react-native')) where the first parameter is the event we want to listen to and the second is a callback function that will be called once the event is triggered.

beaconsDidRange

This event will be called for every region in every beacon interval. If you have three regions you get three events every second (which is the default interval beacons send their signal). When we take a closer look at the parameter of the callback, we get information on both the region and the beacons.

{
  region: {
    identifier: String,
    uuid: String
  },
  beacons: Array<Beacon>
}

A Beacon is an object that follows this structure:

{
  uuid: String, // The uuid for the beacon
  major: Number, // A beacon's major value
  minor: Number, // A beacon's minor value
  rssi: Number, // The signal strength, where -100 is the maximum value and 0 the minium.
                // If the value is 0, this corresponds to not being able to get a precise value
  proximity: String, // Fuzzy value representation of the signal strength.
  		     // Can either be "far", "near", "immediate" or "unknown"
  accuracy: Number // One sigma horizontal accuracy in meters, see: http://stackoverflow.com/questions/20416218/understanding-ibeacon-distancing/30174335#30174335
}

By default, the array is sorted by the rssi value of the beacons.

regionDidEnter

If the device entered a region, regionDidEnter is being called.

Inside the callback the paramter we can use returns an object with a property region that contains the region identifier value as a string. Additionally, we get the UUID of the region through its uuid property.

{
  region: String,
  uuid: String
}

regionDidExit

In the same regionDidEnter is called if the device entered a region, regionDidExit will be called if the device exited a region and we can't get any signal from any of the beacons inside the region.

As for the payload, we get a property called region that represents the region identifier and is a string as well as the uuid.

{
  region: String,
  uuid: String
}

###authorizationDidChange When the user permissions change, for example the user allows to always use beacons, this event will be called. The same applies when the user revokes the permission to use beacons.

// The payload is a string which can either be:
// "authorizedAlways", "authorizedWhenInUse", "denied", "notDetermined" or "restricted"

Troubleshooting

In the beaconsDidRange event, the beacons property is just an empty array.

There are several things that trigger that behavior, so it's best to follow these steps:

  1. Don't use the same identifier for multiple regions
  2. Check if your beacon batteries aren't empty
  3. If monitoring and ranging for beacons, make sure to first monitor and then range

Style guide

This repository uses the Geniux code style guide (based on the AirBnB style guide), for more information see: https://github.com/geniuxconsulting/javascript

For commit messages, we are following the commit guide from https://github.com/geniuxconsulting/guideline

License

MIT, for more information see LICENSE

Changelog

See CHANGELOG.md

More Repositories

1

react-native-create-library

๐Ÿ““ Command line tool to create a React Native library with a single command
JavaScript
1,453
star
2

react-native-bluetooth-state

๐Ÿ“ถ Answering the question of "Is my bluetooth on?" in React Native
Objective-C
73
star
3

react-intl-native

react-intl components for React Native
JavaScript
62
star
4

react-native-flags

๐Ÿ Fun with flags (in React Native)!
JavaScript
51
star
5

moirai

๐Ÿƒ React.js game engine. Exciting, experimental and unstable
JavaScript
46
star
6

react-spritesheet

Spritesheets for React
JavaScript
34
star
7

superobject

๐Ÿ’ข A fast Delphi JSON parser - Fork of http://code.google.com/p/superobject/
Pascal
22
star
8

react-native-agenda-view

Display a schedule/agenda quickly with <AgendaView />
JavaScript
22
star
9

rollup-babel-lib-bundler

๐Ÿšœ Utility to bundle JavaScript libraries with Rollup
JavaScript
20
star
10

talks

Fancy talks I've done or will be doing
JavaScript
19
star
11

react-native-yaml-styles

๐Ÿ‘” If you prefer YAML over JSON for stylesheets in your React Native projects
Objective-C
17
star
12

flockn

๐ŸŽฎ Leightweight declarative game engine for JavaScript
JavaScript
16
star
13

react-lib-starterkit

My personal starterkit for React libraries
JavaScript
15
star
14

react-native-notification

๐Ÿ”” Customizable toast-like notifications for React Native
JavaScript
13
star
15

react-native-piechart

Pie Chart for React Native
Objective-C
12
star
16

react-native-helloworld

Transforming a React Hello World application into a React Native one
Objective-C
11
star
17

grunt-codo

Grunt task for generating codo documentation
CoffeeScript
8
star
18

tilelogic

Logic for tilemaps
TypeScript
7
star
19

rollup-plugin-local-resolve

Resolves Node-style directories with `index.js` files in Rollup
JavaScript
6
star
20

react-native-fontbase

The missing `rem` for React Native
JavaScript
6
star
21

rollup-plugin-named-directory

Resolves modules to its directory names
JavaScript
6
star
22

webpack-config-builder

Split your webpack config into multiple smaller parts
JavaScript
5
star
23

react-app-starterkit

My personal (opiniated) template for React projects
JavaScript
4
star
24

react-scenedirector

Managing scenes in React projects
JavaScript
4
star
25

require-webpack-compat

๐Ÿ’ Monkey-patches `require.context` into Node.js require
JavaScript
4
star
26

babel-preset-es2015-loose-rollup

Babel ES2015 Loose mode to be used with rollup
JavaScript
3
star
27

react-europe-hackathon2017

Something VR with embedding the Youtube conference streams and stuff
JavaScript
3
star
28

BESEN

Fork of BESEN Ecmascript Engine.
Component Pascal
3
star
29

react-tilemap

Tilemap built using React
JavaScript
2
star
30

detectr

detectr is a small library for adding user tests, for example detecting the current platform, display size and orientation
JavaScript
2
star
31

generator-pixi

Yeoman generator for Pixi.js
JavaScript
2
star
32

ava-tdd-starterkit

AVA TDD Starterkit
JavaScript
2
star
33

mealplan

TypeScript
2
star
34

gamebricks

Think Lodash, but for games
TypeScript
2
star
35

my-tech-stack

This is my personal opinionated tech stack
2
star
36

react-simple-component-state

Dead-simple component state with functional stateless React components
JavaScript
2
star
37

astroorigami

Migjam #12
JavaScript
1
star
38

travel-checklist

1
star
39

isr2013

Indie Speedrun Game 2013
JavaScript
1
star
40

bundlebee

Experiment to provide a unified API for bundlers and allow to just drop in bundlers
JavaScript
1
star
41

reshine

Let's take the sunshine path with RethinkDB
JavaScript
1
star
42

survivalguide-vampires

Indie Speed Run 2015
JavaScript
1
star
43

ghosthand

Lightweight blog engine for node.js
JavaScript
1
star
44

crust

Crust Library: Use the same (cheese-filled) crust, create a new topping.
C++
1
star
45

grunt-bower-commands

Grunt task for running bower commands
JavaScript
1
star
46

martian-robots

Command-line tool to path out the way for a robot on Mars
JavaScript
1
star
47

functional-game-template

JavaScript
1
star
48

migratr

Dead-simple database-agnostic migrations
JavaScript
1
star
49

github-issue-browser

TypeScript
1
star
50

repo-template

1
star
51

confessor

Command line library for FreePascal/Delphi
Pascal
1
star
52

fruityscript

TypeScript
1
star
53

todo-cards

Simple todo management for iOS written in React Native
Objective-C
1
star
54

moviedb

Movie DB app made in React
JavaScript
1
star
55

gitmoji-toolkit

:clown2: Several tools to use gitmoji commits in your projects
JavaScript
1
star
56

hapi-json-api-starterkit

Starterkit for creating JSON APIs with Hapi
JavaScript
1
star
57

standup-randomizer

1
star
58

monorepo-talk

JavaScript
1
star
59

conference-time

It's conference time! A mobile app made with React Native
JavaScript
1
star
60

immutable-tilelogic

TypeScript
1
star
61

react-native-image-container

An image container for images - in React Native
JavaScript
1
star
62

gitmoji-commiteur

Use emojis for your commits! โšก โœจ
JavaScript
1
star
63

clearice

Functional Canvas Renderer
TypeScript
1
star
64

juicyscript

Sweet experimental scripting language
TypeScript
1
star
65

shapeshifter

Experimental source-to-source transformer
1
star
66

horde3d-pascal

Pascal Bindings for Horde3D
Pascal
1
star
67

processing-sketcher

Small wrapper for using Processing.js with CoffeeScript
CoffeeScript
1
star
68

learning-curve

1
star
69

react-scaling-viewport

๐Ÿ“บ React viewport component that scales based on the window size
1
star
70

asteria

Prototyping a framework for JavaScript that works on the desktop
Component Pascal
1
star
71

react-proxy-es2015-loader

Like `react-proxy-loader`, but using ES2015
JavaScript
1
star