Get Started – iOS

This guide shows you how to add App Events to your new or existing app by integrating the Facebook SDK then logging these events.

Changes have been made to the Facebook iOS SDK. We recommend upgrading to the new version of the Facebook iOS SDK. See the Device Consent section for more information about this change.

Step 1: Configure Your Facebook App

Go to the App Dashboard, click My Apps, and create a new app if you don't already have one. Navigate to Settings > Basic to view the App Details Panel with your App ID, your App Secret, and other details about your app.

Scroll down to the bottom of page, and click Add Platform. Choose iOS, add your app details, and save your changes.

Set up your app for advertising by adding the following details:

  • App Domains - Provide Apple App Store URL of your app.
  • Privacy Policy URL - Provide a Privacy Policy URL. Required to take your app public.
  • Terms of Service URL - Provide a Terms of Service URL.
  • Platform - Scroll to the bottom of the Settings panel to add the iOS Platform.

To learn more about adding details to your app, such as an icon or category, visit the App Development docs.

Step 2: Link your Ad Account

To run ads and measure installs in the Ads Manager, associate at least one Ad Account with your App.

  1. In the App Dashboard click Settings > Advanced.
  2. In Authorized Ad Account IDs, add your Ad Account IDs. You can get your ad account IDs from your Ads Manager.
  3. If you also have a business account, in Authorized Businesses, add your Business Manager ID. You can find your Business Manager id in the URL of your Business Manager

Step 3: Set Up Your Development Environment

The following procedure uses Swift Package Manager to set up your development environment in xCode.

Only available for Xcode 11.2 and forward

  1. In Xcode, click File > Swift Packages > Add Package Dependency.
  2. In the dialog that appears, enter the repository URL: https://github.com/facebook/facebook-ios-sdk.
  3. In Version, select Up to Next Major and take the default option.
  4. Complete the prompts to select the libraries you'd like to use in your project.
  5. To use the Objective-C interface exclusively, import the 'FBSDK'-prefixed module.
    Example: import FBSDKCoreKit
    To use the enhanced Swift interface in your code, import the 'Facebook'-prefixed module.
    Example: import FacebookCore

Step 4: Register and Configure Your App with Facebook

Add Your Bundle Identifier and enable Single Sign-On for your app.

The bundle identifier (Bundle ID) should appear in the box below. If the box is empty, find your bundle identifier in your Xcode Project's iOS Application Target and paste it into the box below.
Bundle ID
You can change your bundle identifier in the future via the iOS section on the settings page.
Enable Single Sign On
Enable single sign on for your app by setting Single Sign On to Yes below.
Single Sign On Will launch from iOS Notifications

Step 5: Configure Your Project

Configure the Info.plist file with an XML snippet that contains data about your app.
  1. Right-click Info.plist, and choose Open As ▸ Source Code.
  2. Copy and paste the following XML snippet into the body of your file ( <dict>...</dict>).
    <key>CFBundleURLTypes</key>
    <array>
      <dict>
      <key>CFBundleURLSchemes</key>
      <array>
        <string>fb[APP_ID]</string>
      </array>
      </dict>
    </array>
    <key>FacebookAppID</key>
    <string>[APP_ID]</string>
    <key>FacebookDisplayName</key>
    <string>[APP_NAME]</string>
  3. In <array><string> in the key [CFBundleURLSchemes], replace [APP_ID] with your App ID.
  4. In <string> in the key FacebookAppID, replace [APP_ID] with your App ID.
  5. In <string> in the key FacebookDisplayName, replace [APP_NAME] with the name of your app.
  6. To use any of the Facebook dialogs (e.g., Login, Share, App Invites, etc.) that can perform an app switch to Facebook apps, your application's Info.plist also needs to include: <dict>...</dict>).
    <key>LSApplicationQueriesSchemes</key>
    <array>
      <string>fbapi</string>
      <string>fbapi20130214</string>
      <string>fbapi20130410</string>
      <string>fbapi20130702</string>
      <string>fbapi20131010</string>
      <string>fbapi20131219</string>
      <string>fbapi20140410</string>
      <string>fbapi20140116</string>
      <string>fbapi20150313</string>
      <string>fbapi20150629</string>
      <string>fbapi20160328</string>
      <string>fbauth</string>
      <string>fb-messenger-share-api</string>
      <string>fbauth2</string>
      <string>fbshareextension</string>
    </array>

Step 6: Connect Your App Delegate and Scene Delegate

Upon initialization, the SDK will perform various network calls to fetch configuration information. If you would like to defer these operations you may want to wrap initialization in a method that can conditionally run code based on a server response. There are a number of ways to do this. The following code block is pseudocode to demonstrate what a potential solution might look like.
FlagFetcher.fetchFlags { result in
    if case let .success(flags) = result,
      flags.contains("use_facebook") {
        // Initialize the SDK
        ApplicationDelegate.shared.application(
            application,
            didFinishLaunchingWithOptions: launchOptions
        )			
    }
}      
    
Replace the code in the AppDelegate method with the following code. This code initializes the SDK when your app launches, and allows the SDK handle results from the native Facebook app when you perform a Login or Share action.

Swift

    
// Swift
//
// AppDelegate.swift
import UIKit
import FBSDKCoreKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
          
        ApplicationDelegate.shared.application(
            application,
            didFinishLaunchingWithOptions: launchOptions
        )

        return true
    }
          
    func application(
        _ app: UIApplication,
        open url: URL,
        options: [UIApplication.OpenURLOptionsKey : Any] = [:]
    ) -> Bool {

        ApplicationDelegate.shared.application(
            app,
            open: url,
            sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
            annotation: options[UIApplication.OpenURLOptionsKey.annotation]
        )

    }  

}
    

Objective C

// Objective-C
//
// AppDelegate.m  
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  
  [[FBSDKApplicationDelegate sharedInstance] application:application
                           didFinishLaunchingWithOptions:launchOptions];
  return YES;
}


- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
            options:(nonnull NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options
{
  [[FBSDKApplicationDelegate sharedInstance] application:application
                                                 openURL:url
                                                 options:options];
  return YES;
}
    

iOS 13 moved opening URL functionality to the SceneDelegate. If you are using iOS 13, add the following method to your SceneDelegate so that operations like logging in or sharing function as intended:

Swift

// Swift
//
// SceneDelegate.swift
import FBSDKCoreKit
  ...
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
    guard let url = URLContexts.first?.url else {
        return
    }

    ApplicationDelegate.shared.application(
        UIApplication.shared,
        open: url,
        sourceApplication: nil,
        annotation: [UIApplication.OpenURLOptionsKey.annotation]
    )
}

    

Objective C

// Objective-C
//
// SceneDelegate.m
#import <FBSDKCoreKit/FBSDKCoreKit.h>

@import FacebookCore;

@interface SceneDelegate ()

@end

@implementation SceneDelegate

- (void)scene:(UIScene *)scene openURLContexts:(NSSet<UIOpenURLContext *> *)URLContexts
{
  UIOpenURLContext *context = URLContexts.allObjects.firstObject;
  [FBSDKApplicationDelegate.sharedInstance application:UIApplication.sharedApplication
                                               openURL:context.URL
                                     sourceApplication:context.options.sourceApplication
                                            annotation:context.options.annotation];
}
    

Step 7: Add App Events

There are three ways events are tracked in your app:

App Store Connect for iOS 14

Events that your app collects and sends to Facebook may require you to disclosed these data types in the App Store Connect questionnaire. It is your responsibility to ensure this is reflected in your application’s privacy policy. Visit the Apple App Store Privacy Details article to learn more about the data types you will need to disclose.

Automatically Logged Events

When using the Facebook SDK, certain events in your app are automatically logged and collected for Facebook Analytics unless you disable automatic event logging. These events are relevant for all use cases - targeting, measurement and optimization.

There are three key events collected as part of the Automatic App Event Logging: App Install, App Launch, and Purchase. When automatic logging is enabled, advertisers are able to disable these events, as well as other Facebook internal events such as login impression events. However, if you have disabled automatic logging, but still want to log specific events, such as install or purchase events, manually implement logging for these events in your app.

EventDetails

App Install

The first time a new user activates an app or the first time an app starts on a particular device.

App Launch

When a person launches your app, the Facebook SDK is initialized and the event is logged. However, if a second app launch event occurs within 60 seconds of the first, the second app launch event is not logged.

In-App Purchase

When a purchase processed by the Apple App Store or Google Play has been completed. If you use other payments platforms, you will need to add purchase event code manually.

Facebook SDK Crash Report

(For Facebook Use Only.)

If your app crashed due to the Facebook SDK, a crash report is generated and sent to Facebook when your app is restarted. This report contains no user data and helps Facebook ensure the quality and stability of the SDK. To opt out of logging this event, disable automatically logged events.

Caveats

These instructions are for version 4.0 and higher of the SDK. If you are still using version 3.X, omit "SDK" from your App Event calls. For example, you would use FBAppEvents instead of FBSDKAppEvents.

If you are using Swift, please refer to App Events with the Facebook SDK for Swift.

In-app purchase logging is automatically enabled for apps that have installed or upgraded to v4.39. For apps running an earlier version, enable in-app purchase events in Basic > Settings iOS card in the app dashboard or add the purchase event code manually.

Get Device Consent

Starting with iOS 14.5, you will need to set AdvertiserTrackingEnabled and log each time you give a device permission to share data with Facebook. If a device provides consent, call the setAdvertiserTrackingEnabled method of the FBSDKSettings class and set it to YES for Objective-C or true for Swift. If a device does not allow tracking, set setAdvertiserTrackingEnabled to NO for Objective-C or false for Swift. The method will return a boolean value to indicate whether the method is set successfully or not.

Allow Advertiser Tracking


// Set AdvertiserTrackingEnabled to YES if a device provides consent
[FBSDKSettings setAdvertiserTrackingEnabled:YES];
// Set AdvertiserTrackingEnabled to true if a device provides consent
Settings.setAdvertiserTrackingEnabled(true)
// Set AdvertiserTrackingEnabled to true if a device provides consent
FB.Mobile.SetAdvertiserTrackingEnabled(true)

Do Not Allow Advertiser Tracking


// Set AdvertiserTrackingEnabled to NO if a device does not provide consent
[FBSDKSettings setAdvertiserTrackingEnabled:NO];
// Set AdvertiserTrackingEnabled to false if a device does not provide consent
Settings.setAdvertiserTrackingEnabled(false)
// Set AdvertiserTrackingEnabled to false if a device does not provide consent
FB.Mobile.SetAdvertiserTrackingEnabled(false)

Disable Automatically Logged Events

To disable automatic event logging, open the application's .plist as code in Xcode and add the following XML to the property dictionary:

<key>FacebookAutoLogAppEventsEnabled</key>
<false/>

In some cases, you want to delay the collection of automatically logged events, such as to obtain User consent or fulfill legal obligations, instead of disable it. In this case, call the setAutoLogAppEventsEnabled method of the FBSDKSettings class to re-enable auto-logging after the end-user provides consent.

[FBSDKSettings setAutoLogAppEventsEnabled:YES];
FBSDKSettings.setAutoLogAppEventsEnabled(true)

To suspend collection again for any reasons, set the setAutoLogAppEventsEnabled method to NO for iOS or false for Swift.

[FBSDKSettings setAutoLogAppEventsEnabled:NO];
FBSDKSettings.setAutoLogAppEventsEnabled(false)

You can also disable automatic In-App Purchase event logging using the app dashboard. Go to the iOS card under Basic>Settings and toggle the switch to No.

Disable Collection of Advertiser IDs

To disable collection of advertiser-id, open the application's .plist as code in Xcode and add the following XML to the property dictionary:

<key>FacebookAdvertiserIDCollectionEnabled</key>
<false/>

In some cases, you want to delay the collection of advertiser_id, such as to obtain User consent or fulfill legal obligations, instead of disabling it. In this case, call the setAdvertiserIDCollectionEnabled method of the FBSDKSettings class and set it to YES for iOS or true for Swift after the end-user provides consent.

[FBSDKSettings setAdvertiserIDCollectionEnabled:@YES];
FBSDKSettings.setAdvertiserIDCollectionEnabled(true);

To suspend collection for any reason, set the setAdvertiserIDCollectionEnabled method to NO for iOS or false for Swift.

[FBSDKSettings setAdvertiserIDCollectionEnabled:@NO];
FBSDKSettings.setAdvertiserIDCollectionEnabled(false)

Manually Log Events

Get Code

Use the Code Generator to get code for standard events or custom events, and parameters.

To Generate Code for a Standard or Custom Event

  1. Choose the tab of the type of event code you want, Standard Event or Custom Event.
  2. In Event Name, enter the name of your event.
  3. Click Add Event Paramater if you would like to add parameters to your custom event.
  4. Click Get Code.
  5. In the window, select a language to get the code to copy and paste into your app.

To log a custom event, just pass the name of the event as an NSString:

[FBSDKAppEvents logEvent:@"battledAnOrc"];

Event Parameters

Facebook has created a set of useful event parameters for inclusion with standard events or with your own custom events. You can also provide your own parameters.

These pre-defined parameters are intended to provide guidance on common logging patterns, and may have a more readable form in reporting and other UIs. Log the set of parameters you're interested in seeing broken down in Analytics. The recommended description for these are guidance only - you can use these parameters for whatever makes sense for your app.

The parameters are passed via an NSDictionary where the key holds the parameter name as an NSString (iOS SDK constants for the pre-defined ones are listed below), and the value must be either an NSString or an NSNumber.

Step 8: Test Your Events

The App Ads Helper allows you to test the app events in your app to ensure that your app is sending events to Facebook.

  1. Open the App Ads Helper.
  2. In Select an App, choose your app and choose Submit.
  3. Scroll the bottom and choose Test Event.
  4. Start your app and send an event. The event should appear page.

Learn More

  • Best Practices Guide - View a wide variety of sample apps and how each handles App Events.
  • FAQ - Check out our Frequently Asked Questions.

Example Apps

We have created some examples for different app types to make it easier for you to see how you can use app events. Each of the example apps provides a screen by screen breakdown of the different events and parameters that can be collected. At the end of each section, there is a table listing the recommended events and parameters for each app. And, if necessary, you can create your own events and parameters.