### Basic SDK Setup Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/REFERENCE.md Initializes the AppsFlyer SDK and starts its operation within the application's launch process. Requires the delegate to be set. ```swift func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? ) -> Bool { AppsFlyerLib.shared.initSDK(with: nil, delegate: self) AppsFlyerLib.shared.start() return true } ``` -------------------------------- ### Initialize and Start AppsFlyer SDK Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/README.md Initialize the SDK with options and delegate, then start the SDK. Ensure `options` and `self` are correctly configured. ```swift AppsFlyerLib.shared.initSDK(with: options, delegate: self) AppsFlyerLib.shared.start() ``` -------------------------------- ### AppsFlyer SDK Delegate Lifecycle Example Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/delegates.md This example demonstrates the complete integration of the AppsFlyer SDK delegate, including initialization, starting the SDK, and handling various delegate callbacks for conversion data and app open attribution. It also shows how to handle deep links within the application's open URL method. Ensure you import UIKit and AppsFlyerLib. ```swift import UIKit import AppsFlyerLib @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, AppsFlyerLibDelegate { func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? ) -> Bool { // Initialize AppsFlyer with configuration AppsFlyerLib.shared.initSDK(with: [ AFSDKDebugLogEnabled: true, AFSDKHTTPFallbackEnabled: false ], delegate: self) // Start SDK - triggers conversion data fetch AppsFlyerLib.shared.start() return true } // MARK: - AppsFlyerLibDelegate func onConversionDataSuccess(_ conversionData: [String: Any]!) { print("✓ Conversion data received") // Handle attribution } func onConversionDataFailure(_ error: Error!) { print("✗ Conversion data failed: \(error?.localizedDescription ?? "")") // Handle failure gracefully } func onAppOpenAttribution(_ attribution: [String: Any]!) { print("✓ Deep link attribution received") } func onAppOpenAttributionFailure(_ error: Error!) { print("✗ Deep link attribution failed") } // MARK: - UIApplicationDelegate func application( _ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey: Any] = [:] ) -> Bool { // Handle deep links AppsFlyerLib.shared.handleOpen(url, options: options) return true } } ``` -------------------------------- ### Start SDK Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/appsflyer-core.md Starts the SDK and begins tracking user sessions. This method must be called after initialization in the application delegate's `application(_:didFinishLaunchingWithOptions:)`. ```APIDOC ## Start SDK ### Description Starts the SDK and begins tracking user sessions. Must be called after initialization in the application delegate's `application(_:didFinishLaunchingWithOptions:)`. ### Method `func start()` ### Return Value `Void` ### Example ```swift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { AppsFlyerLib.shared.initSDK(with: nil, delegate: self) AppsFlyerLib.shared.start() return true } ``` ``` -------------------------------- ### Start Tracking Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/INDEX.md Starts the SDK's tracking services, essential for collecting attribution and user engagement data. ```APIDOC ## start() ### Description Starts the SDK's tracking services, essential for collecting attribution and user engagement data. ### Method Objective-C ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```objectivec [[AppsFlyerLib shared] start]; ``` ### Response #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### Start SDK Session Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/START_HERE.txt Starts a new SDK session. This method should be called after initialization to begin tracking user activity. ```swift AppsFlyerLib.shared.start() ``` -------------------------------- ### Install via CocoaPods Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/START_HERE.txt Instructions for installing the AppsFlyer SDK using CocoaPods. Ensure you have CocoaPods set up in your project. ```bash pod 'AppsFlyerFramework' ``` -------------------------------- ### Initialization and Lifecycle Methods Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/REFERENCE.md Methods for initializing the SDK, starting session tracking, and managing debug logging. ```APIDOC ## Initialization & Lifecycle ### `initSDK(with:delegate:)` #### Description Initialize SDK with configuration. #### Method `initSDK` #### Parameters - **options** (Any) - SDK configuration options. - **delegate** (AppsFlyerLibDelegate) - Delegate to receive SDK callbacks. ### `start()` #### Description Start session tracking. #### Method `start` ### `setIsDebug(_:)` #### Description Enable or disable debug logging. #### Method `setIsDebug` #### Parameters - **isDebug** (Bool) - Set to true to enable debug logging, false otherwise. ``` -------------------------------- ### Initialization Methods Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/MANIFEST.md Methods for initializing and starting the AppsFlyer SDK. ```APIDOC ## Initialization ### `initSDK()` Initializes the AppsFlyer SDK. ### `start()` Starts the AppsFlyer SDK after initialization. ``` -------------------------------- ### CocoaPods Installation Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/README.md Instructions for installing the AppsFlyer SDK using CocoaPods, with options for standard, dynamic linking, and strict (no IDFA) versions. ```ruby pod 'AppsFlyerFramework' # Standard pod 'AppsFlyerFramework/Dynamic' # Dynamic linking pod 'AppsFlyerFramework/Strict' # No IDFA ``` -------------------------------- ### Example Email Array Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/types.md Illustrates the expected format for an array of email addresses. ```swift ["user@example.com", "alternate@example.com"] ``` -------------------------------- ### SDK Initialization Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/README.md Initialize the AppsFlyer SDK with options and set up a delegate for callbacks. Start the SDK to begin tracking. ```APIDOC ## SDK Initialization ### Description Initialize the AppsFlyer SDK with configuration options and a delegate for receiving attribution data. After initialization, start the SDK to begin its operations. ### Methods - `initSDK(with:options, delegate:self)`: Initializes the SDK. - `start()`: Starts the SDK's tracking and processing. ### Parameters #### `initSDK` Parameters - **options** (Dictionary): Configuration options for the SDK. - **delegate** (AppsFlyerLibDelegate): An object conforming to the AppsFlyerLibDelegate protocol to handle callbacks. ### Code Example ```swift AppsFlyerLib.shared.initSDK(with: options, delegate: self) AppsFlyerLib.shared.start() ``` ``` -------------------------------- ### Initialize and Use AppsFlyerLib Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/REFERENCE.md Access the shared SDK instance, initialize it with options and a delegate, start tracking, and log events. ```swift import AppsFlyerLib // Access the shared instance let sdk = AppsFlyerLib.shared // Initialize sdk.initSDK(with: options, delegate: self) // Start tracking sdk.start() // Log events sdk.logEvent("event_name", withValues: ["key": "value"]) ``` -------------------------------- ### Install AppsFlyerFramework with Cocoapods Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/README.md Use these lines in your Podfile to install the desired version of the AppsFlyerFramework. Choose the static, dynamic, or strict (no IDFA collection) library. ```ruby # For statically linked library pod 'AppsFlyerFramework' # For dynamically linked library pod 'AppsFlyerFramework/Dynamic' # For Strict (No IDFA colection) library pod 'AppsFlyerFramework/Strict' ``` -------------------------------- ### Starting AppsFlyerLib SDK Session Tracking Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/appsflyer-core.md Starts the SDK's session tracking mechanism. This method must be called after initialization within the application delegate's `application(_:didFinishLaunchingWithOptions:)` method. ```swift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { AppsFlyerLib.shared.initSDK(with: nil, delegate: self) AppsFlyerLib.shared.start() return true } ``` -------------------------------- ### Start Session Tracking Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/INDEX.md Starts the session tracking for the AppsFlyer SDK. This should be called after initialization. ```APIDOC ## start() ### Description Starts the session tracking for the AppsFlyer SDK. This method should be called after `initSDK` to begin collecting user engagement data. ### Method Signature `start()` ``` -------------------------------- ### Core SDK Methods Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/REFERENCE.md Provides reference for the main SDK class and its core methods for initialization and starting the SDK. ```APIDOC ## Core SDK Methods ### initSDK(with:delegate:) Initializes the AppsFlyer SDK with an app ID and a delegate for callbacks. ### Method Objective-C/Swift ### Parameters - **appId** (string) - Required - Your AppsFlyer application ID. - **delegate** (AppsFlyerLibDelegate) - Optional - An object conforming to the AppsFlyerLibDelegate protocol to receive SDK callbacks. ### start() Starts the AppsFlyer SDK's tracking and initialization process. ### Method Objective-C/Swift ### shared (singleton) Accesses the singleton instance of the AppsFlyerLib class. ### Method Objective-C/Swift ``` -------------------------------- ### Install AppsFlyer SDK with CocoaPods Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/integration-guide.md Add the appropriate AppsFlyerFramework pod to your Podfile for static, dynamic, or strict library linking. Run 'pod install' afterwards. ```ruby pod 'AppsFlyerFramework' pod 'AppsFlyerFramework/Dynamic' pod 'AppsFlyerFramework/Strict' ``` -------------------------------- ### Install Strict AppsFlyer Framework (No IDFA) Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/integration-guide.md Install the strict framework for privacy-focused apps that do not require IDFA collection. It offers a smaller footprint. ```ruby pod 'AppsFlyerFramework/Strict' ``` -------------------------------- ### Example Phone Array Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/types.md Illustrates the expected format for an array of phone numbers. ```swift ["+1234567890", "+0987654321"] ``` -------------------------------- ### Complete User Setup on Login Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/user-management.md Set all available user identifiers and log a login event after a user successfully logs in. This ensures all relevant user data is associated with the session. ```swift func setupUserAfterLogin(_ user: User) { // Set all available identifiers AppsFlyerLib.shared.setCustomerUserId(user.id) if let email = user.email { AppsFlyerLib.shared.setUserEmail(email) } if let phone = user.phone { AppsFlyerLib.shared.setPhoneNumber(phone) } // Log login event AppsFlyerLib.shared.logEvent(AFSDKEventLogin, withValues: [ "af_user_id": user.id, "af_login_method": user.loginMethod ]) } ``` -------------------------------- ### Carthage Installation Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/README.md Specifies the GitHub repository for integrating the AppsFlyer SDK using Carthage. ```text github "AppsFlyerSDK/AppsFlyerFramework" ``` -------------------------------- ### Conversion Data Structure Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/README.md Represents attribution data for app installs, including install time, status, media source, campaign, ad details, and first launch indicator. ```swift [ "install_time": String, "af_status": String, // "Organic" or "Non-organic" "media_source": String, "campaign": String, "ad": String, "is_first_launch": Bool ] ``` -------------------------------- ### Install Dynamic AppsFlyer Framework Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/integration-guide.md Use the dynamic framework for iOS app extensions. Note that this option results in a larger app bundle size. ```ruby pod 'AppsFlyerFramework/Dynamic' ``` -------------------------------- ### Log Current User Setup Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/user-management.md This Swift function logs the current AppsFlyerUID and CustomerID that are set for the user. Call this to verify your user ID configuration. ```swift func logCurrentUserSetup() { var setup = [String: String]() if let uid = AppsFlyerLib.shared.appsFlyerUID { setup["AppsFlyerUID"] = uid } if let customerId = AppsFlyerLib.shared.customerUserId { setup["CustomerID"] = customerId } print("Current user setup: \(setup)") } ``` -------------------------------- ### Install AppsFlyer SDK with Swift Package Manager Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/INDEX.md Add this repository URL to your Swift Package Manager dependencies to integrate the AppsFlyer SDK. ```text https://github.com/AppsFlyerSDK/AppsFlyerFramework-Static ``` -------------------------------- ### onAppOpenAttribution(_:) Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/delegates.md This method is called when the app is opened via a deep link or an attribution link after installation. It provides the attribution data from deep link parameters. ```APIDOC ## onAppOpenAttribution(_:) ### Description Called when app is opened via deep link or attribution link after install. ### Parameters #### Path Parameters - **attribution** ( `[String: Any]!` ) - Required - Attribution data from deep link parameters ### Request Example ```swift func onAppOpenAttribution(_ attribution: [String: Any]!) { guard let attribution = attribution else { print("No attribution data from deep link") return } // Handle deep link navigation if let deepLinkValue = attribution["deep_link_value"] as? String { print("Deep link value: \(deepLinkValue)") // Route user based on deep link } } ``` ``` -------------------------------- ### Initialize AppsFlyer SDK in AppDelegate Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/INDEX.md Implement this code in your AppDelegate to initialize the AppsFlyer SDK and start session tracking. Ensure you conform to the `AppsFlyerLibDelegate` protocol to handle attribution callbacks. ```swift import AppsFlyerLib class AppDelegate: UIResponder, UIApplicationDelegate, AppsFlyerLibDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Initialize AppsFlyerLib.shared.initSDK(with: nil, delegate: self) AppsFlyerLib.shared.start() return true } // Implement required delegates func onConversionDataSuccess(_ conversionData: [String: Any]!) { print("Attribution: \(conversionData ?? [:])") } func onConversionDataFailure(_ error: Error!) { print("Error: \(error?.localizedDescription ?? "")") } } ``` -------------------------------- ### Handle App Open Attribution Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/delegates.md Implement this method to receive and process attribution data when the app is opened via a deep link or attribution link after installation. Ensure attribution data is not nil before attempting to use it. ```swift func onAppOpenAttribution(_ attribution: [String: Any]!) ``` ```swift func onAppOpenAttribution(_ attribution: [String: Any]!) { guard let attribution = attribution else { print("No attribution data from deep link") return } // Handle deep link navigation if let deepLinkValue = attribution["deep_link_value"] as? String { print("Deep link value: \(deepLinkValue)") // Route user based on deep link } } ``` -------------------------------- ### Conversion Data Dictionary Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/REFERENCE.md Defines the structure for conversion data, including install time, status, media source, campaign, ad, and first launch information. ```swift [ "install_time": String, "af_status": String, // "Organic" or "Non-organic" "media_source": String, "campaign": String, "ad": String, "is_first_launch": Bool ] ``` -------------------------------- ### Project Structure Overview Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/README.md This code block outlines the directory structure for the AppsFlyerLib documentation. It helps users navigate to specific documentation files like the README, index, reference, integration guide, configuration, types, errors, and API reference sections. ```tree /output/ ├── README.md ← This file ├── INDEX.md ← Start here (navigation) ├── REFERENCE.md ← Master reference summary ├── integration-guide.md ← Setup & implementation patterns ├── configuration.md ← SDK options & initialization ├── types.md ← Data dictionaries & structures ├── errors.md ← Error codes & recovery └── api-reference/ ← Detailed API documentation ├── appsflyer-core.md ← Core SDK class & methods ├── delegates.md ← Callback protocol methods ├── user-management.md ← User ID methods ├── deep-linking.md ← Deep link & OneLink API ├── event-constants.md ← Standard event names └── purchase-validation.md ← In-app purchase validation ``` -------------------------------- ### Complete Deep Link Integration in AppDelegate Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/deep-linking.md Integrates AppsFlyer SDK initialization and deep link handling within the AppDelegate. This includes handling deep links from cold starts and background app opens. ```swift import UIKit import AppsFlyerLib class AppDelegate: UIResponder, UIApplicationDelegate, AppsFlyerLibDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Initialize AppsFlyer AppsFlyerLib.shared.initSDK(with: nil, delegate: self) AppsFlyerLib.shared.start() // Handle deep link from cold start if let url = launchOptions?[UIApplicationLaunchOptionsKey.url] as? URL { AppsFlyerLib.shared.logDeepLink(url, deepLinkScheme: url.scheme ?? "") handleDeepLink(url) } return true } // MARK: - Deep Link Handling func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey: Any] = [:]) -> Bool { AppsFlyerLib.shared.logDeepLink(url, deepLinkScheme: url.scheme ?? "") handleDeepLink(url) return true } private func handleDeepLink(_ url: URL) { guard let components = URLComponents(url: url, resolvingAgainstBaseURL: true) else { return } let queryItems = components.queryItems ?? [] switch url.host { case "product": if let productId = queryItems.first(where: { $0.name == "id" })?.value { NotificationCenter.default.post(name: NSNotification.Name("DeepLinkProduct"), object: productId) } case "profile": if let userId = queryItems.first(where: { $0.name == "user" })?.value { NotificationCenter.default.post(name: NSNotification.Name("DeepLinkProfile"), object: userId) } case "promo": if let code = queryItems.first(where: { $0.name == "code" })?.value { NotificationCenter.default.post(name: NSNotification.Name("DeepLinkPromo"), object: code) } default: break } } // MARK: - AppsFlyerLibDelegate func onAppOpenAttribution(_ attribution: [String: Any]!) { print("Deep link attribution: \(attribution ?? [:])") if let deepLinkValue = attribution["deep_link_value"] as? String { print("Routing to: \(deepLinkValue)") handleDeepLink(URL(string: deepLinkValue) ?? URL(fileURLWithPath: "")) } } func onAppOpenAttributionFailure(_ error: Error!) { print("Attribution failure: \(error?.localizedDescription ?? "")") } func onConversionDataSuccess(_ conversionData: [String: Any]!) { // Handle regular conversion data } func onConversionDataFailure(_ error: Error!) { // Handle conversion data failure } } ``` -------------------------------- ### Handle Successful Conversion Data Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/delegates.md Implement this method to process attribution and conversion data received from AppsFlyer servers. Handle cases for both organic and non-organic installs, and check for first-time launches. ```swift func onConversionDataSuccess(_ conversionData: [String: Any]!) { guard let conversionData = conversionData else { print("No conversion data available") return } // Check if this is an attributed install if let afStatus = conversionData["af_status"] as? String { print("Attribution status: \(afStatus)") if afStatus == "Non-organic" { // Handle attributed user if let mediaSource = conversionData["media_source"] as? String, let campaign = conversionData["campaign"] as? String { print("User acquired from \(mediaSource) via campaign: \(campaign)") // Send to analytics or adjust in-app experience Analytics.log(event: "user_attributed", parameters: [ "media_source": mediaSource, "campaign": campaign ]) } } else { // Handle organic user print("Organic user") } } // Check if this is first launch if let isFirstLaunch = conversionData["is_first_launch"] as? NSNumber { if isFirstLaunch.boolValue { print("First time user opened app") } } } ``` -------------------------------- ### Access App Store Receipt Data Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/purchase-validation.md Obtain the App Store receipt data for parsing transaction IDs. This example shows how to get the URL to the receipt. ```swift if let appReceipt = Bundle.main.appStoreReceiptURL { let receiptData = try? Data(contentsOf: appReceipt) // Parse receipt to extract transaction IDs } ``` -------------------------------- ### Initialize AppsFlyerLib with Configuration Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/configuration.md Use this method to initialize the SDK with a dictionary of configuration options. Ensure the delegate is set correctly. ```swift AppsFlyerLib.shared.initSDK(with: [ AFSDKDebugLogEnabled: true, AFSDKCurrency: "USD", "minTimeBetweenSessions": NSNumber(value: 300) ], delegate: self) ``` -------------------------------- ### Signup Flow Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/user-management.md Handle new user signups by setting immediate identifiers and logging a signup event. This is crucial for tracking new user acquisition. ```swift func handleNewUserSignup(_ userData: SignupData) { // Set identifiers immediately AppsFlyerLib.shared.setCustomerUserId(userData.userId) AppsFlyerLib.shared.setUserEmail(userData.email) if let phone = userData.phone { AppsFlyerLib.shared.setUserPhones([phone]) } // Log signup event AppsFlyerLib.shared.logEvent(AFSDKEventSignup, withValues: [ "af_user_id": userData.userId, "af_signup_method": "email" ]) } ``` -------------------------------- ### SDK Initialization Options Dictionary Structure Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/types.md Specifies the configuration options for initializing the SDK using `initSDK(with:delegate:)`. Includes debug logging, attribution, and deeplink settings. ```swift [String: Any] = [ AFSDKDebugLogEnabled: Bool, // Enable debug logging AFSDKHTTPFallbackEnabled: Bool, // Enable HTTP fallback AFSDKCurrency: String, // Default currency AFSDKAppleSearchAdsAttributionEnabled: Bool, // ASA tracking AFSDKShareInviteParametersEnabled: Bool, // Share invite params AFSDKResolveDeepLinkURL: String, // Deeplink URL AFSDKUserCurrencyCode: String, // User currency "minTimeBetweenSessions": NSNumber, // Session timeout seconds "disableAppleSearchAdsAttribution": NSNumber // Disable ASA ] ``` -------------------------------- ### AppsFlyer SDK Initialization Configuration Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/REFERENCE.md Pass a dictionary of configuration options to the `initSDK(with:delegate:)` method to customize SDK behavior. Defaults are provided for most options. ```swift [ AFSDKDebugLogEnabled: Bool, // Default: false AFSDKHTTPFallbackEnabled: Bool, // Default: true AFSDKCurrency: String, // Default: nil AFSDKAppleSearchAdsAttributionEnabled: Bool, // Default: true AFSDKShareInviteParametersEnabled: Bool, // Default: true AFSDKResolveDeepLinkURL: String, // Default: nil "minTimeBetweenSessions": NSNumber // Default: 300 ] ``` -------------------------------- ### Log Tutorial Completion Event Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/event-constants.md Logs when a user completes the app tutorial. This event does not require additional parameters. ```swift AFSDKEventTutorialComplete = "af_tutorial_completion" ``` ```swift AppsFlyerLib.shared.logEvent(AFSDKEventTutorialComplete, withValues: [:]) ``` -------------------------------- ### Get Custom AppsFlyer User ID Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/appsflyer-core.md Retrieves the AppsFlyerUID for the current user. Returns nil if not set. ```swift var appsFlyerUID: String? ``` ```swift if let uid = AppsFlyerLib.shared.appsFlyerUID { print("AppsFlyerUID: \(uid)") } ``` -------------------------------- ### Get Transaction ID from StoreKit 2 Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/purchase-validation.md Extract the transaction ID from a StoreKit 2 transaction object. ```swift let transactionID = String(transaction.id) ``` -------------------------------- ### Configuration Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/MANIFEST.md Methods for configuring SDK behavior and settings. ```APIDOC ## Configuration ### `setIsDebug(_:)` Enables or disables debug logging. ### `setMinTimeBetweenSessions(_:)` Sets the minimum time interval between user sessions. ### `disableIDFACollection()` Disables IDFA collection. ### `disableAppleSearchAdsAttribution()` Disables Apple Search Ads attribution. ### `disableSKAdNetwork()` Disables SKAdNetwork integration. ``` -------------------------------- ### Initialize SDK with Delegate Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/delegates.md Pass the delegate instance during SDK initialization to enable callbacks. Ensure the delegate is set before calling initSDK. ```swift AppsFlyerLib.shared.initSDK(with: options, delegate: self) ``` -------------------------------- ### Get AppsFlyerUID Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/user-management.md Retrieves the current AppsFlyerUID, which can be auto-generated or custom. This is useful for sending the identifier to your backend systems. ```swift var appsFlyerUID: String? ``` ```swift // Get current AppsFlyerUID if let uid = AppsFlyerLib.shared.appsFlyerUID { print("Current AppsFlyerUID: \(uid)") // Send to your backend sendUserIdToBackend(uid) } ``` -------------------------------- ### Initialize AppsFlyer SDK Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/configuration.md Configure and initialize the AppsFlyer SDK with essential settings. Ensure this is done early in your application's lifecycle. ```swift import AppsFlyerLib class AppDelegate: UIResponder, UIApplicationDelegate, AppsFlyerLibDelegate { func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? ) -> Bool { // Configure AppsFlyer let config: [String: Any] = [ AFSDKDebugLogEnabled: true, // Enable logging in debug builds AFSDKCurrency: "USD", // Default currency AFSDKAppleSearchAdsAttributionEnabled: true, // ASA tracking "minTimeBetweenSessions": NSNumber(value: 300) // 5 minute session timeout ] // Initialize SDK AppsFlyerLib.shared.initSDK(with: config, delegate: self) // Additional configuration after init AppsFlyerLib.shared.setIsDebug(true) AppsFlyerLib.shared.setMinTimeBetweenSessions(300) // Start tracking AppsFlyerLib.shared.start() return true } // MARK: - AppsFlyerLibDelegate func onConversionDataSuccess(_ conversionData: [String: Any]!) {} func onConversionDataFailure(_ error: Error!) {} } ``` -------------------------------- ### Initializing AppsFlyerLib SDK Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/appsflyer-core.md Initializes the AppsFlyerLib SDK with optional configuration settings and a delegate for handling lifecycle events. Ensure the delegate conforms to AppsFlyerLibDelegate. ```swift import AppsFlyerLib AppsFlyerLib.shared.initSDK(with: [ AFSDKDebugLogEnabled: true, AFSDKHTTPFallbackEnabled: false ], delegate: self) ``` -------------------------------- ### SDK Initialization Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/INDEX.md Initializes the AppsFlyer SDK with the provided developer key and delegate for handling attribution callbacks. ```APIDOC ## initSDK(with:delegate:) ### Description Initializes the AppsFlyer SDK with the provided developer key and delegate for handling attribution callbacks. ### Method Objective-C ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```objectivec [AppsFlyerLib shared].appsFlyerDevKey = @"YOUR_APPSFLYER_DEV_KEY"; [AppsFlyerLib shared].appleAppID = @"YOUR_APPLE_APP_ID"; [[AppsFlyerLib shared] initSDKWithAppId:@"YOUR_APPLE_APP_ID" withDelegate:self]; ``` ### Response #### Success Response (N/A) N/A #### Response Example N/A ``` -------------------------------- ### Conversion Data Dictionary Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/types.md Dictionary returned by `AppsFlyerLib.shared.conversionData` and passed to `onConversionDataSuccess(_:)` delegate method. It contains attribution and install details. ```APIDOC ## Conversion Data Dictionary ### Description Dictionary returned by `AppsFlyerLib.shared.conversionData` and passed to `onConversionDataSuccess(_:)` delegate method. It contains attribution and install details. ### Structure ```swift [String: Any] = [ "install_time": String, // Unix timestamp "af_status": String, // "Organic" or "Non-organic" "media_source": String, // Channel identifier "campaign": String, // Campaign name "campaign_id": String, // Campaign ID "adset": String, // Ad set name "adset_id": String, // Ad set ID "ad": String, // Ad name "ad_id": String, // Ad ID "media_source_id": String, // Media source identifier "is_first_launch": Bool, // First app launch indicator "click_time": String? // Click timestamp if available ] ``` ### Fields | Key | Type | Description | When Present | |-----|------|-------------|--------------| | `install_time` | `String` | Unix timestamp of app installation | Always | | `af_status` | `String` | "Organic" for non-attributed, "Non-organic" for attributed | Always | | `media_source` | `String` | Source identifier (e.g., "facebook", "google_ads", "organic") | Always | | `campaign` | `String` | Campaign name or identifier | Attributed installs | | `campaign_id` | `String` | Unique campaign ID | Attributed installs | | `adset` | `String` | Ad set name | Attributed installs | | `adset_id` | `String` | Unique ad set ID | Attributed installs | | `ad` | `String` | Individual ad name | Attributed installs | | `ad_id` | `String` | Unique ad ID | Attributed installs | | `media_source_id` | `String` | Numeric media source identifier | Attributed installs | | `is_first_launch` | `Bool` / `NSNumber` | `true` on first app launch | Always (cast to NSNumber) | | `click_time` | `String?` | Unix timestamp of attribution click | Attributed installs | ``` -------------------------------- ### Get Customer User ID Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/user-management.md Retrieves the customer user ID that was previously set. This can be used for debugging or logging purposes. ```swift var customerUserId: String? ``` ```swift // Get customer ID if let customerId = AppsFlyerLib.shared.customerUserId { print("Customer ID: \(customerId)") } ``` -------------------------------- ### Initialize SDK Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/INDEX.md Initializes the AppsFlyer SDK with optional configuration and a delegate for handling attribution data. ```APIDOC ## initSDK(with:delegate:) ### Description Initializes the AppsFlyer SDK. This method should be called early in your application's lifecycle, typically in the `application(_:didFinishLaunchingWithOptions:)` method of your AppDelegate. ### Method Signature `initSDK(with:delegate:)` ### Parameters - **launchOptions** (`[UIApplicationLaunchOptionsKey: Any]?`) - Optional launch options. - **delegate** (`AppsFlyerLibDelegate`) - An object conforming to the `AppsFlyerLibDelegate` protocol to receive attribution data and other callbacks. ``` -------------------------------- ### Test Deep Link URL Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/integration-guide.md Example of a deep link URL structure used for testing. This format is used with the AppsFlyer OneLink tool. ```url https://example.onelink.me/abc123?pid=test&c=test_campaign&af_dp=myapp%3A%2F%2Fproduct%3Fid%3D123 ``` -------------------------------- ### Configure Debugging in Swift Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/integration-guide.md Enable or disable debug logging and HTTP fallback based on the build environment. Initialize the SDK with the chosen configuration. ```swift #if DEBUG let config: [String: Any] = [ AFSDKDebugLogEnabled: true, // Enable console logging AFSDKHTTPFallbackEnabled: true ] #else let config: [String: Any] = [ AFSDKDebugLogEnabled: false ] #endif AppsFlyerLib.shared.initSDK(with: config, delegate: self) ``` -------------------------------- ### Conversion Data Dictionary Structure Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/types.md This dictionary is returned by `AppsFlyerLib.shared.conversionData` and passed to the `onConversionDataSuccess(_:)` delegate method. It contains details about the app's install and attribution. ```swift [String: Any] = [ "install_time": String, // Unix timestamp "af_status": String, // "Organic" or "Non-organic" "media_source": String, // Channel identifier "campaign": String, // Campaign name "campaign_id": String, // Campaign ID "adset": String, // Ad set name "adset_id": String, // Ad set ID "ad": String, // Ad name "ad_id": String, // Ad ID "media_source_id": String, // Media source identifier "is_first_launch": Bool, // First app launch indicator "click_time": String? // Click timestamp if available ] ``` -------------------------------- ### Get Transaction ID from StoreKit 1 Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/purchase-validation.md Retrieve the transaction identifier from a StoreKit 1 transaction object. Returns an empty string if the identifier is nil. ```swift let transactionID = transaction.transactionIdentifier ?? "" ``` -------------------------------- ### Handle Deep Link Opening with Options Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/deep-linking.md Use this alternative method for handling deep link openings when you have the full options dictionary. It combines deep link logging and processing into a single call. ```swift func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey: Any] = [:]) -> Bool { // Single call handles both logging and processing AppsFlyerLib.shared.handleOpen(url, options: options) return true } ``` -------------------------------- ### Log Signup Event Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/event-constants.md Logs when a user creates an account or signs up. Supports new user ID and signup method. ```swift AFSDKEventSignup = "af_signup" ``` ```swift AppsFlyerLib.shared.logEvent(AFSDKEventSignup, withValues: [ "af_user_id": "user_456", "af_signup_method": "email" ]) ``` -------------------------------- ### Handle URL Opening in Swift Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/appsflyer-core.md Handles URL opening for universal links and custom schemes. This method is crucial for integrating deep linking capabilities. ```swift func handleOpen(_ url: URL, options: [UIApplicationOpenURLOptionsKey: Any]) ``` -------------------------------- ### AFSDKEventTutorialComplete Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/event-constants.md Logs when a user completes the app tutorial. ```APIDOC ## AFSDKEventTutorialComplete ### Description Logs when user completes app tutorial. ### Request Example ```swift AppsFlyerLib.shared.logEvent(AFSDKEventTutorialComplete, withValues: [:]) ``` ``` -------------------------------- ### Basic Purchase Validation Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/purchase-validation.md This is a basic example of how to validate an in-app purchase. It logs success or failure and calls helper functions to finish the transaction or handle the failure. ```APIDOC ## Basic Purchase Validation ### Description Validates a standard in-app purchase. ### Method Signature `validateAndLogInAppPurchase(productIdentifier: String, price: String, currency: String, transactionId: String, additionalParameters: [String: Any]?, success: (() -> Void)?, failure: ((Error?) -> Void)?) ### Parameters - `productIdentifier` (String) - The identifier of the purchased product. - `price` (String) - The price of the product. - `currency` (String) - The currency code (e.g., "USD"). - `transactionId` (String) - The unique identifier for the transaction. - `additionalParameters` ([String: Any]?, Optional) - Additional parameters to send with the validation. - `success` (() -> Void)?, Optional) - Callback for successful validation. - `failure` ((Error?) -> Void)?, Optional) - Callback for failed validation. ``` -------------------------------- ### Log Subscription with Trial Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/purchase-validation.md Validate and log a subscription purchase that includes a free trial period. Specify trial details in additional parameters. ```swift AppsFlyerLib.shared.validateAndLogInAppPurchase( productIdentifier: "com.example.premium_yearly", price: "99.99", currency: "USD", transactionId: "1000000123456789", additionalParameters: [ "subscription_period": "P1Y", "has_trial": "true", "trial_days": "7" ], success: { /* Handle success */ }, failure: { /* Handle failure */ } ) ``` -------------------------------- ### PII Hashing Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/user-management.md Optionally hash Personally Identifiable Information (PII) like email addresses before sending them to AppsFlyer for enhanced privacy. This example uses MD5 hashing. ```swift import CryptoKit func setUserEmailHashed(_ email: String) { // Optional: hash PII for extra privacy let digest = Insecure.MD5.hash(data: email.data(using: .utf8) ?? Data()) let hashedEmail = digest.map { String(format: "%02hhx", $0) }.joined() AppsFlyerLib.shared.setUserEmail(hashedEmail) } ``` -------------------------------- ### Get IDFA Declaration Status Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/appsflyer-core.md Retrieves the IDFA declaration status, crucial for iOS 14+ privacy compliance. Returns an optional String representing the declaration or nil. ```swift var idfaDeclaration: String? ``` -------------------------------- ### Initialize SDK with Delegate Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/START_HERE.txt Initializes the AppsFlyer SDK with a delegate for handling conversion data callbacks. Ensure the delegate is set before calling this method. ```swift AppsFlyerLib.shared.initSDK(with:delegate:) ``` -------------------------------- ### Initialization Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/appsflyer-core.md Initializes the AppsFlyerLib SDK with configuration options and a delegate for lifecycle events. This method must be called before other SDK methods. ```APIDOC ## Initialization ### Description Initializes the AppsFlyerLib SDK with configuration options and a delegate for lifecycle events. ### Method `func initSDK(with options: [String: Any]?, delegate: AppsFlyerLibDelegate)` ### Parameters #### Options - **options** (`[String: Any]?`) - Optional - Dictionary of configuration options. See Configuration section. #### Delegate - **delegate** (`AppsFlyerLibDelegate`) - Required - Delegate object to receive SDK callbacks ### Return Value `Void` ### Throws None (errors delivered to delegate methods) ### Example ```swift import AppsFlyerLib AppsFlyerLib.shared.initSDK(with: [ AFSDKDebugLogEnabled: true, AFSDKHTTPFallbackEnabled: false ], delegate: self) ``` ``` -------------------------------- ### handleOpen Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/deep-linking.md An alternative method to handle deep link opening with the full options dictionary. This method combines deep link logging and handling into a single call. ```APIDOC ## handleOpen(url:options:) ### Description Alternative method to handle deep link opening with full options dictionary. Combines deep link logging and handling. ### Parameters #### Path Parameters - **url** (URL) - Required - The deep link URL being opened - **options** ([UIApplicationOpenURLOptionsKey: Any]) - Required - Options from system callback including source app ### Implementation Example ```swift func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey: Any] = [:]) -> Bool { // Single call handles both logging and processing AppsFlyerLib.shared.handleOpen(url, options: options) return true } ``` ``` -------------------------------- ### Check for Deferred Deep Link in Swift Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/deep-linking.md Use this code within the `onAppOpenAttribution` delegate method to determine if a deep link is deferred. This helps identify users who installed the app after clicking a link. ```swift func onAppOpenAttribution(_ attribution: [String: Any]!) { if let isDeferred = attribution["is_deferred"] as? NSNumber { if isDeferred.boolValue { print("This is a deferred deep link - user installed app after clicking link") } } } ``` -------------------------------- ### handleOpen Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/appsflyer-core.md Handles URL opening for universal links and custom schemes. This method should be called from your application's URL handling delegate methods. ```APIDOC ## handleOpen(url:options:) ### Description Handles URL opening for universal links and custom schemes. ### Parameters #### Path Parameters - **url** (URL) - Required - URL being opened - **options** ([UIApplicationOpenURLOptionsKey: Any]) - Required - Options dictionary from system callback ``` -------------------------------- ### Handle Invalid Deep Link Error in Swift Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/errors.md This example shows how to handle errors related to invalid deep link URLs in the `onAppOpenAttributionFailure` callback. It logs the error and suggests showing a default screen. ```swift func onAppOpenAttributionFailure(_ error: Error!) { print("Cannot process deep link: \(error?.localizedDescription ?? "")") // Show default home screen instead showDefaultScreen() } ``` -------------------------------- ### AFSDKEventSignup Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/event-constants.md Logs when a user creates an account or signs up. Tracks new user ID and signup method. ```APIDOC ## AFSDKEventSignup ### Description Logs when user creates an account/signs up. ### Parameters #### Request Body - **af_user_id** (String) - Optional - New user ID - **af_signup_method** (String) - Optional - Signup method (e.g., "email", "social") ### Request Example ```swift AppsFlyerLib.shared.logEvent(AFSDKEventSignup, withValues: [ "af_user_id": "user_456", "af_signup_method": "email" ]) ``` ``` -------------------------------- ### Initialize and Sync IDs at App Launch Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/api-reference/user-management.md Call this function during app launch to initialize the SDK and set all known user identifiers. Ensure helper functions like `retrieveSavedAppsFlyerUID`, `currentUserId`, `userEmail`, and `userPhone` are implemented to fetch the correct user data. ```swift func setupAppsFlyer() { AppsFlyerLib.shared.initSDK(with: nil, delegate: self) // Set all known user identifiers syncUserIdentifiers() AppsFlyerLib.shared.start() } private func syncUserIdentifiers() { // Set AppsFlyerUID if available if let uid = retrieveSavedAppsFlyerUID() { AppsFlyerLib.shared.setAppsFlyerUID(uid) } // Set customer ID if user is logged in if let customerId = currentUserId() { AppsFlyerLib.shared.setCustomerUserId(customerId) } // Set contact info if let email = userEmail() { AppsFlyerLib.shared.setUserEmail(email) } if let phone = userPhone() { AppsFlyerLib.shared.setPhoneNumber(phone) } } ``` -------------------------------- ### Initialize AppsFlyer SDK on tvOS Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/configuration.md Initialize the AppsFlyer SDK on tvOS with debug logging enabled. Note that IDFA is not available on tvOS. ```swift // tvOS initialization AppsFlyerLib.shared.initSDK(with: [ AFSDKDebugLogEnabled: true ], delegate: self) AppsFlyerLib.shared.start() ``` -------------------------------- ### Implement AppsFlyerLibDelegate Methods Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/integration-guide.md Implement the AppsFlyerLibDelegate methods to handle conversion data and app open attribution. These methods provide information about user attribution and deep link events. ```swift // MARK: - AppsFlyerLibDelegate func onConversionDataSuccess(_ conversionData: [String: Any]!) { print("Conversion data: \(conversionData ?? [:])") if let status = conversionData["af_status"] as? String { if status == "Non-organic" { print("User attributed to: \(conversionData["media_source"] ?? "") } } } func onConversionDataFailure(_ error: Error!) { print("Conversion data error: \(error?.localizedDescription ?? "")") } func onAppOpenAttribution(_ attribution: [String: Any]!) { print("Deep link attribution: \(attribution ?? [:])") } func onAppOpenAttributionFailure(_ error: Error!) { print("Deep link error: \(error?.localizedDescription ?? "")") } ``` -------------------------------- ### Delegate Methods Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/README.md Implement these delegate methods to receive callbacks for conversion data, attribution data, and errors. ```APIDOC ## Delegate Methods ### Description Implement these delegate methods in your `AppsFlyerLibDelegate` conforming class to handle asynchronous callbacks from the AppsFlyer SDK, such as conversion data, attribution data, and errors. ### Methods - `onConversionDataSuccess(_ conversionData: [String: Any]!)`: Called when conversion data is successfully received. - `onConversionDataFailure(_ error: Error!)`: Called when there is an error fetching conversion data. - `onAppOpenAttribution(_ attribution: [String: Any]!)`: Called when app open attribution data is successfully received. - `onAppOpenAttributionFailure(_ error: Error!)`: Called when there is an error fetching app open attribution data. ### Parameters - **conversionData** ([String: Any]!): A dictionary containing conversion data. - **error** (Error!): An error object if an error occurred. - **attribution** ([String: Any]!): A dictionary containing app open attribution data. ### Code Example ```swift func onConversionDataSuccess(_ conversionData: [String: Any]!) { // Handle conversion data } func onConversionDataFailure(_ error: Error!) { // Handle conversion data error } func onAppOpenAttribution(_ attribution: [String: Any]!) { // Handle app open attribution data } func onAppOpenAttributionFailure(_ error: Error!) { // Handle app open attribution error } ``` ``` -------------------------------- ### Provide User-Friendly Fallbacks on Failure Source: https://github.com/appsflyersdk/appsflyerframework/blob/master/_autodocs/errors.md When attribution data fails to load, provide sensible default values (e.g., organic status, unknown media source) to maintain a consistent user experience instead of halting functionality. ```swift func onConversionDataFailure(_ error: Error!) { print("Attribution unavailable: \(error?.localizedDescription ?? "")") // Use sensible defaults instead of failing let defaultAttribution = [ "af_status": "Organic", "media_source": "unknown" ] processAttribution(defaultAttribution) } ```