Basic Integration
This will Guide you through the basic integration of Nudge SDK with various platform. This includes installing sdk, tracking events and tracking user.
Installing the SDK
- Android
- iOS
- Flutter
- React Native
- Web
Latest Version:
To install the nudge_android_v2
SDK into your Android application, follow these steps:
1. Configure settings.gradle
Add the following repository to your settings.gradle file to download the Nudge SDK:
- Groovy
- Kotlin(DSL)
dependencyResolutionManagement {
repositories {
maven {
url "https://github.com/nudgenow/android/raw/prod_main/release/"
}
}
}
dependencyResolutionManagement {
repositories {
maven("https://github.com/nudgenow/android/raw/prod_main/release/")
}
}
2. Add Plugin to build.gradle (Project-Level)
Ensure you have the Kotlin Android plugin in your project-level build.gradle:
- Groovy
- Kotlin(DSL)
plugins {
id "org.jetbrains.kotlin.android" version "1.7.10" apply false
}
plugins {
id("org.jetbrains.kotlin.android") version "1.7.10" apply false
}
3. Add SDK Dependency to build.gradle (App-Level)
Import the nudge_android_v2 SDK module-wide in your app-level build.gradle:
- Groovy
- Kotlin(DSL)
dependencies {
implementation "com.nudgenow.nudge_android:nudge_android_v2:latest_version"
}
dependencies {
implementation("com.nudgenow.nudge_android:nudge_android_v2:latest_version")
}
Sync Gradle: After adding the dependencies, sync your project in Android Studio.
Latest Version:
To install the Nudgecore_iOS
SDK into your iOS application, follow these steps:
Swift Package Manager (SPM)
Add the Nudgecore_iOS
SDK through Swift Package Manager in Xcode.
Use
https://github.com/nudgenow/iOS
as the package source.
Latest Version:
Add nudgecore_v2
to your pubspec.yaml
file:
dependencies:
nudgecore_v2: ^3.0.0
Run the following command to fetch the package:
flutter pub get
Run the below command to install the SDK
npm i nudge_react_native_v2
Find the latest version of the package here
Start by installing the nudge_core_browser_v2
SDK in your web application
npm install nudge_core_browser_v2
You can find the latest versions of the SDK here
Initialising Nudge
- Android
- iOS
- Flutter
- React Native
- Web
Initialize NudgeCore
in onCreate() method of the Application
class of your android app.
- Kotlin
- Java
import com.nudgenow.nudgecorev2.core.NudgeInitialise
class YourApplication : Application() {
override fun onCreate() {
super.onCreate()
NudgeCore.initialize(
application = this, // Context of Your Application
apiKey = "YOUR API KEY",
debugMode = true // THIS WILL ENABLE Nudge's Log to get printed
)
}
}
import com.nudgenow.nudgecorev2.core.NudgeCore;
public class YourApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
NudgeCore.initialize(
this, // Context of Your Application
"YOUR API KEY",
true // THIS WILL ENABLE Nudge's Log to get printed
);
}
}
Configure Proguard Rules
Add the below rule to your proguard rules
-keep class com.nudgenow.** { *; }
Initialize NudgeCore
in your iOS application by adding the following code to your AppDelegate
or SceneDelegate
file, depending on your app's lifecycle setup.
- SwiftUI
- UIKit
import SwiftUI
import Nudgecore_iOS
@main
struct YourApp: App {
var nudgeLifecycleManager: NudgeInitialise?
init() {
nudgeLifecycleManager = NudgeInitialise(
apiKey: "YOUR_API_KEY",
debugMode: true
)
}
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
import UIKit
import Nudgecore_iOS
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
var nudgeLifecycleManager: NudgeInitialise?
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
nudgeLifecycleManager = NudgeInitialise(
apiKey: "YOUR_API_KEY",
debugMode: true
)
return true
}
}
Import the nudgecore_v2
package in your Dart file:
import 'package:nudgecore_v2/nudgecore_v2.dart';
Create an instance of the Nudge
class with your API_KEY
:
Nudge nudge = Nudge(
apiKey: "API_KEY", // Obtain from the Nudge dashboard
debugMode: true // Enables verbose logging
);
Initialise Nudge()
in the main()
function before runApp()
is called.
A Nudge account is required to retrieve your API_KEY
. See how to create one here.
Navigation Key Configuration
Nudge requires access to the navigation stack to operate correctly. You may provide your own navigatorKey
or use the one provided by Nudge.nudgeNavigatorKey
.
Configuring a Custom Navigator Key
final GlobalKey<NavigatorState> clientNavigatorKey = GlobalKey<NavigatorState>();
await nudge.config(
navigatorKey: clientNavigatorKey, // Pass your custom navigator key
// navigatorKey: Nudge.nudgeNavigatorKey, // Use default key if not defining one
);
Using go_router
with Nudge
final NudgeTrackerObserver _nudgeTrackerObserver = NudgeTrackerObserver();
final GoRouter _router = GoRouter(
navigatorKey: clientNavigatorKey,
observers: [
_nudgeTrackerObserver, // Attaches Nudge tracking observer to monitor navigation transitions.
],
routes: [
GoRoute(
path: '/',
builder: (context, state) => HomePage(),
),
GoRoute(
path: '/test',
builder: (context, state) => const TestPage(),
),
],
);
class MainGoRouter extends StatelessWidget {
const MainGoRouter({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp.router(
debugShowCheckedModeBanner: false,
routerConfig: _router,
);
}
}
Using MaterialApp
with Nudge
class MainMaterialRouter extends StatelessWidget {
const MainMaterialRouter ({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
navigatorKey: clientNavigatorKey, // Assign the same navigator key
title: "Nudge App",
home: HomeScreen(),
routes: {
"/second": (context) => SecondScreen(),
},
);
}
}
Ensure the same navigator key is passed to both nudge.config()
and MaterialApp
.
Android-Specific Configuration
1. Updating build.gradle
allprojects {
repositories {
maven {
url "https://github.com/nudgenow/android/raw/prod_main/release/"
}
google()
mavenCentral()
}
}
2. Initializing SDK in MainApplication
Navigate to android/app/src/main/kotlin/com/example/example_app/
and create a MainApplication.kt
file with the following implementation:
package com.example.your_awesome_application
import android.app.Application
import com.nudgenow.nudgecore_v2.NudgecoreV2Plugin
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
// Initialize Nudge SDK lifecycle tracking
NudgecoreV2Plugin.NudgeFLutterLifecycleCapture(this)
}
}
3. Changing FlutterActivity
Navigate to android/app/src/main/kotlin/com/example/example_app/
and update your MainActivity.kt
file with the following implementation:
package com.example.your_awesome_application
import android.os.Bundle
import io.flutter.embedding.android.FlutterFragmentActivity
class MainActivity : FlutterFragmentActivity() { // if MainActivity extends from FlutterActivity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
... // rest of your code
}
}
4. Updating AndroidManifest.xml
Ensure that your AndroidManifest.xml
reflects the following modifications:
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application
android:label="your_awesome_application"
android:name=".MyApplication"
android:theme="@style/Theme.Material3.DayNight"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:taskAffinity=""
android:theme="@style/NormalTheme" >
Android Setup
- Inside the android block of your
app/build.gradle
file add the following
repositories{
maven{
url "https://github.com/nudgenow/android/raw/prod_main/release/"
}
}
- For Android, you need to add the Nudge SDK initialization code in your main application class.
import com.nudgecorev2reactnative.Nudgecorev2ReactNativeModule
class YourApplication: Application() {
override fun onCreate() {
super.onCreate()
Nudgecorev2ReactNativeModule.NudgeReactNativeLifecycleCapture(this)
}
}
- If you want to initialize the Nudge SDK from android side in your react native application use the below snippet :
import com.nudgecorev2reactnative.Nudgecorev2ReactNativeModule
class YourApplication: Application() {
override fun onCreate() {
super.onCreate()
Nudgecorev2ReactNativeModule.NudgeReactNative.initialise(this, "YOUR_API_KEY", debugMode : Boolean)
}
}
Importing the package
To use the Nudge SDK, you need to import the Nudge class in the main entry point of your application.
import { Nudge } from "nudge_react_native_v2";
Initialization
Initialize Nudge at the root of your application using the Nudge.init method. This method takes two parameters:
Your public API key (string)
Debug mode (boolean): When true, it will initialize the SDK in debug mode, helping you check logs and debug errors.
const YourApp = () => {
const navigationRef = React.useRef(null);
useEffect(() => {
Nudge.init(
"<YOUR_PUBLIC_API_KEY>",
true, //Debug mode
navigationRef , // Pass your ref if you are already using one
)
}, [])
return (
//Your Application code
)
}
Importing the package
Import Nudge
from nudge_core_browser_v2
package into your JS/TS file:
import { Nudge } from 'nudge_core_browser_v2';
Initialization
Create an instance of the Nudge
class with your desired variable name at the root of your application.
You need to pass the apiKey
in your instance (Your Public API key that can be obtained from your dashboard)
const nudge = new Nudge({ apiKey: <YOUR_PUBLIC_API_KEY>});
See how to find your Public API key here.
Example
import {Nudge} from 'nudge_core_browser_v2'
export default function App() {
const nudge = new Nudge({
apiKey:"API_KEY",
});
return ()
}
Identifying Users
- Android
- iOS
- Flutter
- React Native
- Web
You can identify users using the userIdentifier
method in our SDK. This method requires a unique user identifier and allows you to include additional user properties within a properties
object.
- To display the user's name, email, and phone number in the Nudge dashboard, pass these properties separately and do not include them again inside the props object.
- Keys in properties map should be in smaller case
- If you are sending any string properties the length should nt exceed 256 Characters
- Kotlin
- Java
val props = HashMap<String, Any>().apply {
put("sample_string_data", "20") // String
put("sample_float_data", 17.5) // Float
put("sample_int_data", 11) // String (Overwrites previous "zepto" entry)
put("sample_boolean_data", false) // Boolean
}
Nudge.getInstance().userIdentifier(
externalId = "unique_id_for_user",
properties = props, //optional
onResult = object : Nudge.NudgeResponse {
override fun onSuccess(response: String) {
// Handle success
}
override fun onFailure(error: String) {
// Handle failure
}
})
HashMap<String, Object> props = new HashMap<>();
props.put("sample_string_data", "20"); // String
props.put("sample_float_data", 17.5f); // Float
props.put("sample_int_data", 11); // Integer
props.put("sample_boolean_data", false); // Boolean
Nudge.getInstance().userIdentifier(
"unique_id_for_user",
props, //optional
new Nudge.NudgeResponse() {
@Override
public void onSuccess(String response) {
// Handle success
}
@Override
public void onFailure(String error) {
// Handle failure
}
}
);
You can identify users using the Nudge.getInstance().userIdentifier()
method provided by our SDK. This method requires a unique identifier for your user.
You can send user properties to Nudge by passing properties inside a props object.
To see the name, email, and phone number of the user in Nudge's dashboard, make sure to pass these properties outside the props object.
Nudge.getInstance().userIdentifier(
externalId: String,
name: String?,
email: String?,
phoneNumber: String?,
properties: [String : Any]?,
referralCode: String?,
completion: (Result<String, any Error>) -> Void
)
The completion handler is optional but, if provided, it will be called once the user identification process is complete. The Result type will return:
- A String, containing the
externalId
on success. - An Error if something goes wrong during the process.
Event name, event properties, and user properties all follow this regex : ^[a-z][a-z0-9_]99$
- Only small alphabets, numbers and underscore (_) are allowed
- Name cannot start with number, it needs to start with an alphabet only
- The name should be between 2 and 99 characters in length
- If any capital letter is sent, it will be converted to small case
Initialize user sessions with the userIdentifier
method to identify users. Providing the externalId
is crucial as it uniquely identifies the user.
nudge.userIdentifier(externalId: "EXTERNAL_ID");
or
Nudge.getInstance().userIdentifier(externalId: "EXTERNAL_ID");
Sending User Properties
You can also send additional user properties for better targeting and segmentation:
Map<String,dynamic>? props = {
"tier" : "Gold",
"location" : "India",
"hasSubscribed" : false,
};
nudge.userIdentifier (
externalId : "EXTERNAL_ID",
name: "Jon",
email: "[email protected]",
phoneNumber: "9999999999",
properties: props
)
or
Map<String,dynamic>? props = {
"tier" : "Gold",
"location" : "India",
"hasSubscribed" : false,
};
Nudge.getInstance().userIdentifier(
externalId: "EXTERNAL_ID",
name: "NAME",
email: "EMAIL",
phoneNumber: "PHONE_NUMBER",
properties: props);
- User properties need to be passed in the
properties
parameter. - Only
externalId
,name
,email
, andphoneNumber
are passed outside theproperties
parameter.
You can identify users using the userIdentifier
method provided by our SDK. This method requires a unique identifier for your user.
Nudge.userIdentifier(
"sample_id" //Client identifiable unique ID
);
Sending User Details
The userIdentifier
method takes a second parameter that is an object where you can send the user details. This object has 4 fields name
, email
, phoneNumber
and properties
. You can further add more data ito the properties
object.
The name
, email
, and phoneNumber
of the user are passed outside the properties
object.
Nudge.userIdentifier(
"sample_id", //externalId : Client identifiable unique ID
{
name: "Sample User", //optional
email: "[email protected]", //optional
phoneNumber: "9999999999", //optional
properties: {
//User properties
age: 25,
location: "India",
},
}
);
Track users and their properties in your web application.
You can identify users using the userIdentifier
method provided by our SDK. This method required a unique identifier for your user. You can also pass additional user properties inside a properties
object.
You can also send more user attributes along with the user ID for making segments of audiences.
To see the name, email, and phone number of the user in Nudge's dashboard, make sure to pass these properties outside the props object.
await nudge.userIdentifier({
externalId: "CLIENT_IDENTIFIABLE_USER_ID",
name: "Client User 1",
email: "[email protected]",
properties: {
age: 27,
gender: "M",
country: "US",
},
});
Tracking Events
- Android
- iOS
- Flutter
- React Native
- Web
Nudge provides a track method to track user interactions in your application. You can also send event properties with the track method.
- Event name should be in smaller case.
- Keys in properties map should be in smaller case
- If you are sending any string properties the length should n't exceed 256 Characters
- Kotlin
- Java
val props = HashMap<String, Any>().apply {
put("sample_string_data", "20") // String
put("sample_float_data", 17.5) // Float
put("sample_int_data", 11) // Integer
put("sample_boolean_data", false) // Boolean
}
Nudge.getInstance().track(
"event_name", // Event name
props, // Event properties (optional)
object : Nudge.NudgeResponse {
override fun onSuccess(response: String) {
// Handle success
}
override fun onFailure(error: String) {
// Handle failure
}
}
)
HashMap<String, Object> props = new HashMap<>();
props.put("sample_string_data", "20"); // String
props.put("sample_float_data", 17.5f); // Float
props.put("sample_int_data", 11); // Integer
props.put("sample_boolean_data", false); // Boolean
Nudge.getInstance().track(
"event_name", // Event name
props, // Event properties (optional)
new Nudge.NudgeResponse() {
@Override
public void onSuccess(String response) {
// Handle success
}
@Override
public void onFailure(String error) {
// Handle failure
}
}
);
}
- Only small alphabets, numbers, and underscores (_) are allowed.
- Spaces are not allowed in event names.
- Name cannot start with a number; it needs to start with an alphabet.
- The name should be between 2 and 99 characters in length.
- If any capital letter is sent, it will be converted to lowercase.
Nudge provides a track method to track user interactions in your application. You can also send event properties with the track method.
Nudge.getInstance().track(
event: String,
properties: [String : Any]?,
completion: (Result<Bool, any Error>) -> Void
)
Event name, event properties, and user properties all follow this regex : ^[a-z][a-z0-9_]99$
- Only small alphabets, numbers and underscore (_) are allowed
- Name cannot start with number, it needs to start with an alphabet only
- The name should be between 2 and 99 characters in length
- If any capital letter is sent, it will be converted to small case
The completion handler is optional but, if provided, it will be called once the event tracking process is complete. On success, it returns a Bool value (true) indicating that the event was tracked successfully. If something goes wrong, it returns an Error.
var props: [String: Any] = ["price": 150, "category": "food"]
Nudge.getInstance().track(
event: "click_button",
properties: props
completion: { result in
switch result {
case .success(let success):
if success {
print("Event tracked successfully.")
}
case .failure(let error):
// Handle the error accordingly.
print("Error tracking event: \(error)")
}
}
)
Track user interactions by calling the track
method. Ensure the session is initialized before tracking events:
Nudge.getInstance().track(event: "event_name");
or
nudge.track(event: "event_name");
- Only small alphabets, numbers, and underscores (_) are allowed.
- Spaces are not allowed in event names.
- Name cannot start with a number; it needs to start with an alphabet.
- The name should be between 2 and 99 characters in length.
- If any capital letter is sent, it will be converted to lowercase.
- Do not use
Nudge.getInstance().track()
ornudge.track()
insidebuild
method of a stateful widget.
Send Event Properties
Just like you added user properties, you can also send event properties along with you event:
Map<String,dynamic>? props = {
"tier" : "Gold",
"location" : "India",
"subscribe" : "No"
};
nudge.track(event: "event_name",properties: props);
or
Map<String,dynamic>? props = {
"tier" : "Gold",
"location" : "India",
"subscribe" : "No"
};
Nudge.getInstance().track(event: "event_name",properties: props);
Nudge provides a track method to track user interactions in your application. You can also send event properties with the track method.
Nudge.track("event_name", {
amount: 100, // Event Properties
mode: "upi",
});
- Only small alphabets, numbers, and underscores (_) are allowed.
- Spaces are not allowed in event names.
- Name cannot start with a number; it needs to start with an alphabet.
- The name should be between 2 and 99 characters in length.
- If any capital letter is sent, it will be converted to lowercase.
Track events and event properties in your web application
Nudge provides a track method to track user interactions in your application. You can also send event properties with the track method.
To see the name, email, and phone number of the user in Nudge's dashboard, make sure to pass these properties outside the props object.
await nudge.track({ event: "event_name" });
You can also add event properties for analytics and make segments of users based on their properties and actions for personalized experiences.
await nudge.track({
event: "event_name",
properties: {
product: "Fortune Cookies",
quantity: 5,
countryOfExport: "US",
},
});
User Sign Out
- Android
- iOS
- Flutter
- React Native
- Web
Once the user signs out from your application, use the userSignOut method provided by Nudge to clear any cached data for that user.
- Kotlin
- Java
Nudge.getInstance().userSignOut(
onResult = object : Nudge.NudgeResponse {
override fun onSuccess(response: String) {
}
override fun onFailure(error: String) {
}
})
Nudge.getInstance().userSignOut(new Nudge.NudgeResponse() {
@Override
public void onSuccess(String response) {
// Handle success
}
@Override
public void onFailure(String error) {
// Handle failure
}
});
Once the user signs out from your application, use the Nudge.getInstance.userSignOut
method provided by Nudge to clear any cached data for that user.
Nudge.getInstance().userSignout { result in
switch result {
case .success(let success):
if success {
print("User signed out successfully.")
}
case .failure(let error):
print("Error signing out user: \(error)")
}
}
Signing out users
Once the user signs out from your application, use the userSignOut
method provided by Nudge to clear any cached data for that user.
Nudge.getInstance().userSignOut()
For a hybrid structure you can use the below snippet to sign out users from the Android side :
Nudgecorev2ReactNativeModule.NudgeReactNative.userSignOut()
Once the user signs out from your application, use the userSignOut
method provided by Nudge to clear any cached data for that user.
await nudge.userSignOut();