AppsFlyer SDK Integration - iOS

Current Version: 4.8.0

AppsFlyer's SDK provides app installation and event tracking functionality.  We have developed an SDK that is highly robust (8+ billion SDK installations to date), secure, lightweight and very simple to embed.

You can track installs, updates and sessions (by following the mandatory steps below), and also track additional in-app events beyond app installs (including in-app purchases, game levels, etc.) to evaluate ROI and user engagement levels.

The mandatory steps are explained below, followed by additional optional features.

The iOS SDK is compatible with all iOS devices (iPhone, iPod, iPad) with iOS version 6 and above in Static Lib or iOS version 8 and above in Framework.


  • AppsFlyer's SDK is fully compliant with Apple's IPv6 DNS64/NAT64 Networks.  For more information, click here.
  • AppsFlyer's SDK makes use of NSUserDefaults class. Clearing values from NSUserDefaults may cause attribution issues.

The following sections are covered in this guide:

  iOS SDK Download

  • To download the iOS SDK as a static library click here.
  • To download the iOS SDK as a framework click here. 

1.  Release Notes

  • Release notes for the AppsFlyer iOS SDK can be found here.

2.  Embedding the SDK into Your Application (Mandatory)

AppsFlyer SDK is available both as a framework and as a static library.

2.1  AppsFlyer SDK Framework

The simplest way to integrate the framework is using cocoapods:

  • Add the following line to your pod file:
    pod ‘AppsFlyerFramework’

If you do not use cocoapods, follow the steps below:

  • In Xcode, go to Build Phases >> Link Binary with Libraries >> Click + to add a new library

  • Click Add Other and add the AppsFlyerLib.framework

  • Include the following header:
    #import <AppsFlyerLib/AppsFlyerTracker.h>

2.2  AppsFlyer SDK Static Library

The Static Library is now deprecated in Cocoapods. Please download it directly from this article (above).

Follow the steps below:

  • Add the header and lib files to your project.
  • Add the AppsFlyer header import:
  • #import "AppsFlyerTracker.h"
  • Add the AdSupport.framework to your project and set it as Optional. You can find the submission instructions here.

2.3  IDFA and Apple Search Ads

  • Add the AdSupport.framework - AppsFlyer collects IDFA only if you include this framework.  
    Failure to add this framework means that you cannot track Facebook, Twitter and most other ad networks.
  • Add the iAd.framework to your project. - It is highly recommend to include this framework in the app since it is mandatory for tracking Apple Search Ads.  

3.  SDK Initialization & Installation Event (Minimum Requirement for Tracking)

NOTE:  This is the minimum requirement to start tracking your app installs.

You must initialize the SDK on the first launch of the app.  Make sure that the SDK is initialized before sending the tracking event below.

3.1  Initializing the SDK

To initialize the SDK, add the following to your “didFinishLaunchingWithOptions” function:

[AppsFlyerTracker sharedTracker].appsFlyerDevKey = @"REPLACE THIS WITH YOUR Dev_Key";
[AppsFlyerTracker sharedTracker].appleAppID = @"REPLACE THIS WITH YOUR App_ID";

NOTEYou should enter the number only and not the "ID" prefix.  For example, if your App ID is id123456789 the above should appear as:

[AppsFlyerTracker sharedTracker].appleAppID = @"123456789";

Replace [Dev_Key] with your own Dev_Key (accessible from your account, under App Settings in the AppsFlyer dashboard).  

For example: a4kGpVyxm8iGgzvzT8NPaV

3.2  Adding Code

Add the following code to your AppDelegate.m source file at “applicationDidBecomeActive” function:

#import "AppsFlyerTracker.h"
-(void)applicationDidBecomeActive:(UIApplication *)application
     // Track Installs, updates & sessions(app opens) (You must include this API to enable tracking)
     [[AppsFlyerTracker sharedTracker] trackAppLaunch];

3.3  Reporting Deeplinks for Re-Targeting Attribution

If your app supports deeplinking (Universal links or Standard) or you plan to run re-targeting campaigns, you must implement the steps in section 5.7.

4.  In-App Events Tracking API (Optional)

This API enables AppsFlyer to track post install events. These events are defined by the advertiser and include an event name in addition to optional event values.

Tracking in-app events helps you measure and analyse how loyal users discover your app, and attribute them to specific campaigns/media sources. It is recommended to take the time and define the events you would like to measure to allow you to track ROI (Return on Investment) and LTV (Lifetime Value).


- (void) trackEvent:(NSString *)eventName withValues:(NSDictionary*)values

eventName is any string to define the event name.

values is a dictionary of event parameters that comprise a rich event.

Counting revenue as part of a rich in-app event: Use the ‘af_revenue” (constant)


event parameter to count revenue as part of an in-app event. You can populate it with any numeric value, positive or negative.

NOTE:  “af_price” 


is not counted as revenue and is a descriptive parameter which does not affect revenue and LTV measurements.

Example 1: Level Achieved In-App Event

[[AppsFlyerTracker sharedTracker] trackEvent: AFEventLevelAchieved withValues:@{        
    AFEventParamLevel: @9,
    AFEventParamScore : @100 }];

This generates an event of type “af_level_achieved” with the following event values:

{af_level: 9 , af_score: 100}

Example 2: Purchase Event

[[AppsFlyerTracker sharedTracker] trackEvent:AFEventPurchase withValues: @{
    AFEventParamContentType : @"category_a",
    AFEventParamRevenue: @200,

This generates an event of type “af_purchase” with the following event values:

{af_content_id: “1234567” , af_content_type: “category_a”, af_revenue: 200, af_currency: “USD”}

The purchase event above contains a $200 revenue, appearing as revenue in the dashboard.


  • An In-app event name must be no longer than 45 characters.  Events names with more than 45 characters do not appear in the dashboard, but only in the raw Data, Pull and Push APIs.
  • The number of in app events that can be defined in one app is limited to 128.

For details of the AppsFlyer Rich In-App Events for iOS, click here.

5.  Advanced Integration

The APIs below are optional and are part of the advanced integration with AppsFlyer SDK.

5.1  Set Currency Code (Optional)

You can set a global currency code using the API below, in addition to specific currency codes that can be used as part of each in-app event that is sent to AppsFlyer. The global currency code is used when “af_currency” (AFEventParamCurrency) is not sent as part of an in-app event.

USD is the default value.  Find acceptable ISO currency codes here.

Use the following API in order to set the currency code:

[AppsFlyerTracker sharedTracker].currencyCode = @"GBP";

5.2  Get AppsFlyer Unique ID (Optional)

An AppsFlyer proprietary unique ID is created for every new install of an app. AppsFlyer’s unique ID is the main ID used by AppsFlyer in the Reports and APIs.

Use the following API In order to get AppsFlyer’s unique ID:

(NSString *) [AppsFlyerTracker sharedTracker] getAppsFlyerUID

5.3  Set Customer User ID (Optional)

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

To set your customer user ID:

[AppsFlyerTracker sharedTracker].customerUserID = @"YOUR_CUSTOM_DEVICE_ID";


  • The set customer ID, must be called before the trackAppLaunch.
  • It is recommended to set your Customer User ID as soon as possible as it is only associated to events reported after setting this attribute.
  • You must set the Customer User ID using this API in order to use AppsFlyer’s integrations with Analytics platforms such as Mixpanel and Swrve.

For more information about the Customer User ID, click here.

5.4  Get Conversion Data (Optional)

AppsFlyer allows you to access the user attribution data in real time directly at the SDK level. It enables you to customize the landing page a user sees on the very first app open after a fresh app install.

For more information regarding this advanced functionality, read here.

5.5  Enabling App Extension Support (Optional)

The app extension requires permissions to use the Internet:

  1. Go to your app extension's info.plist file
  2. In the NSExtension / NSExtensionAttributes set the RequestsOpenAccess flag to YES.

On the App Extension ViewController ViewDidLoad initialize AppsFlyerLib:

[AppsFlyerTracker sharedTracker].appsFlyerDevKey = @"YOUR_DEV_KEY_HERE";
[AppsFlyerTracker sharedTracker].appleAppID = @"APP_ID_HERE"; 
[AppsFlyerTracker sharedTracker].delegate = self;
[[AppsFlyerTracker sharedTracker] trackAppLaunch];

To receive Conversion Data:

  1. Go to the App Extension ViewController.h
  2. Import Appsflyer header file
#import "AppsFlyerTracker.h"
  1. Add <AppsFlyerTrackerDelegate> on the interface declaration

On the Extension ViewController.m add the following methods:

-(void)onConversionDataReceived:(NSDictionary*) installData {
    id status = [installData objectForKey:@"af_status"];
   if([status isEqualToString:@"Non-organic"]) {     
      id sourceID = [installData objectForKey:@"media_source"];      
      id campaign = [installData objectForKey:@"campaign"];      
      NSLog(@"This is a none organic install. Media source: %@  Campaign: %@",sourceID,campaign);      
  } else if([status isEqualToString:@"Organic"]) {      
      NSLog(@"This is an organic install.");      
-(void)onConversionDataRequestFailure:(NSError *) error {  
- (void) onAppOpenAttribution:(NSDictionary*) attributionData {  
  NSLog(@"attribution data: %@", attributionData);
- (void) onAppOpenAttributionFailure:(NSError *)error {

5.6   Set User Email (Optional)

AppsFlyer enables you to report one or more of the user’s email addresses. The developer should collect the email addresses from the user and report it to AppsFlyer according to the developer’s desired encryption method. The following encryption methods are available: SHA1, SHA256, MD5 and plain.


[[AppsFlyerTracker sharedTracker] setUserEmails:@[@"", @""] withCryptType:EmailCryptTypeSHA1];

NOTE​: Personally Identifiable Information (PII) such as email addresses are ​not​ retained by AppsFlyer and this information is not presented in any reports. The purpose of collecting this information is solely for postback purposes to the media source.

5.7  Reporting Deeplinks for Re-Targeting Attribution (Optional)

Deeplinking is a crucial part of re-targeting campaigns and it is highly recommended to use when running re-targeting campaigns.

AppsFlyer enables you to report launches initiated through deeplinks including iOS Universal Links and to analyze the performance of your re-targeting attribution campaigns.

From iOS 9 and above, deeplinking is performed by Universal Links.  Therefore, you must integrate Universal Links in to your app.

Click here to see AppsFlyer's Universal Links integration guide.

To report such launches, add the following code to the app delegate:

// Reports app open from a Universal Link for iOS 9
- (BOOL) application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray *_Nullable))restorationHandler
[[AppsFlyerTracker sharedTracker] continueUserActivity:userActivity restorationHandler:restorationHandler];
return YES;
// Reports app open from deeplink for iOS 8 or below (DEPRECATED)
- (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 deeplink for iOS 10 - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
     options:(NSDictionary *) options {
[[AppsFlyerTracker sharedTracker] handleOpenUrl:url options:options];
return YES;

For more information see, OneLink Set-Up Guide.

5.8  In-App Purchase Receipt Validation (Optional)

NOTE:  This function is supported for iOS7 and above.

AppsFlyer’s SDK can provide in‐app purchase server verification. To set receipt validation tracking you need to call the validateAndTrackInAppPurchase method inside the SKStoreKit’s completeTransaction: callback. This call automatically generates an “af_purchase” in‐app event.

- (void) validateAndTrackInAppPurchase:(NSString *) productIdentifier
price:(NSString *) price
currency:(NSString *) currency
transactionId:(NSString *) tranactionId
additionalParameters:(NSDictionary *) params
success:(void (^)(NSDictionary *response)) successBlock
failure:(void (^)(NSError *error, id reponse)) failedBlock;

This call has two callback blocks, one for ‘success’ and one for ‘failure’ (for any reason, including validation fail). On success, a dictionary is returned with the receipt validation data provided by Apple’s servers.  

IMPORTANT: For testing purposes, we recommend to set the useReceiptValidationSandbox flag to YES, as this redirects the requests to Apple sandbox servers.

#ifdef DEBUG
    [AppsFlyerTracker sharedTracker].useReceiptValidationSandbox = YES;


[[AppsFlyerTracker sharedTracker] validateAndTrackInAppPurchase:product.productIdentifier price:product.price.stringValue
additionalParameters:@{@"test": @"val" , @"test1" : @"val 1"}
success:^(NSDictionary *result){
               NSLog(@"Purcahse succeeded And verified!!! response: %@", result[@"receipt"]);
} failure:^(NSError *error, id response) {
               NSLog(@"response = %@", response);

For a list of possible return values for validating receipts, please refer to Apple's documentation here.

5.9 End User Opt-Out (Optional)

AppsFlyer provides you a method to opt‐out specific users from AppsFlyer analytics. This method complies with the latest privacy requirements and complies with Facebook data and privacy policies. Default is NO, meaning tracking is enabled by default.  Use this API during the SDK initialization in Section 4 to explicitly opt-out:

[AppsFlyerTracker sharedTracker].deviceTrackingDisabled = YES;

5.10  Explicit Opt-out from ID for Advertisers – IDFA/IFA (Optional)

The AppsFlyer SDK collects IDFA only if AdSupport.framework library is included in your project. There is no need to explicitly opt‐in or opt‐out. However, if you want to explicitly opt‐out IDFA, use the following API during the SDK initialization in Section 4:

[AppsFlyerTracker sharedTracker].disableAppleAdSupportTracking = YES;

The IDFA is NOT collected to the AppsFlyer servers when the disableAppleAdSupport tracking is set to YES.

5.11 Track App Uninstalls (Optional)

AppsFlyer enables you to track app uninstalls.  Use this function to register to the uninstall feature:

Call this function:

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
Call this code in order to activate this feature.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// AppsFlyer SDK Initialization
// Register for Push Notifications
   UIUserNotificationType userNotificationTypes = (UIUserNotificationTypeAlert |
                                                   UIUserNotificationTypeBadge |
   UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:userNotificationTypes
   [application registerUserNotificationSettings:settings];
   [application registerForRemoteNotifications];
   [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
   application.applicationIconBadgeNumber = 0;

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

Usage Example

[[AppsFlyerTracker sharedTracker] registerUninstall:deviceToken];

When testing uninstalls against Apple's development environment, leave the default setting to NO of this flag:

[AppsFlyerTracker sharedTracker].useUninstallSandbox = NO;

Currently, we only support testing uninstall on TestFlight and Production.

To complete this process fully and correctly, click here.

For additional information on AppsFlyer's iOS Uninstall Tracking, click here.

NOTE:  Uninstall tracking will not be possible for users who reject Push Notification permissions.

5.12 Implementing Deeplinking with OneLink (Optional)

OneLink triggers an app to open at the deeplink location by mentioning the scheme under the af_dp parameter, or the Universal Links for iOS9.

You can implement the callback onAppOpenAttribution called by the AppsFlyer SDK.  It returns the Onelink parameters used to trigger the app open. Then, you can parse the values and apply the logic to trigger the relevant app page.

(void) onAppOpenAttribution:(NSDictionary*) attributionData; ///iOS

For more information, click here.

5.13 Push Notification Measurements (Optional)

AppsFlyer allows you to measure push notifications as part of an advertising campaign.

To integrate push notification tracking into your app, add the following code to your app’s AppDelegate.

-(void) application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
   [[AppsFlyerTracker sharedTracker] handlePushNotification:userInfo];

The push message should have an "af" parameter with AppsFlyer tracking params.

Usage Example

   "aps": {
       "alert": "Push text",
       "sound": "default",
       "category": "REMINDER_CATEGORY"
   "_p": 123456,
   "payloadKey": "payloadValue"
   "af": {
       "pid": "swrve_int",
       "is_retargeting": true,
       "c": "test_campaign"

5.14  Cross Promotion Tracking

AppsFlyer allows you to track and attribute installs originating from a cross promotion of one of your apps from within the current app the user has.  Cross promoting apps can be a major growth factor in driving additional installs for your apps.
For details, see the Cross Promotion Tracking article, here.

5.15  User Invite Tracking

AppsFlyer allows you to track and attribute installs originating from user invites within your app.  Allowing your existing users to invite their friends and contacts as new users to your app can be a key growth factor for your app. 
For details, see the User Invite Tracking article, here.

5.16  Custom Time Between Sessions

For AppsFlyer to count two separate sessions, the default time between each session must be at least 5 seconds.  A session commences when the user opens the app.  If you want to configure a different time between sessions, use the following API:
[[AppsFlyerTracker sharedTracker] setMinTimeBetweenSessions:<your custom time in seconds>];

6.  Testing the SDK Integration

6.1  Initial iOS SDK Integration Testing Using Test Page  

Testing the SDK Integration is a crucial part of the process. You can easily test the iOS SDK integration before or after submitting to the App Store by using AppsFlyer's dedicated iOS SDK Integrations Tests page.

6.2  Ongoing Tests 

Testing does not stop with a successful initial SDK Integration. 
You may want to perform further tests for tasks such as:

To do so simply use a test media source when testing tracking links, by adding pid=test to them. All subsequent results are displayed under the Test media source, and also as part of the general app's data on the dashboard.

For more information about creating custom tracking links, click here

NOTE:  It is highly recommended to use whitelisted test devices to perform either initial or ongoing tests.



Was this article helpful?
7 out of 9 found this helpful
Have more questions? Submit a request
Powered by Zendesk