AppsFlyer SDK Integration - iOS

  • Advertisers
  • Developers

ios.pngSDK Version: 4.8.10(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.

 Important!

AppsFlyer's SDK makes use of NSUserDefaults class. Clearing all values from NSUserDefaults may cause attribution issues.

 Tip

  • Chapters 2 and 3 are MANDATORY to implement BASIC SDK integration, i.e. install attribution only
  • Tracking in-app events chapter is HIGHLY RECOMMENDED to implement
  • The rest of the described features are OPTIONAL to implement, although some of them may be necessary for you, depending on your app's business logic. For example, tracking revenue or getting the conversion data on first launch may be vital for your app's flow

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

Note that you need to set the app ID here with digits only, without the "id" prefix.

Swift Objective-C
AppsFlyerTracker.shared().appsFlyerDevKey = "<your-appsflyer-dev-key>";
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: Purchase In-App Event

Swift Objective-C
AppsFlyerTracker.shared().trackEvent(AFEventPurchase,
    withValues: [
         AFEventParamRevenue: "1200",
         AFEventParamContent: "shoes",
         AFEventParamContentId: "123"
]);

This generates an af_purchase event type (using the AFEventPurchase constant) with the following event values: {af_revenue: 200 , af_currency: "USD", af_quantity: 2, af_content_id: "092" af_receipt_id: "9277"} 

 Note

AppsFlyer supports non-English characters with in-app events, or with any other SDK API, starting from iOS SDK version 4.8.1.

Do not add any currency symbol or decimal points to the figures, as these are not recognized

 Usage Example

Swift Objective C
AppsFlyerTracker.shared().trackEvent(AFEventPurchase,
withValues: [
    AFEventParamRevenue: @1200,
    AFEventParamCurrency : @"JPY"
]); 

5. Tracking Deep Linking

 Tip

We highly recommend having deep linking integrated in your app.  Deep Linking is a crucial part of retargeting campaigns and it is highly recommended to use when running retargeting campaigns.

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


To handle deep linking, add the following code in your app (in the app delegate class). The methods in this code allow you to get deep linking data. With deep linking data you can redirect users to the relevant app activity and serve them with the relevant content.

Swift Objective-C

 func onConversionDataReceived(_ installData: [AnyHashable: Any]) {
    //Handle Conversion Data (Deferred Deep Link)
    }
    
    func onConversionDataRequestFailure(_ error: Error?) {
        //        print("\(error)")
    }
    
    func onAppOpenAttribution(_ attributionData: [AnyHashable: Any]) {
        //Handle Deep Link Data
        
    }
    
    func onAppOpenAttributionFailure(_ error: Error?) {
    }
// 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
    }
   

 Important!

For Swift 4.2 and above, use the following code for the continue userActivity method:

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
	AppsFlyerTracker.shared().continue(userActivity, restorationHandler: nil)
	return true
}

6. Tracking Revenue

Use the af_revenue (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(AFEventPurchase, 
withValues: [
	AFEventParamContentId:"1234567",
	AFEventParamContentType : "category_a",
	AFEventParamRevenue: 1.99,
	AFEventParamCurrency:"USD"
]);

 Important!

Do NOT format the revenue value in any way. It should not contain comma separators, currency sign, or text. A revenue event should be similar to 1234.56, for example.

Tracking Negative Revenue

If you need to track negative revenue for example when a user cancels a purchase or receives a refund, you can send negative revenue.

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

 Note

Notice the following in the code above:

  1. The revenue value is preceded by a minus sign
  2. The event name has a unique value of "cancel_purchase" - to allow you to identify negative revenue events in the dashboard and raw data reports

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

It is recommended to set your Customer User ID as soon as possible as it is only associated to events reported after its setup. If setCustomerUserId is called before calling trackAppLaunch, the Customer User ID is visible in the raw export for installs and for events. If it is set after, only the value for events tracked is visible after calling this method.

Customer User ID can also be used to complete integrations with Analytics platforms such as Mixpanel and Swrve.

Getting Customer User ID:

To get the customer user ID retrieve it from the sharedTracker.

[AppsFlyerTracker sharedTracker].customerUserID

 Important!

Make sure to set the customer user ID each time the app is launched, before calling trackAppLaunch</code.

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

Measure Uninstalls

For Uninstall measurement, 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 measurement 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

Objective-C Swift
[[AppsFlyerTracker sharedTracker] validateAndTrackInAppPurchase:product.productIdentifier price:product.price.stringValue
currency:@"USD"
transactionId:trans.transactionIdentifier
additionalParameters:@{@"test": @"val" , @"test1" : @"val 1"}
success:^(NSDictionary *result){
  NSLog(@"Purchase 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.

Anonymize

AppsFlyer provides you with a method to annonymize specific user identifiers in AppsFlyer analytics. This method complies with the latest privacy requirements and complies with Facebook data and privacy policies. Default is NO, meaning no anonymization is performed by default.

Use this API during the SDK Initialization to explicitly anonymize 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

Anonymizing users SEVERELY impacts your attribution information.
Use this option ONLY for regions which legally prevent you from collecting your users' information.

Custom Time Between Sessions

By default, at least 5 seconds must lapse between 2 app launches to count as separate 2 sessions (more about counting sessions). 
However, you can use the following API to set your custom value for the minimum required time between sessions:

Swift Objective-C
AppsFlyerTracker.shared().minTimeBetweenSessions = <your_custom_time_in_seconds>

Note that setting a high value to the custom time between launches may badly impact APIs relying on sessions data, such as deep linking.

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.

Opt-Out

In some extreme cases you might want to shut down all SDK tracking due to legal and privacy compliance. This can be achieved with the isStopTracking API. Once this API is invoked, our SDK no longer communicates with our servers and stops functioning.

There are several different scenarios for user opt-out. We highly recommend following the exact instructions for the scenario, that is relevant for your app.

 Warning

Use this API only in cases where you want to fully ignore this user from any and all tracking. Using this API SEVERELY impacts your attribution, data collection and deep linking mechanism.

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

 Important

Do not call trackAppLaunch if isStopTracking is set to true

Collect Device Name

AppsFlyer SDK allows you to collect Device Name for your internal analysis. By default, this capability is turned off. To turn it on use the following API:

Swift Objective-C
>AppsFlyerTracker.shared().shouldCollectDeviceName = false`

 Important

Device Name might be considered Personal Data in certain regions. Only collect this information if you know you are legally allowed to and have received the user's explicit consent to do so.

Setting Additional Custom Data

The setAdditionalData API is required to integrate on the SDK level with several external partner platforms, including Segment, Adobe and Urban Airship. Use this API only if the integration article of the platform specifically states setAdditionalData API is needed.
The following is a code example for implementing setAdditionalData on iOS for Objective-C or Swift

Objective-C Swift
NSDictionary* CustomDataMap = [[NSDictionary alloc] initWithObjectsAndKeys:@"value_of_param_1", @"custom_param_1", nil];
    
[[AppsFlyerTracker sharedTracker] setAdditionalData:CustomDataMap];

10. Testing Your Integration

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

Now you can start tracking the media sources you work with.

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 12 found this helpful

Comments

5 comments
  • We are pleased to announce the release of iOS SDK Integration Guide v. 4.8.4.

    This version includes bug fixes and maintenance.

  • Hi everybody.
    We have just fixed an SSL issue we had with 2 iOS SDK download links.
    If you haven't done so already, we highly recommend updating to the latest iOS SDK version 4.8.4.

  • Hi all.
    We have released AppsFlyer's iOS SDK version 4.8.5, which contains some scheduled periodic bug fixes and maintenance.
    If you haven't updated the SDK in over 3 months, we strongly recommend doing so now, to also be compliant with GDPR requirements.

  • Hi Everyone,

    An updated iOS SDK has been released. Version 4.8.6 fixes a crash when calling NSUserDefaults on a background thread.

    If you haven't done so already, we highly recommend updating to the latest iOS SDK version.

  • Hello Everyone,

    We're happy to announce the release of iOS SDK version 4.8.9.

    This new version SDK support 4 new events:
    Subscribe, Start Trial, Ad Click, Ad View

    In addition, standard events have been mapped for future support of Facebook's enhanced Ad Event Optimization.

Please sign in to leave a comment.