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: 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

Make sure to delete node_modules/ at project/node_modules/react-native-situm-plugin/node_modules.

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 follow repository in your project gradle file:

allprojects {
    repositories {
        maven {
            url "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 depedency 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:

//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. 

//App.js

import { PermissionsAndroid} from 'react-native';

...


//We will call this method from a <Button /> later
const requestLocationPermissions = async () => {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log("ACCESS_FINE_LOCATION granted");
    } else {
      console.log("ACCESS_FINE_LOCATION denied");
    }
  } catch (err) {
    console.warn(err);
  }
};

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 positioining, 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 { PermissionsAndroid} from 'react-native';
import { View, StyleSheet, Button} from 'react-native';
import SitumPlugin from 'react-native-situm-plugin';

//We will call this method from a <Button /> later
const requestLocationPermissions = async () => {
  try {
    const granted = await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      console.log("ACCESS_FINE_LOCATION granted");
    } else {
      console.log("ACCESS_FINE_LOCATION denied");
    }
  } catch (err) {
    console.warn(err);
  }
};
 

//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={requestLocationPermissions} />
    <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