# Get Started with App Events on 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.
**Success:** 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 ](#get-device-consent) for more information about this change.
## Before You Start
You will need:
- A [Facebook Developer Account](https://developers.facebook.com/apps)
- A [Facebook Ad Account](https://adsmanager.facebook.com/)
- A [Facebook Business Portfolio](https://business.facebook.com/)(create a new business portfolio if you don’t already have one)
- A [Facebook app](https://developers.facebook.com/docs/apps)
## Step 1: Configure Your Facebook App
Go to the [App Dashboard](https://developers.facebook.com/apps), 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 the 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](https://en.wikipedia.org/wiki/Privacy_policy) URL. *Required to take your app public.*
- **Terms of Service URL** - Provide a [Terms of Service](https://en.wikipedia.org/wiki/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](https://developers.facebook.com/docs/apps/register#app-settings).
## Step 2: Link your ad and business portfolios
To run ads and measure installs in the [Ads Manager](https://www.facebook.com/ads/manager), associate at least one [ad account](https://www.facebook.com/ads/manager/accounts/) and a [business portfolio](https://business.facebook.com/) with your App.
- In the [App Dashboard](https://developers.facebook.com/apps/) click **Settings > Advanced**.
- In **Authorized Ad Account IDs**, add your Ad Account IDs. You can get your ad account IDs from your [Ads Manager](https://www.facebook.com/ads/manager/accounts/).
- In the **Advertising Accounts** Panel, click **Get Started** and follow the instructions to connect the app to a Business.
## Step 3: Set Up Your Development Environment
The following procedure uses Swift Package Manager to set up your development environment in Xcode.
- In Xcode, click **File > Add Packages...**.
- In the search field that appears, enter the repository URL: [https://github.com/facebook/facebook-ios-sdk](https://github.com/facebook/facebook-ios-sdk).
- In **Dependency Rule**, select **Up to Next Major Version** and enter a recent version. The most current release is listed at [https://github.com/facebook/facebook-ios-sdk/releases/](https://github.com/facebook/facebook-ios-sdk/releases/)
- Choose the libraries you intend to use and the targets to which you want to add those libraries.
- Click on **Add Package** to complete your setup.
## Step 4: Register and Configure Your App with Facebook
1. In the App Dashboard under **App settings > Basic** scrolldown and click **+ Add platform**.
2. Scrolldown to the **iOS** card and add your Bundle ID. Find your bundle identifier in your Xcode Project's iOS Application Target. You can update your Bundle ID at any time.
## Step 5: Configure Your Project
Configure the `Info.plist` file with an XML snippet that contains data about your app.
- Right-click `Info.plist`, and choose **Open As ▸ Source Code**.
- 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>fbAPP-ID</string>
</array>
</dict>
</array>
<key>FacebookAppID</key>
<string>APP-ID</string>
<key>FacebookClientToken</key>
<string>CLIENT-TOKEN</string>
<key>FacebookDisplayName</key>
<string>APP-NAME</string>
```
- In `<array><string>` in the key `[CFBundleURLSchemes]`, replace *APP-ID* with your App ID.
- In `<string>` in the key `FacebookAppID`, replace *APP-ID* with your App ID.
- In `<string>` in the key `FacebookClientToken`, replace *CLIENT-TOKEN* with the value found under **Settings** > **Advanced** > **Client Token** in your App Dashboard.
- In `<string>` in the key `FacebookDisplayName`, replace *APP-NAME* with the name of your app.
- 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 the following:
```
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fb-messenger-share-api</string>
</array>
```
Your project will need to include the Keychain Sharing capability in order for login to work in Mac Catalyst applications.
- Select the **+ Capability** button in the **Signing & Capabilities** tab when configuring your app target.
- Find and select the **Keychain Sharing** capability.
- Ensure that the **Keychain Sharing** capability is listed for the target.
## Step 6: Connect Your App Delegate and Scene Delegate
Replace the code in `AppDelegate.swift` method with the following code. This code initializes the SDK when your app launches, and allows the SDK to handle logins and sharing from the native Facebook app when you perform a Login or Share action. Otherwise, the user must be logged into Facebook to use the in-app browser to login.
```
// 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]
)
}
}
```
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:
```
// 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]
)
}
```
## Step 7: Add App Events
There are three ways events are tracked in your app:
- [Automatically Logged Events](#auto-events) - App installs, launches, and in-app purchases are automatically logged with the Facebook SDK.
- The [Codeless App Events tool](https://developers.facebook.com/documentation/app-events/codeless-app-events#ios) - Use this tool to add Standard Events without adding code to your app.
- [Manually Logged Events](#manually-log-events) - Add code to your app to track Standard and Custom Events.
### Automatically Logged Events {#auto-events}
When using the Facebook SDK, certain events in your app are automatically logged and collected for Facebook Events Manager 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.
| Event | Details |
| --- | --- |
| 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.<br><br>Note: If you’d like to use in-app purchases to measure [Dynamic Ads](https://www.facebook.com/business/m/one-sheeters/dynamic-ads) conversions, please set the Product ID on the Apple App Store or the Google Play store to be equivalent to the Product ID used in the associated Dynamic Ad. |
| 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](#disable-auto-events). |
### In-App Purchase Automatically Logged Events
Apple provides four different In-app purchase types: consumable, non-consumable, auto-renewable subscription, and non-renewing subscription. If you implement In-App Purchases with StoreKit 1, we will automatically log each of these In-app purchase types. If you implement In-App Purchases with StoreKit 2, we will automatically log non-consumables, auto-renewable subscriptions, and non-renewing subscriptions. If you would like to also automatically log consumables, you will need to add the [SKIncludeConsumableInAppPurchaseHistory](https://developer.apple.com/documentation/bundleresources/information_property_list/skincludeconsumableinapppurchasehistory) key to your `Info.plist`:
```
<key>SKIncludeConsumableInAppPurchaseHistory</key>
```
```
<true/>
```
In StoreKit 1, we will automatically log an event when the user successfully purchases a product, restores a product, or attempts to purchase a product but the purchase fails. In Store Kit 2, we will automatically log an event when the user successfully purchases a product or restores a product. If you would like to also log when a purchase fails in Store Kit 2, we have provided a manual API you must call. You can call this API in your StoreKit 2 purchase flow in the following way:
```
do {
let result = try await product.purchase()
switch result {
case .success(let verificationResult):
// Handle success case
case .pending:
// Handle pending case
default:
AppEvents.shared.logFailedStoreKit2Purchase(product.id)
}
} catch {
AppEvents.shared.logFailedStoreKit2Purchase(product.id)
}
```
### Get Device Consent
Starting with iOS 14.5, you will need to set `isAdvertiserTrackingEnabled` and log each time you give a device permission to share data with Facebook.
If a device provides consent, set `Settings.shared.isAdvertiserTrackingEnabled = true`.
If a device does not allow tracking, set `Settings.shared.isAdvertiserTrackingEnabled = false`.
#### Disable Automatically Logged Events {#disable-auto-events}
To disable automatic event logging, open the application's `Info.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, set `Settings.shared.isAutoLogAppEventsEnabled = true` to re-enable auto-logging after the end-user provides consent.
To suspend collection again for any reasons, set `Settings.shared.isAutoLogAppEventsEnabled = false`.
You can also disable automatic In-App Purchase event logging using the [app dashboard](https://developers.facebook.com/apps). Go to the **iOS card** under **Basic** **>** **Settings** and toggle the switch to **No**.
#### Disable Collection of Advertiser IDs {#disable-advertiser-id}
To disable collection of [`advertiser-id`](docs/marketing-api/app-event-api#installs), open the application's `.plist` as code in Xcode and add the following XML to the property dictionary:
```plist
<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, set `Settings.shared.isAdvertiserIDCollectionEnabled = true` after the end-user provides consent.
To suspend collection for any reason, set `Settings.shared.isAdvertiserIDCollectionEnabled = false`.
### Manually Log Events
To log a custom event, just pass the name of the event as an `AppEvents.Name`:
```
AppEvents.shared.logEvent(AppEvents.Name("battledAnOrc"))
```
#### Event Parameters {#event-params}
Meta has created a set of [useful event parameters](https://developers.facebook.com/documentation/app-events/reference#standard-event-parameters-2) for inclusion with standard events or with your own custom events. You can also provide your own parameters.
If you’d like to use app events to measure [Dynamic Ads](https://www.facebook.com/business/m/one-sheeters/dynamic-ads) conversions, please set the `fb_content_id` parameter to be the value of the Product ID used in the associated Dynamic Ad.
These [pre-defined parameters](https://developers.facebook.com/documentation/app-events/reference#standard-event-parameters-2) 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. 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 a dictionary where the key holds the parameter name as an `AppEvents.ParameterName`, and the value must be either a `String` or a number (`Int`, `Double`, etc.).
## Step 8: Test Your Events {#test-events}
The [App Ads Helper](https://developers.facebook.com/tools/app-ads-helper/) allows you to test the app events in your app to ensure that your app is sending events to Facebook.
- Open the [App Ads Helper](https://developers.facebook.com/tools/app-ads-helper/).
- In **Select an App**, choose your app and choose **Submit**.
- Scroll to the bottom and choose **Test Event**.
- Start your app and send an event. The event should appear on the page.
**Warning:** If you plan to optimize/track your events in SKAdNetwork campaigns, you also need to properly configure event priority (also known as conversion value) in order for Facebook to correctly receive the conversions. More details [can be found here](https://www.facebook.com/business/help/670955636925518).
## Learn More
- [Best Practices Guide](https://developers.facebook.com/documentation/app-events/best-practices) - View a wide variety of sample apps and how each handles App Events.
- [FAQ](https://developers.facebook.com/documentation/app-events/faq) - Check out our Frequently Asked Questions.
- Meta Blueprint course: [Configure the SDK and App Events for iOS](https://www.facebookblueprint.com/student/path/253018?content_id=WVtozducrYVuJ9p)
- Meta Blueprint course: [Use App Events to Target, Optimize and Measure](https://www.facebookblueprint.com/student/path/253008?content_id=FWxmTOIlbsCCDdg)
### Example Apps {#examples}
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.
- [E-Commerce and Retail](https://developers.facebook.com/documentation/app-events/best-practices/ecom-and-retail)
- [Travel (Hotel)](https://developers.facebook.com/documentation/app-events/best-practices/travel-hotel)
- [Travel (Flight)](https://developers.facebook.com/documentation/app-events/best-practices/travel-flight)
- [Gaming (Casual)](https://developers.facebook.com/documentation/app-events/best-practices/gaming-casual)
- [Gaming (Strategy)](https://developers.facebook.com/documentation/app-events/best-practices/gaming-strategy)
- [Gaming (Casino)](https://developers.facebook.com/documentation/app-events/best-practices/gaming-casino)