React Native Library

The OkHi react native library will enable you to start collecting and verifying your user's addresses.

Prerequisites

OkHi Client Key and Branch Id

First you need to obtain your OkHi client key and branch ID. You can get these by signing up here.

Installation

Install the OkHi React Native library

yarn add react-native-okhi react-native-webview

Configure your app

Android

​Add the following permissions to your AndroidManifest.xml located under android/app/src/main/AndroidManifest.xml

<manifest ...>

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
    <uses-permission android:name="android.permission.INTERNET" />
    ...
    
    <application>
    ...
    </application>

</manifest>

If you're targeting Android versions >= 8 and you're using the OkVerify library you need to make sure your users select on "Allow always" when granting permissions otherwise the verification process won't work.

All OkHi react-native libraries target Android devices >= SDK 23. Make sure you're targeting at least the same by modifying your android/build.gradle file

ext {
  minSdkVersion = 23
  ..//
}

iOS

Enable background mode in your application.

OkHi obtains verification signals in the background, to enable this make sure to add "Location updates" and "Background fetch" to your Background Modes under Signing & Capabilities of your target.

Enable "Allow Non-modular includes in Framework modules"

in the Build Settings, filter for "allow non-modular" and Enable "Allow Non-modular includes in Framework modules"

Filter from "other c++", and add -fcxx-modules to both debug and release

All OkHi react-native libraries target IOS devices >= 12. Make sure you're targeting at least the same by modifying both your Podfile and deployment target.

Podile located under: ios/Podfile

platform :ios, '12.0'

Add necessary permissions to your info.plist file located under /ios/MyApp

<key>NSLocationWhenInUseUsageDescription</key>
<string>String that explains why you need this permission</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>String that explains why you need this permission</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>String that explains why you need this permission</string>

Finally, install all required pods by running the following command in the ios directory

pod install

Set up OkVerify in your AppDelegate file

Open your AppDelegate.h file located under ios/MyApp/AppDelegate.h and add the following lines

#import <React/RCTBridgeDelegate.h>
#import <UIKit/UIKit.h>
@import OkHi; // <= add this!

@interface AppDelegate : UIResponder <UIApplicationDelegate, RCTBridgeDelegate>

@property (nonatomic, strong) UIWindow *window;
@property (strong, nonatomic) OkVerify *okverify; // <= and this!
@end

Enable background monitoring

Open your AppDelegate.m file located under ios/MyApp/AppDelegate.m and add the following lines

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  self.okverify = [[OkVerify alloc] init]; // add this!
  if ([launchOptions objectForKey:UIApplicationLaunchOptionsLocationKey]) // add this!
    [self.okverify startMonitoring];
    
  //.. rest of default react native code
  return YES;
}

Initialization

Add the following initialization code to your index.js file. Replace my_branch_id and my_client_key with the keys provided to you after sign up.

import * as OkHi from 'react-native-okhi';

OkHi.initialize({
  credentials: {
    branchId: '', // your branch ID
    clientKey: '', // your client key
  },
  context: {
    mode: 'prod',
  },
  notification: {
    title: 'Address verification in progress',
    text: 'Tap here to view your verification status.',
    channelId: 'okhi',
    channelName: 'OkHi Channel',
    channelDescription: 'OkHi verification alerts',
  },
})
  .then(() => console.log('init done'))
  .catch(console.log);

Create and verify addresses

fcmPushNotificationToken is an optional field for your user object. Learn more.

import React, {useState} from 'react';
import {View, Button, ActivityIndicator, ViewStyle} from 'react-native';
import {
  OkHiLocationManager,
  OkCollectSuccessResponse,
  request,
} from 'react-native-okhi';

const App = () => {
  const [launch, setLaunch] = useState(false);
  const style: ViewStyle = {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  };

  const handleOnPress = async () => {
    request('always', null, async (status, error) => {
      if (status === 'authorizedAlways') {
        setLaunch(true);
      }
    });
  };

  const handleOnSuccess = async (response: OkCollectSuccessResponse) => {
    response.startVerification()
      .then(locationId => {
        console.log("started verification for: " + locationId)
      })
      .catch(error => {
        console.log(error.code)
        console.log(error.message)
      })
      .finally(() => {
        setLaunch(false);
      });
  };

  const renderLoader = () => {
    return (
      <View style={style}>
        <ActivityIndicator />
      </View>
    );
  };

  return (
    <View style={style}>
      <Button title="Create address" onPress={handleOnPress} />
      <OkHiLocationManager
        launch={launch}
        user={{
          phone: '+234xxxxx', // It is important to provide your actual phone number, as a message will be sent to this number
          firstName: 'Gift',
          lastName: 'Moore',
          email: 'giftmoore@okhi.com', // It is important to use your actual email address, an email may be sent to the provided address
          fcmPushNotificationToken: 'asdfgh.......'
        }}
        onCloseRequest={() => setLaunch(false)}
        onError={console.log}
        onSuccess={handleOnSuccess}
        config={{streetView: true}}
        loader={renderLoader()}
        theme={{
          appBar: {
            backgroundColor: '#333',
            logo: 'https://cdn.okhi.co/icon.png',
          },
          colors: {
            primary: '#333',
          },
        }}
      />
    </View>
  );
};

export default App;

Customizing verification type parameters

OkCollect V1 introduces the ability to specify out of two types, the location the customer is at.

  • home

  • work

Ideally, you would ask your user to specify this during address creation and it helps our AI more efficiently and quickly verify an address.

<OkHiLocationManager
  ...// normal configuration
  config={{ addressTypes: { home: true, work: false } }}
/>

Managing verification start requirements

For Addresses to be verified, the following requirements must be satisfied.

  1. User grants background location permission on both Android / iOS

  2. Location services must be turned on both Android / iOS

  3. Google Play Services must be available on Android

Luckily the OkHi library has helper methods to assist you with these requirements.

The request function will go ahead and requests for background location permission as well as activate any services that might be offline. If you'd like a much fine grain control over how permissions are requested please see the API reference.

Make sure to go over our best practices doc requirement to make sure your application meets Play Store and App Store guidelines for requesting for background location permission.

Leveraging OkVerify's Android foreground service

OkVerify's foreground service improves the reliability and stability of verification signals coming from your user's Android device. Here's how to use it

Due to the Background Execution Limits introduced in Android 8 as well as restrictions imposed by some device manufacturers its become increasingly difficult to determine accurate and timely verification signals within android applications. In order to ensure reliability of these verification signals, the library comes with an opt-in foreground service that you can leverage to decrease the amount of time it takes to verify an address.

Starting the foreground service

Configure a notification that'll be used to start the service. If you followed the previous guide, this should already be setup in your index.js file.

The foreground service is started by default once verification of an address starts, but can also be started again if previously stopped using the startForegroundService function

import { startForegroundService } from '@okhi/react-native-okverify';
 
const startedForegroundService = await startForegroundService(); // returns true || false indicating success of the process 

Stopping the foreground service

Stopping the service is easy, simply make a call to the stopForegroundService function

import { stopForegroundService } from '@okhi/react-native-okverify'
// stops the running foreground service
const stoppedForeground = await stopForegroundService();

Stopping the foreground service does not stop verification of that address, the library will continue to use background services in order to obtain verification signals.

Determining whether the foreground service is running

You can make a call to the isForegroundServiceRunning function to determine whether a foreground service is present and running

import { isForegroundServiceRunning } from '@okhi/react-native-okverify'
// stops the running foreground service
const serviceRunning = await isForegroundServiceRunning();

Customise notification icon & color

You can specify a custom default icon and a custom default color by adding these lines inside the application tag to set the custom default icon and custom color. You'll need to have already created the icon resource in your android application. Icon assets can be created by following these steps

<application>
    <!-- Set custom default icon for OkVerify's foreground service -->
    <meta-data android:name="io.okhi.android_background_geofencing.foreground_notification_icon" android:resource="@drawable/ic_person_pin" />
    <!-- Set custom default icon color for OkVerify's foreground service -->
    <meta-data android:name="io.okhi.android_background_geofencing.foreground_notification_color" android:resource="@color/colorAccent" />
    
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
    
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Recipes

Starting verification without using OkHiLocationManager

If your user created an address with OkHi and you have a valid locationId, pair of coordinates and user information such as a phone number, you can start verification without using the OkHiLocationManagerResponse object

import {start} from 'react-native-okhi';

const location = {id: '<user_okhi_location_id>', lat: -1.2344, lon: 34.83872};
await start('+234xxxx', location.id, location.lat, location.lon);

Customizing OkHiLocationManager

Its possible to completely transform the default apperance of OkHiLocationManager to better match your brand by providing values to the theme prop

const theme = {
 colors: {primary: '#005D67'},
 appBar: {
   backgroundColor: '#005D67',
   logo: 'https://mydomain.com/logo.png'
  },
};

<OkHiLocationManager
 user={user}
 launch={launch}
 theme={theme} // customizes apperance of buttons and app bar
 style={styles.locationManager} // customizes apperance of the wrapping container
 onSuccess={handleOnSuccess}
 onCloseRequest={handleCloseRequest}
 onError={handleOnError}
/>

FAQs

Building with pro-guard enabled

If you have minifyEnabled set to true in your build.gradle file located android/app/build.gradle, you'll need to modify your proguard-rules.pro file, located android/app/proguard-rules.proas shown bellow to include classes required by the library to run.

-dontwarn sun.reflect.**
-dontwarn java.beans.**
-dontwarn sun.nio.ch.**
-dontwarn sun.misc.**

-keep class com.esotericsoftware.** {*;}

-keep class java.beans.** { *; }
-keep class sun.reflect.** { *; }
-keep class sun.nio.ch.** { *; }

-keep class com.snappydb.** { *; }
-dontwarn com.snappydb.**

# If you don't use OkHttp as a dep and the following

-dontwarn org.codehaus.mojo.animal_sniffer.*
-dontwarn javax.annotation.**
-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase
-dontwarn org.codehaus.mojo.animal_sniffer.*
-dontwarn okhttp3.internal.platform.ConscryptPlatform
-dontwarn org.conscrypt.ConscryptHostnameVerifier

Next steps

Checkout the API reference

Build a webhook endpoint to receive OkHi address verification scores.

OkHi integration best practices

Last updated