Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

react-native-appsflyer

Package Overview
Dependencies
Maintainers
2
Versions
120
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

react-native-appsflyer

React Native Appsflyer plugin

  • 1.1.12
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
74K
increased by7.99%
Maintainers
2
Weekly downloads
 
Created
Source

react-native-appsflyer

The React Native Library for AppsFlyer SDK

npm version


In order for us to provide optimal support, we would kindly ask you to submit any issues to support@appsflyer.com

When submitting an issue please specify your AppsFlyer sign-up (account) email, your app ID, production steps, logs, code snippets and any additional relevant information.


Table of content

This plugin is built for

  • iOS AppsFlyerSDK
  • Android AppsFlyerSDK

Installation

$ npm install react-native-appsflyer --save

iOS

  1. Add the appsFlyerFramework to podfile and run pod install.

Example:

  pod 'react-native-appsflyer',
      :path => '../node_modules/react-native-appsflyer'

This assumes your Podfile is located in ios directory.

You must also have the React dependencies defined in the Podfile as described here.

  1. Run pod install (inside ios directory).

Manually:

  1. Download the Static Lib of the AppsFlyer iOS SDK from here: https://support.appsflyer.com/hc/en-us/articles/207032066-AppsFlyer-SDK-Integration-iOS#2-quick-start
  2. Unzip and copy the contents of the Zip file into your project directory
  3. Copy RNAppsFlyer.h and RNAppsFlyer.m from node_modulesreact-native-appsflyer to your project directory

enter image description here

Breaking Changes for react-native >= 0.40.0:

In RNAppsFlyer.h:

#import <React/RCTBridgeModule.h>  //for react-native ver >= 0.40
//#import "RCTBridgeModule.h"        //for react-native ver < 0.40

In RNAppsFlyer.m:

// for react-native ver >= 0.40
#import <React/RCTBridge.h>
#import <React/RCTEventDispatcher.h>

// for react-native ver < 0.40
//#import "RCTBridge.h"
//#import "RCTEventDispatcher.h"

Android

android/app/build.gradle

Add the project to your dependencies

dependencies {
    ...
    compile project(':react-native-appsflyer')
}
android/settings.gradle

Add the project

include ':react-native-appsflyer'
project(':react-native-appsflyer').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-appsflyer/android')

Build project so you should get following dependency (see an Image):

enter image description here

MainApplication.java

Add:

  1. import com.appsflyer.reactnative.RNAppsFlyerPackage;

  2. In the getPackages() method register the module: new RNAppsFlyerPackage(MainApplication.this)

So getPackages() should look like:

 @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
          new RNAppsFlyerPackage(MainApplication.this),
          //.....
      );
    }

API Methods


Call module by adding:

import appsFlyer from 'react-native-appsflyer';


appsFlyer.initSdk(options, callback): void

initializes the SDK.

parametertypedescription
optionsObjectSDK configuration

options

nametypedefaultdescription
devKeystringAppsflyer Dev key
appIdstringApple Application ID (for iOS only)
isDebugbooleanfalsedebug mode (optional)

Example:

const options = {
  devKey: "WdpTVAcYwmxsaQ4WeTspmh",
  appId: "975313579",
  isDebug: true
};

if (Platform.OS === 'ios') {
  options.appId = "0546492998";
}

appsFlyer.initSdk(options,
  (result) => {
    console.log(result);
  },
  (error) => {
    console.error(error);
  }
)

appsFlyer.trackAppLaunch(): void

Necessary for tracking sessions and deep link callbacks in iOS on background-to-foreground transitions. Should be used with the relevant AppState logic.

Example:

state = {
  appState: AppState.currentState
}

componentDidMount() {
  AppState.addEventListener('change', this._handleAppStateChange);
}

componentWillUnmount() {
   AppState.removeEventListener('change', this._handleAppStateChange);
}

_handleAppStateChange = (nextAppState) => {
  if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
      
      if (Platform.OS === 'ios') {
        appsFlyer.trackAppLaunch();
      }
  }
  
  this.setState({appState: nextAppState});
}

appsFlyer.setCustomerUserId(customerUserId, callback): void

Setting your own Custom ID enables you to cross-reference your own unique ID with AppsFlyer’s user ID and the other devices’ IDs. This ID is available in AppsFlyer CSV reports along with postbacks APIs for cross-referencing with you internal IDs.

Note: The ID must be set during the first launch of the app at the SDK initialization. The best practice is to call this API during the deviceready event, where possible.

parametertypedescription
customerUserIdString

Example:

const userId = "some_user_id";

appsFlyer.setCustomerUserId(userId,
  (response) => {
    //..
  }
); 

appsFlyer.trackEvent(eventName, eventValues, successC, errorC): void
  • These in-app events help you track how loyal users discover your app, and attribute them to specific campaigns/media-sources. Please take the time define the event/s you want to measure to allow you to track ROI (Return on Investment) and LTV (Lifetime Value).
  • The trackEvent method allows you to send in-app events to AppsFlyer analytics. This method allows you to add events dynamically by adding them directly to the application code.
parametertypedescription
eventNameStringcustom event name, is presented in your dashboard. See the Event list HERE
eventValuesObjectevent details (optional)

Example:

const eventName = "af_add_to_cart";
const eventValues = {
  "af_content_id": "id123",
  "af_currency":"USD",
  "af_revenue": "2"
};

appsFlyer.trackEvent(eventName, eventValues, successC, errorC) => {
  (result) => {
    //...
  },
  (error) => {
    console.error(error);
  }
 })
    

Track App Uninstalls

iOS

AppsFlyer enables you to track app uninstalls. To handle notifications it requires to modify your AppDelegate.m. Use didRegisterForRemoteNotificationsWithDeviceToken to register to the uninstall feature.

Example:

@import AppsFlyerLib;

...

- (void)application:(UIApplication ​*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *​)deviceToken {
   // notify AppsFlyerTracker
   [[AppsFlyerTracker sharedTracker] registerUninstall:deviceToken];
}

Read more about Uninstall register: Appsflyer SDK support site

Android

appsFlyer.enableUninstallTracking(GCMProjectID): void (Android only)

Set the GCM API key. AppsFlyer requires a Google Project Number and GCM API Key to enable uninstall tracking.

parametertypedescription
GCMProjectIDString

Example:


 enableUninstallTracking(){
    const  gcmProjectNum = "987186475229";
    appsFlyer.enableUninstallTracking(gcmProjectNum,
        (success) => {
          //...
        })
  }
  

Read more about Android Uninstall Tracking: Appsflyer SDK support site


appsFlyer.onInstallConversionData(callback): function:unregister

Accessing AppsFlyer Attribution / Conversion Data from the SDK (Deferred Deeplinking). Read more: Android, iOS

parametertypedescription
callbackfunctionreturns object
callback structure:
  • status: "success"or "failure" if SDK returned error on onInstallConversionData event handler
  • type:
  • "onAppOpenAttribution" - returns deep linking data (non-organic)
  • "onInstallConversionDataLoaded" - called on each launch
  • "onAttributionFailure"
  • "onInstallConversionFailure"
  • data: some metadata, for example:
{
  "status": "success",
  "type": "onInstallConversionDataLoaded",
  "data": {
    "af_status": "Organic",
    "af_message": "organic install"
  }
}

The code implementation fro the conversion listener must be made prior to the initialisation code of the SDK

Example:

this.onInstallConversionDataCanceller = appsFlyer.onInstallConversionData(
  (data) => {
    console.log(data);
  }
);

appsFlyer.initSdk(...);

The appsFlyer.onInstallConversionData returns function to unregister this event listener. Actually it calls NativeAppEventEmitter.remove()

Example:

_unmountAFListener() {
  if(this.onInstallConversionDataCanceller){
    this.onInstallConversionDataCanceller();
  }
}

state = {
  appState: AppState.currentState
}

componentDidMount() {
  AppState.addEventListener('change', this._handleAppStateChange);
}

componentWillUnmount() {
   _unmountAFListener();
   AppState.removeEventListener('change', this._handleAppStateChange);
}

_handleAppStateChange = (nextAppState) => {
  if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
  
      if (Platform.OS === 'ios') {
        appsFlyer.trackAppLaunch();
      }
  }

  if (this.state.appState.match(/active|foreground/) && nextAppState === 'background') {
    _unmountAFListener();
  }
  
  this.setState({appState: nextAppState});
}

appsFlyer.getAppsFlyerUID(callback): void

Get AppsFlyer’s proprietary Device ID. The AppsFlyer Device ID is the main ID used by AppsFlyer in Reports and APIs.

parametertypedescription
errorStringError callback - called on getAppsFlyerUID failure
appsFlyerUIDstringThe AppsFlyer Device ID

Example:

appsFlyer.getAppsFlyerUID((error, appsFlyerUID) => {
  if (error) {
    console.error(error);
  } else {
    console.log("on getAppsFlyerUID: " + appsFlyerUID);
  }
});

appsFlyer.trackLocation(longitude, latitude, callback(error, coords): void (iOS only)

Get AppsFlyer’s proprietary Device ID. The AppsFlyer Device ID is the main ID used by AppsFlyer in Reports and APIs.

parametertypedescription
errorStringError callback - called on getAppsFlyerUID failure
appsFlyerUIDstringThe AppsFlyer Device ID

Example:

const latitude = -18.406655;
const longitude = 46.406250;
 
appsFlyer.trackLocation(longitude, latitude, (error, coords) => {
  if (error) {
    console.error(error);
  } else {
    this.setState({ ...this.state, trackLocation: coords });
  }
});

appsFlyer.sendDeepLinkData(String url): void (Android only)

Report Deep Links for Re-Targeting Attribution (Android). This method should be called when an app is opened using a deep link.

Example:

componentDidMount() {
  Linking.getInitialURL().then((url) => {
    if (appsFlyer) {
        appsFlyer.sendDeepLinkData(url); // Report Deep Link to AppsFlyer
        // Additional Deep Link Logic Here ...
      }
  }).catch(err => console.error('An error occurred', err));
}

More about Deep Links in React-Native: React-Native Linking More about Deep Links in Android: Android Deep Linking , Adding Filters


appsFlyer.setUserEmails(options, errorC, successC): void

AppsFlyer enables you to report one or more of the device’s associated email addresses. You must collect the email addresses and report it to AppsFlyer according to your required encryption method. More info you can find on AppsFlyer-SDK-Integration-Android and AppsFlyer-SDK-Integration-iOS

parametertypedescription
optionsObjectsetUserEmails configuration

options

nametypedefaultdescription
emailsCryptTypeint0NONE - 0 (default), SHA1 - 1, MD5 - 2
emailsarraycomma separated list of emails

Example:

const options = {
  "emailsCryptType": 2,
  "emails": [
    "user1@gmail.com",
    "user2@gmail.com"
  ]
};

appsFlyer.setUserEmails(options,
  (response) => {
    this.setState({ ...this.state, setUserEmailsResponse: response });
  },
  (error) => {
    console.error(error);
  }
);
    

In order to track retargeting and use the onAppOpenAttribution callbacks in iOS, the developer needs to pass the User Activity / URL to our SDK, via the following methods in the AppDelegate.m file:

- (BOOL) application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray *_Nullable))restorationHandler
{
  [[AppsFlyerTracker sharedTracker] continueUserActivity:userActivity restorationHandler:restorationHandler];
  return YES;
}
URL Schemes
    // Reports app open from deep link from apps which do not support Universal Links (Twitter) and for iOS8 and below
    - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString*)sourceApplication annotation:(id)annotation {
        [[AppsFlyerTracker sharedTracker] handleOpenURL:url sourceApplication:sourceApplication withAnnotation:annotation];
        return YES;
    }
   
    // Reports app open from URL Scheme deep link for iOS 10
    - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
    options:(NSDictionary *) options {
        [[AppsFlyerTracker sharedTracker] handleOpenURL:url options:options];
        return YES;
    }

Demo

This plugin has a demo project bundled with it. To give it a try , clone this repo and from root a.e. react-native-appsflyer execute the following:

npm run setup
  • Run npm run demo.ios or npm run demo.android will run for the appropriate platform.
  • Run npm run ios-pod to run Podfile under demo project

demo printscreen

Second Demo (demo2)

Basic code implementation example of implementing the AppsFlyer React-Native plugin in the cross-platform App.js file:

  • Run npm run demo2.ios or npm run demo2.android will run for the appropriate platform.
  • Run npm run ios-pod2 to run Podfile under demo2 project

Keywords

FAQs

Package last updated on 04 Feb 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc