04 – A basic React Native app

Situm SDK can be used to build Wayfinding and Tracking applications, and dozens of use cases within those realms. However, there is a common pattern or skeleton that most Situm based applications will follow. In this Section, we provide an Android step-by-step guide to build your first Situm app based on this pattern.

There are many things you can do with the Situm SDK React Native Plugin. In this guide, we will show you how to do the basic stuff. For more info, take a look at our React Native sample app and at the Plugin Method Reference.

Pre-requisites: Configuring React Native #

First, you need to setup react-native development environment. To get started please follow instructions under section React Native CLI Quickstart on this guide.

Installing the plugin #

We assume that you have already created a React Native application. There are some different ways to install the plugin:

Alternative 1 (Recommended): Integrate the plugin in your project with npm/yarn #

You may use the plugin using npm or yarn

#You may use yarn
$ yarn add react-native-situm-plugin

#or you may also use npm
$ npm install --save react-native-situm-plugin

Alternative 2: Integrate the plugin in your project from Github #

You may also download the plugin directly from Github:

#You may use yarn
$ yarn add https://github.com/situmtech/situm-react-native-plugin.git

#or you may also use npm
$ npm install --save https://github.com/situmtech/situm-react-native-plugin.git

#or using npm you may want to fetch a particular branch of the repository
npm install --save https://github.com/situmtech/situm-react-native-plugin.git#develop

Notes:

  • As of now, the SDK is available only on Github. When updating the SDK, make sure to delete the existing one from node_modules/react-native-situm-plugin.
  • Please note that we are using Cocoapods in order to manage iOS dependencies, which means you might need to run pod repo update when trying to compile your app after updating our plugin

Adding the dependencies to your project #

You will need to add different dependencies for Android and iOS.

Android #

In Android, you’ll need to add the following repository in your project gradle file:

allprojects {
    repositories {
        maven {
            url "https://repo.situm.com/artifactory/libs-release-local"
        }


        //You might also need to include this to solve altbeacon's dependencies (BLE scanning library used by Situm SDK)
        maven {
             url "https://jcenter.bintray.com/"
        }

    }
}

iOS #

In iOS, you’ll need to add the dependency to your PodFile

 target 'YourApp' do

    pod 'ReactNativeSitumPlugin', :path => '../node_modules/react-native-situm-plugin/ReactNativeSitumPlugin.podspec'

  end

In iOS, you may need to add a Header Search Path.

  $(SRCROOT)/../node_modules/react-native-situm-plugin/lib/ios

Import and initialize the plugin #

You must initialize the SDK before using any of its features. To do this I create an App.js file in the root directory of the project:

//App.js

import SitumPlugin from 'react-native-situm-plugin';
...


const App = () => {


   SitumPlugin.initSitumSDK();
   ...


}

Set your credentials #

Then, you can setup your credentials. If you choose APIKEY based authentication (recommended option), you may retrieve your APIKEY from your Profile.

//App.js. Always call this code after the SitumSDK.init()

//Option 1 (Recommended). APIKEY based authentication
SitumPlugin.setApiKey("SITUM_EMAIL", "SITUM_API_KEY", (response) =>{})

//Option 2. User-Password based authentication
SitumPlugin.setUserPass("SITUM_EMAIL", "SITUM_PASS", (response) =>{})

Request application permissions #

Your application will need certain permissions in order to work correctly.

Android #

In Android, you will need the ACCESS_FINE_LOCATION permission (see this link for details). First, declare it in your AndroidManifest.xml file.

//AndroidManifest.xml
<manifest>
...
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
...
</manifest>

Then, at runtime, you will need to ask the user if they wish to grant your app this permission. To do this, you may use the code that we provide in RequestPermissions.tsx. You will need to install the library react-native-permissions.

//App.js

import {Platform} from 'react-native';
import {
  PERMISSIONS,
  request,
  requestMultiple,
  RESULTS,
} from 'react-native-permissions';

...


//We will call this method from a <Button /> later
async function requestPermissions(): Promise<PermissionsRequestResult> {
  return new Promise(async (resolve, reject) => {
    console.log('Retrieving permissions for platform ' + Platform.OS);
    
    if (Platform.OS === 'ios') {
       ...
    } else {
      ....
    }

    resolve({result: PermissionsRequestResultTypes.NOT_GRANTED});
  });
}

Keep reading to know how to call the requestLocationPermissions declared in the previous snippet.

iOS #

Comming soon.

Starting positioning #

Then, you may start positioning by using the SitumPlugin.startPositioning method. You may pass a locationOptions object in order to modify the default positioning parameters.

//App.js

//We will use this variable as a reference to the SDK positioning instance
let subscriptionId = 0 

//We will call this method from a <Button /> later
const startPositioning = async () => {

  console.log("Starting positioning")


  //Declare the locationOptions (empty = default parameters)
  const locationOptions = { };


  //Start positioning
  subscriptionId = SitumPlugin.startPositioning(
    (location) => {
      //returns location object
      console.log(JSON.stringify(location))
    },
    (status) => {
      //returns positioning status
      console.log(JSON.stringify(status))
    },
    (error) => {
      // returns an error string
      console.log(error)
    },
    locationOptions
  )
}

Stopping positioning #

If you want to stop positioning, you may just call the SitumPlugin.stopPositioning method.

//We will call this method from a <Button /> later
const stopPositioning = async () => {

  console.log("Stopping positioning")

  SitumPlugin.stopPositioning(subscriptionId, (success) => {});
  
}

Bundling everything together with a 3 button interface #

For the sake of the example, we will create a simple interface with 3 buttons:

  • Request permissions: to call the requestLocationPermissions method.
  • Start: to call the startPositioning method.
  • Stop: to call the stopPositioning method.

The following snippet contains the whole App.js file:

import React from 'react';
import { View, StyleSheet, Button} from 'react-native';
import SitumPlugin from 'react-native-situm-plugin';
import {
  PERMISSIONS, request, requestMultiple, RESULTS,
} from 'react-native-permissions';
...
//See https://github.com/situmtech/situm-react-native-plugin/blob/master/example/src/examples/Utils/RequestPermissions.tsx
//for a full implementation of this function


//We will call this method from a <Button /> later
//See https://github.com/situmtech/situm-react-native-plugin/blob/master/example/src/examples/Utils/RequestPermissions.tsx
//for a full implementation of this function
async function requestPermissions(): Promise<PermissionsRequestResult> {
  return new Promise(async (resolve, reject) => {
    console.log('Retrieving permissions for platform ' + Platform.OS);
    
    if (Platform.OS === 'ios') {
       ...
    } else {
      ....
    }

    resolve({result: PermissionsRequestResultTypes.NOT_GRANTED});
  });
}
 

//We will use this variable as a reference to the SDK positioning instance
let subscriptionId = 0 

//We will call this method from a <Button /> later
const startPositioning = async () => {

  console.log("Starting positioning")


  //Declare the locationOptions (empty = default parameters)
  const locationOptions = { };


  //Start positioning
  subscriptionId = SitumPlugin.startPositioning(
    (location) => {
      //returns location object
      console.log(JSON.stringify(location))
    },
    (status) => {
      //returns positioning status
      console.log(JSON.stringify(status))
    },
    (error) => {
      // returns an error string
      console.log(error)
    },
    locationOptions
  )
}

//We will call this method from a <Button /> later
const stopPositioning = async () => {

  console.log("Stopping positioning")

  SitumPlugin.stopPositioning(subscriptionId, (success) => {});
  
}

const App = () => {

  //Initialize Situm SDK
  SitumPlugin.initSitumSDK();

  //APIKEY based authentication
  SitumPlugin.setApiKey("SITUM_EMAIL", "SITUM_API_KEY", (response) =>{})
 

  //3 Button interface
  return (
    <View style={styles.container}>
    <Button title="request permissions" onPress={requestPermissions} />
    <Button title="start" onPress={startPositioning} />
    <Button title="stop" onPress={stopPositioning} />
  </View>
  )
}

//CSS styles
const styles = StyleSheet.create({
  container: {
    margin: 100,
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'space-between'
    
  }
});


export default App;

Running the application #

If you want to run your app from your IDE:

  1. In Android Studio: open root/android folder in Android Studio and run project.
  2. In XCode: go to root/ios folder and open SitumRNGettingStarted.xcworkspace or run the command xed ios from the root directory.

If you want to run it from the command line:

#Android
react-native run-android

#iOS
react-native run-ios

You should see an interface like the following one:

Click on “Request Permissions” and accept the dialog. You should see a log like this:

LOG  ACCESS_FINE_LOCATION granted

Then, click on “Start”. The SDK will start and if everything works fine, it will start computing your geolocation:

LOG  Starting positioning
LOG  {"statusOrdinal":7,"statusName":"CALCULATING"}
LOG  {"statusOrdinal":0,"statusName":"STARTING"}
LOG  {"isOutdoor":true,"isIndoor":false,"hasCartesianBearing":false,"timestamp":"1634925467026","provider":"SITUM_PROVIDER","hasBearing":true,"cartesianCoordinate":{"y":0,"x":0},"position":{"isOutdoor":true,"coordinate":{"longitude":-8.413362,"latitude":43.3565841},"isIndoor":false,"cartesianCoordinate":{"y":0,"x":0},"floorIdentifier":"-1","buildingIdentifier":"-1"},"bearingQuality":"HIGH","coordinate":{"longitude":-8.413362,"latitude":43.3565841},"accuracy":22.395000457763672,"quality":"HIGH","cartesianBearing":{"radians":0,"radiansMinusPiPi":0,"degreesClockwise":360,"degrees":0},"deviceId":"728484012264","floorIdentifier":"-1","buildingIdentifier":"-1","bearing":{"radians":0,"radiansMinusPiPi":0,"degreesClockwise":360,"degrees":0}}

Finally, you may click on “Stop”. The SDK will stop and the log will reflect it:

LOG  Stopping positioning

Subscribe to our newsletter

BASIC INFORMATION ON DATA PROTECTION

Data controller: SITUM TECHNOLOGIES, S.L.
Contact: Data controller: situm@situm.es
Responsible for protection: dpo@situm.es
Purpose and legal basis: To manage the sending of SITUM newsletters only with consent.
Legitimation: Express consent of the interested party.
Recipients: The data will not be passed on to third parties with the exception of legal obligations.
Retention period: As long as the interested party remains subscribed to the newsletter (a link to unsubscribe will be available in each newsletter sent by Situm).
Rights: The interested party may at any time revoke their consent, as well as exercise their rights of opposition, access, conservation, rectification, limitation, deletion of data and not be subject to a decision based only on automated data processing, by writing to SITUM at the addresses indicated.
Additional Information: You can consult additional and detailed information on Data Protection in our privacy policy.

Please, download your copy here

Thank you for downloading our whitepaper. Please do not hesitate to contact us if you would like to know more about how our solutions can help your business. Download whitepaper


Close window