Foursquare LogoFoursquare Developers Logo

React Native

To help with React Native development, we've put together a React Native module. In conjunction with a sample React Native app and our iOS and Android docs, you should have everything you need to get up and running.

This article was last updated on Dec 13, 2019 and tested with React Native 0.61.

Note: Using the Pilgrim SDK requires having a Pilgrim enabled developer account. If you do not already have one, you can request access.

Installation

  1. Install the module

    npm

    npm install @foursquare/pilgrim-sdk-react-native

    Yarn

    yarn add @foursquare/pilgrim-sdk-react-native
  2. Link native code

    With autolinking (react-native 0.60+)

    cd ios && pod install && cd ..

    Pre 0.60

    react-native link @foursquare/pilgrim-sdk-react-native

iOS Setup

  1. Add the following line to the application:didFinishLaunchingWithOptions method in your project's AppDelegate.m file:

    [[FSQPPilgrimManager sharedManager] configureWithConsumerKey:@"CONSUMER_KEY"
                                                           secret:@"CONSUMER_SECRET"
                                                         delegate:nil
                                                       completion:nil];

    Don't forget to use your actual CONSUMER_KEY and CONSUMER_SECRET, which can be retrieved from your Foursquare Developer Console.

    For example:

    // AppDelegate.m
    #import "AppDelegate.h"
    
    #import <React/RCTBridge.h>
    #import <React/RCTBundleURLProvider.h>
    #import <React/RCTRootView.h>
    #import <Pilgrim/Pilgrim.h>
    
    @implementation AppDelegate
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
     [[FSQPPilgrimManager sharedManager] configureWithConsumerKey:@"CONSUMER_KEY"
                                                           secret:@"CONSUMER_SECRET"
                                                         delegate:nil
                                                       completion:nil];
      // Other react native initialization code
    
      return YES;
    }
    ...

    This allows Pilgrim to run in the background and send you visit notifications, even when your iOS app isn't open.

  2. Ensure the CFBundleIdentifier of your project's Info.plist is correctly added to your Foursquare Developer Console app's iOS Bundle IDs setting. For more details on how to set this up, please refer to Pilgrim's iOS Getting Started Guide.
  3. (Optional) If you want to handle Pilgrim background notifications locally on the device, you would need to set the configureWith method's delegate to self:

    [[FSQPPilgrimManager sharedManager] configureWithConsumerKey:@"CONSUMER_KEY"
                                                         secret:@"CONSUMER_SECRET"
                                                       delegate:self
                                                     completion:nil];

    and add the notification handlers to your AppDelegate:

    - (void)pilgrimManager:(FSQPPilgrimManager *)pilgrimManager handleVisit:(FSQPVisit *)visit {
       // Handle a visit
    }
    
    - (void)pilgrimManager:(FSQPPilgrimManager *)pilgrimManager handleBackfillVisit:(FSQPVisit *)visit {
       // Handle a backfilled Visit
    }
    
    - (void)pilgrimManager:(FSQPPilgrimManager *)pilgrimManager handleGeofenceEvents:(NSArray<FSQPGeofenceEvent *> *)geofenceEvents {
       // Handle a geofence event
    }

Android Setup

  1. Add the following lines to the onCreate method in your project's android.app.Application subclass:

    PilgrimSdk.Builder builder = new PilgrimSdk.Builder(this)
           .consumer("CONSUMER_KEY", "CONSUMER_SECRET")
           .enableDebugLogs();
    PilgrimSdk.with(builder);

    Don't forget to use your actual CONSUMER_KEY and CONSUMER_SECRET, which can be retrieved from your Foursquare Developer Console.

    For example:

    // MainApplication.java
    import android.app.Application;
    import com.facebook.react.ReactApplication;
    import com.foursquare.pilgrim.PilgrimSdk;
    
    public class MainApplication extends Application implements ReactApplication {
    
       @Override
     public void onCreate() {
       super.onCreate();
    
       PilgrimSdk.Builder builder = new PilgrimSdk.Builder(this)
               .consumer("CONSUMER_KEY", "CONSUMER_SECRET")
               .enableDebugLogs();
       PilgrimSdk.with(builder);
    
       // Other react native initialization code
     }
    
     ...
    
    }

    This allows Pilgrim to run in the background and send you visit notifications, even when your Android app isn't open.

  2. In android/app/build.gradle modify the signingConfigs section to use your keystore file and ensure the storePassword, keyAlias, and keyPassword are set correctly:

    signingConfigs {
     debug {
       storeFile file('/path/to/file.keystore')
       storePassword 'storePassword'
       keyAlias 'keyAlias'
       keyPassword 'keyPassword'
     }
    }
  3. Ensure the SHA1 key hash of your project is correctly added to your Foursquare Developer Console app's Android Key Hashes setting. For more details on how to set this up, please refer to Pilgrim's Android Getting Started Guide.
  4. (Optional) If you want to handle Pilgrim background notifications locally on the device, you will need to add the notification handlers to your Application's onCreate:

    private final PilgrimNotificationHandler pilgrimNotificationHandler = new PilgrimNotificationHandler() {
       // Primary visit handler
       @Override
       public void handleVisit(Context context, PilgrimSdkVisitNotification notification) {
           // Process the visit however you'd like:
           //Visit visit = notification.getVisit();
           //Venue venue = visit.getVenue();
           //Log.d("PilgrimSdk", visit.toString());
       }
    
       // Optional: If visit occurred while in Doze mode or without network connectivity
       @Override
       public void handleBackfillVisit(Context context, PilgrimSdkBackfillNotification notification) {
           // Process the visit however you'd like:
           //super.handleBackfillVisit(context, notification);
           //Visit visit = notification.getVisit();
           //Venue venue = visit.getVenue();
           //Log.d("PilgrimSdk", visit.toString());
       }
    
       // Optional: If visit occurred by triggering a geofence
       @Override
       public void handleGeofenceEventNotification(Context context, PilgrimSdkGeofenceEventNotification notification) {
           // Process the geofence events however you'd like:
           //List<GeofenceEvent> geofenceEvents = notification.getGeofenceEvents();
           //for (GeofenceEvent geofenceEvent : geofenceEvents) {
           //  Log.d("PilgrimSdk", geofenceEvent.toString());
           //}
       }
    };

    and update the Pilgrim configuration in your onCreate to include the notification handler. For example:

    PilgrimSdk.Builder builder = new PilgrimSdk.Builder(this)
           .consumer("CLIENT_ID", "CLIENT_SECRET")
           .notificationHandler(pilgrimNotificationHandler)
           .enableDebugLogs();
    PilgrimSdk.with(builder);

    Why? Pilgrim handles location events in the background without the requirement of any visible UI. React Native, being written in JS, requires a UI thread before it is able to properly run. Adding the code to handle Pilgrim at the native Java level, allows Pilgrim to still run in the background.

Usage Examples

Getting User's Install ID

Each time Pilgrim is installed on a user's device, Pilgrim creates a unique installId. The returned value will be a Promise<string>. This can be used to allow your users to submit Data Erasure Requests or for debugging in our Event Logs tool in your developer console. Example usage:

import React, { Component } from 'react';
import { Text } from 'react-native';
import PilgrimSdk from '@foursquare/pilgrim-sdk-react-native';

export default class MyScreen extends Component {
  state = {
    installId: '-',
  };

  componentDidMount() {
    PilgrimSdk.getInstallId().then(installId => {
      this.setState({ installId: installId });
    });
  }

  render() {
    return (
      <>
        <Text>Install ID: {this.state.installId}</Text>
      </>
    );
  }
}

Getting User's Current Location

You can actively request the current location of the user by calling the PilgrimSdk.getCurrentLocation method. The return value will be a Promise<CurrentLocation>. The CurrentLocation object has the current venue the device is most likely at as well as any geofences that the device is in (if configured). More information here. Example usage:

import React, { Component } from 'react';
import { Alert, Text } from 'react-native';
import PilgrimSdk from '@foursquare/pilgrim-sdk-react-native';

export default class MyScreen extends Component {
  state = {
    currentLocation: null,
  };

  getCurrentLocation = async function() {
    try {
      const currentLocation = await PilgrimSdk.getCurrentLocation();
      this.setState({ currentLocation: currentLocation });
    } catch (e) {
      Alert.alert('Pilgrim SDK', `${e}`);
    }
  };

  componentDidMount() {
    this.getCurrentLocation();
  }

  render() {
    if (this.state.currentLocation != null) {
      const venue = this.state.currentLocation.currentPlace.venue;
      const venueName = venue.name || 'Unnamed venue';
      return (
        <>
          <Text>Venue: {venueName}</Text>
        </>
      );
    } else {
      return (
        <>
          <Text>Loading...</Text>
        </>
      );
    }
  }
}

Passive Location Detection

Passive location detection is controlled with the PilgrimSdk.start and PilgrimSdk.stop methods. When started, Pilgrim SDK will send notifications to Webhooks and other third-party integrations. Example usage:

import React, { Component } from 'react';
import { Alert, Button } from 'react-native';
import PilgrimSdk from '@foursquare/pilgrim-sdk-react-native';

export default class MyScreen extends Component {
  startPilgrim = async function() {
    const canEnable = await PilgrimSdk.canEnable();
    const isSupportedDevice = await PilgrimSdk.isSupportedDevice();
    if (canEnable && isSupportedDevice) {
      PilgrimSdk.start();
      Alert.alert('Pilrim SDK', 'Pilgrim started');
    } else {
      Alert.alert('Pilrim SDK', 'Error starting');
    }
  };

  stopPilgrim = function() {
    PilgrimSdk.stop();
    Alert.alert('Pilrim SDK', 'Pilgrim stopped');
  };

  render() {
    return (
      <>
        <Button
          title="Start"
          onPress={() => {
            this.startPilgrim();
          }}
        />
        <Button
          title="Stop"
          onPress={() => {
            this.stopPilgrim();
          }}
        />
      </>
    );
  }
}

Note: If you wish to handle background notifications locally on the device, you will need to add the notification handler and delegate in the native piece of each platform, as mentioned in the Installation instructions.

Debug Screen

The debug screen is shown using the PilgrimSdk.showDebugScreen method. This screen contains logs sent from Pilgrim SDK and other debugging tools/information. Example usage:

import React, { Component } from 'react';
import { Button } from 'react-native';
import PilgrimSdk from '@foursquare/pilgrim-sdk-react-native';

export default class MyScreen extends Component {
  showDebugScreen = function() {
    PilgrimSdk.showDebugScreen();
  };

  render() {
    return (
      <>
        <Button
          title="Show Debug Screen"
          onPress={() => {
            this.showDebugScreen();
          }}
        />
      </>
    );
  }
}

Test Visits

Test arrival visits can be fired with the method PilgrimSdk.fireTestVisit. You must pass a location to be used for the test visit. The arrival notification will be received via Webhooks and other third-party integrations

import React, { Component } from 'react';
import { Button } from 'react-native';
import PilgrimSdk from '@foursquare/pilgrim-sdk-react-native';

export default class Screen extends Component {
  fireTestVisit = async function() {
    navigator.geolocation.getCurrentPosition(
      position => {
        const latitude = position.coords.latitude;
        const longitude = position.coords.longitude;
        PilgrimSdk.fireTestVisit(latitude, longitude);
        Alert.alert('Pilgrim SDK', `Sent test visit with location: (${latitude},${longitude})`);
      },
      err => {
        Alert.alert('Pilgrim SDK', `${err}`);
      }
    );
  };

  render() {
    return (
      <>
        <Button
          title="Fire Test Visit"
          onPress={() => {
            this.fireTestVisit();
          }}
        />
      </>
    );
  }
}

API Reference

/**
 * Returns a unique identifier that gets generated the first time this sdk runs on a specific device.
 */
getInstallId(): Promise<string>;

/**
 * Call this after configuring the SDK to start the SDK and begin receiving location updates.
 */
start(): void;

/**
 * Stop receiving location updates, until you call `start` again.
 */
stop(): void;

/**
 * Gets the current location of the user.
 * This includes possibly a visit and and an array of geofences.
 */
getCurrentLocation(): Promise<CurrentLocation>;

/**
 * Generates a visit and optional nearby venues at the given location.
 */
fireTestVisit(latitude: number, longitude: number): void;

/**
 * Initializes a debug mode view controller for viewing PilgrimSDK logs and presents it.
 */
showDebugScreen(): void;

iOS only:

/**
 * If the current device is supported (no iPads or iPod touches; cellular network required).
 */
isSupportedDevice(): Promise<boolean>;

/**
 * If the user is on a supported device and all the required settings ("always" location permission) are on.
 */
canEnable(): Promise<boolean>;

Sample Application

We know sometimes the best way to start is to just get something up and running. So to help you get started faster with integrating Pilgrim into your own React Native app, we've put together a React Native Sample Application that you can get up and running on your own or use as a reference.

Next Steps

Configuration