AppsFlyer SDK Integration - iOS

Current Version: 4.8.1

1. Overview

This guide details how to integrate AppsFlyer's SDK into your iOS app. You can track installs, updates, sessions and additional in-app events as well as app installs (including in-app purchases, game levels, etc.) to evaluate ROI and user engagement levels. The iOS SDK is compatible with all iOS devices (iPhone, iPod, iPad) with iOS version 6 and above.

 Note

  • 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 all values from NSUserDefaults may cause attribution issues.

2. Quick Start

Downloading and adding AppsFlyer's SDK to your Xcode project:

CocoaPods Carthage Static Framework Static Lib
  • Make sure you have downloaded and installed the latest version of CocoaPods.
  • Add the following row to your Podfile:
    pod 'AppsFlyerFramework'
  • run pod install
  • Make sure you use the .xcworkspace file to open your project in Xcode, instead of the .xcodeproj file, from here on out.

AppsFlyer's SDK uses the following native frameworks:

AdSupport.framework
This framework is required to track Facebook Ads, Twitter, Google ads and other networks.
iAd.framework
This framework is required to track Apple Search Ads in your app

2.1 Configuring your AppsFlyer integration in your App Delegate

Open your app's AppDelegate.m file and import AppsFlyer's SDK:

Swift Objective-C
import AppsFlyerLib
  • Initialize the SDK in the didFinishLaunchingWithOptions method with your app ID taken from iTunes Connect and your AppsFlyer dev key:
Swift Objective-C
AppsFlyerTracker.shared().appsFlyerDevKey = "aSikdJAsaAJS123ad23"
AppsFlyerTracker.shared().appleAppID = "123456789"
AppsFlyerTracker.shared().isDebug = true
AppsFlyerTracker.shared().delegate = self

 Note

If isDebug=true is set, AppsFlyer SDK logs are shown in the xCode Console

 

  • Add the following code at the applicationDidBecomeActive function:
Swift Objective-C
func applicationDidBecomeActive(application: UIApplication) { 
                    // Track Installs, updates & sessions(app opens) (You must include this API to enable tracking) 
                   AppsFlyerTracker.shared().trackAppLaunch() 
                   // your other code here.... }

3. Tracking Deeplinking

 Tip

We highly recommend having deeplinking integrated in your app.

iOS9 and above requires your app to support Universal Links. For more details, click here.


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

Swift Objective-C
// Reports app open from a Universal Link for iOS 9 or later
    func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
        AppsFlyerTracker.shared().continue(userActivity, restorationHandler: restorationHandler)
        return true
    }

    // Reports app open from deeplink from apps which do not support Universal Links (Twitter) and for iOS8 and below
    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        AppsFlyerTracker.shared().handleOpen(url, sourceApplication: sourceApplication, withAnnotation: annotation)
        return true
    }

    // Reports app open from deeplink for iOS 10 or later
    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        AppsFlyerTracker.shared().handleOpen(url, options: options)
        return true
    }

4. In-App Events

In-App Events provide insights on what is happening in your app. It is recommended to take the time and define the events you want to measure to allow you to track ROI (Return on Investment) and LTV (Lifetime Value).

Tracking in app events is performed by calling trackEvent with event name and value parameters. See In App Events for more details.

An in-app event name must not be longer than 45 characters. Event names with more than 45 characters do not appear in the dashboard, but only in the raw Data, Pull and Push APIs.

Example: Level Achieved In-App Event

Swift Objective-C
AppsFlyerTracker.shared().trackEvent(AFEventLevelAchieved, withValues: [ 
AFEventParamLevel: 9,
AFEventParamScore : 100
]);

This generates an af_level_achieved event type (using the AFEventLevelAchieved constant) with the following event values: {af_level: 9 , af_score: 100}

5. Tracking Revenue

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

 Note

AFEventParamRevenue (equivalent to using af_revenue) is the ONLY event parameter that is counted on AppsFlyer as real revenue on the raw data and dashboard. For more details please click here.


Example: Revenue In-App Event

Swift Objective-C
AppsFlyerTracker.shared().trackEvent(AFEventLevelAchieved, withValues: [
        AFEventParamContentId:"1234567",
        AFEventParamContentType : "category_a",
        AFEventParamRevenue: 1.99,
        AFEventParamCurrency:"USD"
    ]);

6. Get Attribution Data

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

For more information regarding this advanced functionality, click here.

7. User Identifiers

There are a number of options for retrieving user identifiers:

Getting AppsFlyer User ID

AppsFlyer's Unique User ID is created for every new install of an app. You can obtain it using the following code:

Swift Objective-C
let appsflyerId = AppsFlyerTracker.shared().getAppsFlyerUID()
Setting Customer User ID

If your app has its own User ID to track users with, you can use customerUserID:

Swift Objective-C
AppsFlyerTracker.shared().customerUserID = "my user id"

 Important Note

The customerUserID must be set 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.

Collecting User Email

AppsFlyer enables you to report one or more of the user’s email addresses, if you collect them in your app. The email values can be encrypted by following encryption methods: Sha1, MD5 and plain.

Example: Collecting User Email

Swift Objective-C
AppsFlyerTracker.shared().setUserEmails( ["email1@domain.com", "email2@domain.com"], with: EmailCryptTypeSHA1)

 Note

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

8.  Optional Features

In-App Purchase Receipt Validation

 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;
#endif

 

 

Example

[[AppsFlyerTracker sharedTracker] validateAndTrackInAppPurchase:product.productIdentifier price:product.price.stringValue
currency:@"USD"
transactionId:trans.transactionIdentifier
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.

Opt Out

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 to explicitly opt-out of tracking a user's installs, events and sessions:

Swift Objective-C
AppsFlyerTracker.shared().deviceTrackingDisabled = true

Tracking can be restarted by calling deviceTrackingDisabled again set to false.

Tracking Uninstalls

For Uninstall Tracking, enable remote push notification on your app. See Apple's Remote Notification Programming Guide for more details.

Add the following code to your AppDelegate.m:

Swift Objective-C
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // The userNotificationTypes below is just an example and may be changed depending on the app
        let pushSettings: UIRemoteNotificationSettings = 
                                UIRemote NotificationSettings(forTypes: 
                                               UIUserNotificationType.Alert | 
                                               UIUserNotificationType.Badge | 
                                               UIUserNotificationType.Sound,
                                               categories: nil)
    
        UIApplication.sharedApplication().registerForRemoteNotificationSettings(pushSettings)
        UIApplication.sharedApplication().registerForRemoteNotifications()
        // if you do not use push notificaiton in your app, uncomment the following line
        //UIApplication.sharedApplication().applicationIconBadgeNumber = 0

        return true
    }
        func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        AppsFlyerTracker.shared().registerUninstall(deviceToken)
    }
Tracking Push Launches

To enable Tracking App Launches from push notifications, add the following code to your app delegate:

Swift Objective-C
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
        AppsFlyerTracker.shared().handlePushNotification(userInfo)
    }

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

Message Example:

{
"aps": {
"alert": "Push text",
"sound": "default",
"category": "REMINDER_CATEGORY"
},
"_p": 123456,
"payloadKey": "payloadValue"
"af": {
"pid": "swrve_int",
"is_retargeting": true,
"c": "test_campaign"
}
}
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.

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.
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:

Swift Objective-C
AppsFlyerTracker.shared().minTimeBetweenSessions = <your_custom_time_in_seconds>
iOS App Extensions and WatchKit

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.

Add the following code to the app extension's UIViewController viewDidLoad:

Swift Objective-C
override func viewDidLoad() {    
        super.viewDidLoad()
        AppsFlyerTracker.shared().appsFlyerDevKey = "MY_APPSFLYER_KEY"

        // MY_APP_ID below stands for you app ID on iTunes Connect. Should be 9 or 10 digits.
        AppsFlyerTracker.shared().appleAppID = "MY_APP_ID"
                
        AppsFlyerTracker.sharedTracker().trackAppLaunch()
    }

To receive attribution data on the app extension, follow the instructions here and implement it on the UIViewController of your app instead of in the AppDelegate.

9. Testing Your Integration

For details on how to test your integration, click here.

10. Submitting App to App Store

You can find the instructions on submitting your app to the App Store here.

Was this article helpful?
8 out of 10 found this helpful