Flutter Library

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.

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_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 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 flutter 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/Runner/info.plist

<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>
<key>NSLocationAlwaysUsageDescription</key>
<string>String that explains why you need this permission</string>

Install all required pods by running the following command in the ios directory

pod install

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_flutter/okhi_flutter.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: "", // your branch ID
      clientKey: "", // your client key
      env: OkHiEnv.prod,
      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:flutter/material.dart';

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

  @override
  _CreateAddressState createState() => _CreateAddressState();
}

class _CreateAddressState extends State<CreateAddress> {
  String? _successMessage;

  void _handleSuccess(response) async {
    print(response.user); // user information
    print(response.location); // address information
    setState(() {
      _successMessage = "Address successfully created: ${response.location.id}";
    });
    await response.startVerification(null);
    print("verification started for ${response.location.id}")
  }

  void _handleError(error) {
    print(error.code);
    print(error.message);
  }

  Widget _buildBody() {
    if (_successMessage != null) {
      return Center(
        child: Text(_successMessage!)
      );
    } else {
      return OkHiLocationManager(
        user: OkHiUser(phone: "+254712345678"),
        onSuccess: _handleSuccess,
        onError: _handleError,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Create an address"),
      ),
      body: _buildBody(),
  }
}

Customizing address type parameters

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

  • withHomeAddressType

  • withWorkAddressType

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(
  user: OkHiUser(phone: "+234xxxxx"),
  onSucess: (response) { // handle success },
  onError: (error) { // handle error },
  configuration: OkHiLocationManagerConfiguration(withHomeAddressType: true, withWorkAddressType: 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 OkHi.canStartVerification method will go ahead and request 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 practice doc requirement to make sure your application meets Play Store and App Store guidelines for requesting 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 the 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_flutter/okhi_flutter.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_flutter/okhi_flutter.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_flutter/okhi_flutter.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: "+234xxxxx");
final location = OkHiLocation(
    id: "<valid_okhi_location_id>",
    lat: -1.313,
    lon: 34.389,
);
await OkHi.startVerification(user, location, null);

Customizing OkHiLocationManager

It is possible to completely transform the default appearance 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: "+234xxxx"),
        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

Review the API reference

Build a webhook endpoint to receive OkHi address verification scores.

OkHi integration best practices

Full integration sample project

Last updated