React Native Documentation

Installing the SDK

This guide will help you setup the React Native module in your application. The module is built on top of native iOS and Android SDKs. The module exposes methods to start and stop tracking, and interact with the GeoSpark APIs.

In case you are not using React Native, you can refer to the iOS version, or Android version.

Install the module

In your project directory, install from npm, and then link it.

  
  $ npm install react-native-geospark --save
  $ react-native link react-native-geospark
  
  

Setup native dependencies

iOS

  1. The native iOS SDKs need to be setup using Cocoapods. In your project's ios directory, create a Podfile.
  2. Edit the Podfile to include GeoSpark as a dependency for your project, and then install the pod.
  3. Now, open the iOS project with the .xcworkspace file in Xcode, and add the GeoSpark.framework file to the linked frameworks and libraries section if they are not already added by Cocoapods.
  4. Then, go to Build Settings in the project targets and change 'Always Embed Swift Standard Libraries' to 'Yes'.
  
  $ cd ios
  $ pod init
  # ios/Podfile
  target 'AppName' do
    use_frameworks!

  # Pods for AppName
    pod 'GeoSpark'

  end
  
 

Manual linking on iOS

After the Cocoapods are setup, we need to manually link the wrapper code. This is a required step, in addition to the link command described previously.

  1. Open the iOS module files, located inside node_modules/react-native-geospark/ios/.
  2. Open the app workspace file (AppName.xcworkspace) in Xcode.
  3. Move the RNGeoSpark.h and RNGeoSpark.m files to your project. When shown a popup window, select Create groups.

Android

Update compileSdkVersion, buildToolsVersion, support library version Edit the build.gradle file in your android/app directory

  
  android {
        compileSdkVersion 26
        buildToolsVersion "26.0.2"
        ...
    }

  ```groovy
  dependencies {
    ...
    compile project(':react-native-geospark')
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:26.1.0"
    compile "com.facebook.react:react-native:+"  // From node_modules
    ...
  }
  ```
  
 

Importing the module

Import the module in App.js file

  
  import GeoSpark from 'react-native-geospark';
  
  

Initialize the API key

Android

Add the SDK to the dependencies section of your build.gradle file:

	
  dependencies {
  	compile 'com.geospark.android:geospark:0.0.4'
  }
	

To initialize the SDK, you must call the GeoSpark.initialize method when your app is started.

  
  public class MainApplication extends Application implements ReactApplication {

    private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {

	…
    @Override
    public void onCreate() {
        super.onCreate();
        SoLoader.init(this, / native exopackage / false);
        GeoSpark.initialize(context,"YOUR-SDK-KEY","YOUR-SECRET");
    }
  }
  

You should call this method in your Main Activity's onCreate method. Put in your own sdk key and secret here.

iOS

To initialize the SDK, you must call the GeoSpark.initialize method when your app is started.

  
  #import <GeoSpark/GeoSpark.h>

  - (BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(NSDictionary )launchOptions
	{
	…
   [[GeoSpark sharedInstance] intialize:@"YOUR-SDK-KEY" apiSecret:@"YOUR-SECRET"];

   [self registerForNotifications];
	...
  }

Capabilities and permissions

Follow these steps to setup native capabilities for iOS.

Go to the capabilities tab in your app settings, scroll to background modes and switch it on. Select Location updates, Background fetch and Remote notifications.

To add permission strings to your Info.plist, go to the Info tab in your app settings and add permission strings for


  Privacy - Location Always Usage Description
  Privacy - Location Always and When In Use Usage Description
  Privacy - Location When In Use Usage Description


Enable Location and Run Time Permissions

Android

The SDK requires Google Play Services to be YES.

  
  GeoSpark.checkGooglePlayService((status) => {
	// do something with status
 });
  

status will be a string, one of:

  • YES
  • NO

The SDK requires Location Permission to be granted.

  
  GeoSpark.checkPermission((status) => {
	// do something with status
 });
  

status will be a string, one of:

  • GRANTED
  • DENIED

To request location permissions for the app, call:

  
  GeoSpark.requestPermissions();
  

The SDK requires GPS to be enabled and Location Services to be enabled in High Accuracy.

  
  GeoSpark.checkLocationServices((status) => {
	// do something with status
  });
  

status will be a string, one of:

  • ENABLED
  • DISABLED

To enable GPS for the app, call:

  
  GeoSpark.requestLocationServices();
  

FCM/APNS Configurations

Android

  1. If you haven't set up Firebase and the FCM SDK, add Firebase to your Android project.
  2. In Android Studio, add the FCM dependency to your app-level build.gradle file:
  3.   
      dependencies {
        compile 'com.google.firebase:firebase-messaging:11.8.0'
      }
      
    
  4. Add the following to your app's manifest: A service that extends FirebaseInstanceIdService to handle the creation, rotation, and updating of registration tokens. This is required for sending to specific devices or for creating device groups.
      
      <service>
        android:name=".MyFirebaseInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
        </intent-filter>
      </service>
      
    
  5. When you need to retrieve the current token, call FirebaseInstanceId.getInstance().getToken() and add the below lines of code. This method returns null if the token has not yet been generated.
      
      public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
        @Override
        public void onTokenRefresh() {
            String refreshToken = FirebaseInstanceId.getInstance().getToken();
            if (refreshToken != null) {
                GeoSpark.setDeviceToken(getApplicationContext(), refreshToken);
            }
      	}
       }
      
    

iOS

  1. The following changes inside AppDelegate.h and AppDelegate.m will register the SDK for push notifications and route GeoSpark notifications to the SDK.

In AppDelegate.h, add the below line of code.

  
  #import <UserNotifications/UserNotifications.h>

  @interface AppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate>
  

In AppDelegate.m, inside didFinishLaunchingWithOptions, use the SDK method to register for notifications.

  
  #import <GeoSpark/GeoSpark.h>

  - (BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(NSDictionary )launchOptions
    {
      …
  [[GeoSpark sharedInstance] intialize:@"YOUR-SDK-KEY" apiSecret:@"YOUR-SECRET"];
  [self registerForNotifications];
	...
    }

  -(void)registerForNotifications{
    if(SYSTEM_VERSION_LESS_THAN( @"10.0" ))
  	 {
    [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
    [[UIApplication sharedApplication] registerForRemoteNotifications];
  	 }
    else
     {
	UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error)
     {
    if (granted) {
      dispatch_async(dispatch_get_main_queue(), ^{
    [[UIApplication sharedApplication] registerForRemoteNotifications];
      });
       }
      }];
     }
    }
  

Inside and didRegisterForRemoteNotificationsWithDeviceToken and didFailToRegisterForRemoteNotificationsWithError methods, add the relevant lines so that GeoSpark can register the device token.

  

  - (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
	{
  		NSString * token = [[[[deviceToken description]
                        stringByReplacingOccurrencesOfString: @"<" withString: @""]
                       stringByReplacingOccurrencesOfString: @">" withString: @""]
                      stringByReplacingOccurrencesOfString: @" " withString: @""];
  		[[GeoSpark sharedInstance] didRegisterForRemoteNotificationsWithDeviceToken:token];
	}
  - (void)application:(UIApplication )application
	didFailToRegisterForRemoteNotificationsWithError:(NSError )error{
  		[[GeoSpark sharedInstance] didFailToRegisterForRemoteNotificationsWithError:error];
	}
  

Inside the didReceiveRemoteNotification method, add the GeoSpark receiver. This method parses only the notifications that sent from GeoSpark.

	
  - (void)application:(UIApplication )application didReceiveRemoteNotification:(NSDictionary )userInfo{
     [[GeoSpark sharedInstance] didReceiveRemoteNotification:userInfo];
	    // Do any additional handling for your app's notifications.
  }	

Basic integration

Once the module has been installed and you have configured your SDK KEY and SECRET, you can use the methods of the SDK.

In case you are not using React Native, you can refer to the iOS version, or Android version.

Create a user

The SDK needs an User ID object to identify the device. The SDK has a convenience method createUser() to create a user which returns User ID.

	
  GeoSpark.createUser((success) => {
	// do something on success                                
  },
  (error) => {
	// do something on error                    
  });
	

To set an optional description for the user, displayed in the dashboard, call:

	
 GeoSpark.setDescription("description");
	

Get User

If you already have an User ID object. The SDK has a convenience method getUser() to to start the session for the existing user.

Method parameters
Parameter Description
userID User ID from your API Server

  GeoSpark.getUser("userID",(success) => {
	// do something on success                               
  },
  (error) => {
 	// do something on error                   
  });

Start Location Tracking

To start tracking the location, use the startLocationTracking() method. You can keep SDK to track location, or turn it off if you want to stop tracking the user at any point of time using the stopLocationTracking() method.

	
  GeoSpark.startLocationTracking();
	

Location Listener

You only need to call these methods once, as these settings will be persisted across app sessions.

To listen for location updates, you can add event listeners:

	
  GeoSpark.startListener('location', (result) => {
  	// do something with result.location, result.user
  });
	

Add event listeners outside of your component lifecycle (e.g., outside of componentDidMount) if you want them to work when the app is in the background.

You can also remove event listeners:

	
  GeoSpark.stopListener('location');
	

Stop Location Tracking

You can stop tracking the user at any point of time using the stopLocationTracking() method.

	
  GeoSpark.stopLocationTracking();
	

View Dashboard

Install your app with the GeoSpark SDK on a device and begin tracking on the Dashboard. You would see the user’s current state on the GeoSpark dashboard. If you click on the user, you should be able to view the user's location history.