AppsFlyer SDK Integration - iOS

ios.pngSDK Version: 4.8.2 (Release notes)

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

2.1 Download and add AppsFlyer's SDK to Xcode

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 collect the IDFA from devices.
Without IDFA you cannot track Facebook Ads, Twitter, Google ads and other networks.
iAd.framework
This framework is required to track Apple Search Ads in your app

2.2 Configure Integration in App Delegate

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

Swift Objective-C
import AppsFlyerLib

3. SDK Initialization

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().delegate = self
#ifdef DEBUG
AppsFlyerTracker.shared().isDebug = true
#endif

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

4. Tracking 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 Deep Linking

 Tip

We highly recommend having deep linking 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 deep link 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 deep link for iOS 10 or later
    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        AppsFlyerTracker.shared().handleOpen(url, options: options)
        return true
    }

6. 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"
    ]);

7. Get Conversion Data

AppsFlyer allows you to access the user attribution data in real-time for every new install, directly from the SDK level. By doing this you can serve users with personalized content or send them to specific activities within the app, which can greatly enhance their engagement with your app. 

For more information regarding this advanced functionality, click here.

8. User Identifiers

There are a number of options for retrieving user identifiers:

Get AppsFlyer Device ID

AppsFlyer's unique device 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()
Set Customer User ID

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 Postback APIs for cross-referencing with your internal IDs.

To set your Customer User ID:

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

 Important Note

The customerUserID SHOULD 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 its setup. Customer User ID can also be used to complete integrations with Analytics platforms such as Mixpanel and Swrve.

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

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

IDFA and IDFV

AppsFlyer automatically collects the IDFA (ID For Advertisers) and IDFV (ID For Vendors) if AdSupport.framework is included in the app.

9. Optional Features

Track Uninstalls

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

Follow the iOS SDK integration instructions to complete the uninstall feature setup.

Tracking Push Notifications

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: [AnyHashable : Any]) {
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.
Set Currency Code
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 sent to AppsFlyer. The global currency code is used when AFEventParamCurrency is not sent as part of an in-app event.

USD is the default value. You can find acceptable ISO currency codes here.

Use the following API to set the currency code:

public void currencyCode(String currencyCode);

Usage Example:

Swift Objective-C
AppsFlyerTracker.shared().currencyCode = "USD"
In-App Purchase 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;

 Note

The price parameter should contain the total revenue associated to the validated purchase event.


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.

 Warning

Opting out users SEVERELY hurts your attribution information.
Use this option ONLY for regions which legally prevent you from collecting your users' information.
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>
Background Sessions for Utility Apps
Unavailable in iOS. 
 
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.

10. Testing Your Integration

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

11. 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 11 found this helpful

Comments

0 comments

Please sign in to leave a comment.