OkHi on your Flutter App

The OkHi Flutter 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.

Use your sandbox keys while you test and develop, and your production mode keys before you publish your app.

Installation

Install the OkHi Flutter library by running the bellow command in your flutter project directory

flutter pub add okhi_flutter

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_NETWORK_STATE" />
    <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 20. Make sure you're targeting at-least the same by modifying your android/app/build.gradle file

ext {
  minSdkVersion = 20
  ..//
}

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.

All OkHi react-native libraries target ios devices >= 12. Make sure you're targeting at-least the same by modifying your 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 when in use location permission</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>String that explains why you need always location permission</string>

Set up OkHi in your AppDelegate file

Open your AppDelegate file located under ios/Runner/AppDelegate.swift and add in the following

import UIKit
import Flutter
import OkHi // <- import OkHi

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
    private let okverify = OkVerify() // <- initialize okverify
    
    override func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        if launchOptions?[UIApplication.LaunchOptionsKey.location] != nil { // <- enable monitoring
            okverify.startMonitoring()
        }
        GeneratedPluginRegistrant.register(with: self)
        return super.application(application, didFinishLaunchingWithOptions: launchOptions)
    }
}

Usage

Initialization

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

import 'package:okhi/okhi.dart';

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    final config = OkHiAppConfiguration(
      branchId: "<my_branch_id>",
      clientKey: "<my_client_key>",
      env: OkHiEnv.sandbox,
      notification: OkHiAndroidNotification(
        title: "Verification in progress",
        text: "Verifying your address",
        channelId: "okhi",
        channelName: "OkHi",
        channelDescription: "Verification alerts",
      ),
    );
    OkHi.initialize(config).then((result) {
      print(result); // returns true if initialization is successfull
    });
  }

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Home(),
    );
  }

Create and verify addresses

import 'package:okhi/okhi.dart';

class CreateAddress extends StatelessWidget {
  const CreateAddress({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Create an address"),
      ),
      body: OkHiLocationManager(
        user: OkHiUser(phone: "+254712345678"),
        onSucess: (response) async {
          print(response.user) // user information
          print(response.location) // address information
          await response.startVerification(null) // start verification with response
        },
        onError (error) {
          print(error.code)
          print(error.message)
        }
      ),
    );
  }
}

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 OkHi.canStartVerification method will go ahead and requests for background location permission as well as activate any services that might be offline. If you'd like much more fine grain control over location permission, see the API reference for more options.

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

Leveraging OkVerify's 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 as part of the initialization.

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

import 'package:okhi/okhi.dart';
 
await OkHi.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 'package:okhi/okhi.dart';
// stops the running foreground service
await OkHi.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 'package:okhi/okhi.dart';
// stops the running foreground service
await OkHi.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 in the AndroidManifest.xml located under android/app/src/main/AndroidManifest 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

final user = OkHiUser(phone: "+254712345678");
final location = OkHiLocation(
    id: "<valid_okhi_location_id>",
    lat: -1.313,
    lon: 34.389,
);
await OkHi.startVerification(user, location, null);

Customizing OkHiLocationManager

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

class Home extends StatelessWidget {
  const Home({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Create an address"),
      ),
      body: OkHiLocationManager(
        user: OkHiUser(phone: "+254712345678"),
        configuration: OkHiLocationManagerConfiguration(
          color: "#333",
          logoUrl: "https://mydomain.com/logo.png",
        ),
      ),
    );
  }
}

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

Full integration sample project

Last updated