Integrar o SDK

Saiba como inicializar e iniciar o SDK do iOS.

Antes de começar

  • Antes de integrar, você deve Instalar o SDK.
  • Este documento contém exemplos de implementações. Certifique-se de substituir o seguinte:
    • <AF_DEV_KEY>: A chave do desenvolvedor da AppsFlyer.
    • <APPLE_APP_ID>: The Apple App ID (without the id prefix).
    • Placeholders adicionais, quando necessário.

Inicializando o SDK do iOS

Etapa 1: importar dependências
Importar AppsFlyerLib:

// AppDelegate.h
#import <AppsFlyerLib/AppsFlyerLib.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@end
import UIKit
import AppsFlyerLib

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    // ...
}

Etapa 2: inicializar o SDK
In didFinishLaunchingWithOptions configure your Apple App ID and AppsFlyer dev key:

[[AppsFlyerLib shared] setAppsFlyerDevKey:@"<AF_DEV_KEY>"];
[[AppsFlyerLib shared] setAppleAppID:@"<APPLE_APP_ID>"];
AppsFlyerLib.shared().appsFlyerDevKey = "<AF_DEV_KEY>"
AppsFlyerLib.shared().appleAppID = "<APPLE_APP_ID>"

Iniciando o SDK do iOS

In applicationDidBecomeActive, call start:

[[AppsFlyerLib shared] start];
func applicationDidBecomeActive(_ application: UIApplication) {
    AppsFlyerLib.shared().start()
    // ...
}

Add SceneDelegate support

OPCIONAL
Do the following only if you use SceneDelegates:

In didFinishLaunchingWithOptions, add a UIApplicationDidBecomeActiveNotification observer and set it to run start:

@implementation AppDelegate
    // SceneDelegate support - start AppsFlyer SDK
    - (void)sendLaunch:(UIApplication *)application {
    [[AppsFlyerLib shared] start];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // ...
    // SceneDelegate support
    [[NSNotificationCenter defaultCenter] addObserver:self
     selector:@selector(sendLaunch:)
     name:UIApplicationDidBecomeActiveNotification
     object:nil];
    // ...
    return YES;
}
// ...
@end
import UIKit
import AppsFlyerLib
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        ...
        // SceneDelegate support
        NotificationCenter.default.addObserver(self, selector: NSSelectorFromString("sendLaunch"), name: UIApplicationdidBecomeActiveNotification, object: nil)
        return true
    }
    // SceneDelegate support - start AppsFlyer SDK
    @objc func sendLaunch() {
        AppsFlyerLib.shared().start()
    }
// ...
}

Start with completion handler

OPCIONAL
To confirm that the SDK started successfully and notified the AppsFlyer servers, call start with a completion handler. You can then apply logic to handle the success or failure of the SDK launch.

[[AppsFlyerLib shared] startWithCompletionHandler:^(NSDictionary<NSString *,id> *dictionary, NSError *error) {
        if (error) {
            NSLog(@"%@", error);
            return;
        }
        if (dictionary) {
            NSLog(@"%@", dictionary);
            return;
        }
    }];
AppsFlyerLib.shared()?.start(completionHandler: { (dictionary, error) in
            if (error != nil){
                print(error ?? "")
                return
            } else {
                print(dictionary ?? "")
                return
            }
        })

Exemplo completo

#import "AppDelegate.h"
#import <AppsFlyerLib/AppsFlyerLib.h>
#import <UserNotifications/UserNotifications.h>
@interface AppDelegate ()
@end
@implementation AppDelegate
    // Start the AppsFlyer SDK
    - (void)sendLaunch:(UIApplication *)application {
    [[AppsFlyerLib shared] start];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    /** APPSFLYER INIT **/
    [AppsFlyerLib shared].appsFlyerDevKey = @"<AF_DEV_KEY>";
    [AppsFlyerLib shared].appleAppID = @"<APPLE_APP_ID>";
    /* Uncomment the following line to see AppsFlyer debug logs */
    // [AppsFlyerLib shared].isDebug = true;
  
    // SceneDelegate support
    [[NSNotificationCenter defaultCenter] addObserver:self
     selector:@selector(sendLaunch:)
     name:UIApplicationDidBecomeActiveNotification
     object:nil];
    if (@available(iOS 10, *)) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        }];
    }

    else {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes: UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }

    [[UIApplication sharedApplication] registerForRemoteNotifications];
    return YES;
}

@end
import UIKit
import AppsFlyerLib
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, AppsFlyerLibDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        AppsFlyerLib.shared().appsFlyerDevKey = "<AF_DEV_KEY>"
        AppsFlyerLib.shared().appleAppID = "<APPLE_APP_ID>"
        /* Uncomment the following line to see AppsFlyer debug logs */
        // AppsFlyerLib.shared().isDebug = true
        // SceneDelegate support
        NotificationCenter.default.addObserver(self, selector: NSSelectorFromString("sendLaunch"), name: UIApplication.didBecomeActiveNotification, object: nil)
        return true
    }
    // SceneDelegate support
    @objc func sendLaunch() {
        AppsFlyerLib.shared().start()
    }
// ...
}

Link do Github

Suporte para iOS 14

A seguir estão os guias sobre como configurar o suporte para os recursos do iOS 14+.

Enabling App Tracking Transparency (ATT) support

Starting iOS 14.5, IDFA access is governed by the ATT framework.
Enabling ATT support in the SDK handles IDFA collection on devices with iOS 14.5+ installed.

🚧

Atenção

Call waitForATTUserAuthorization only if you intend to call requestTrackingAuthorization somewhere in your app.

Etapa 1: Configurar waitForATTUserAuthorization
When Initializing the SDK, before calling start In didFinishLaunchingWithOptions, call waitForATTUserAuthorization:

[[AppsFlyerLib shared] waitForATTUserAuthorizationWithTimeoutInterval:60];
AppsFlyerLib.shared().waitForATTUserAuthorization(timeoutInterval: 60)

Link do Github

Configurado timeoutInterval as such that app users have enough time to see and engage with the ATT prompt. A few examples:

  • Se o prompt da ATT é indicado na inicialização do aplicativo — um intervalo de 60 segundos deve ser suficiente
  • Se o prompt ATT for exibido após um tutorial que leva aproximadamente 2 minutos para ser concluído, um intervalo de 120 segundos deve ser suficiente.

Etapa 2: Chamar requestTrackingAuthorization
Call requestTrackingAuthorization where you wish to display the prompt:

- (void)didBecomeActiveNotification {
    // start is usually called here:
    // [[AppsFlyerLib shared] start]; 
    if @available(iOS 14, *) {
      
      [ATTrackingManager requestTrackingAuthorizationWithCompletionHandler:^(ATTrackingManagerAuthorizationStatus status) {
        NSLog(@"Status: %lu", (unsigned long)status);
      }];
    }
}
@objc func didBecomeActiveNotification() {
    // start is usually called here:
    // AppsFlyerLib.shared().start()
    if #available(iOS 14, *) {
      ATTrackingManager.requestTrackingAuthorization { (status) in
        switch status {
        case .denied:
            print("AuthorizationSatus is denied")
        case .notDetermined:
            print("AuthorizationSatus is notDetermined")
        case .restricted:
            print("AuthorizationSatus is restricted")
        case .authorized:
            print("AuthorizationSatus is authorized")
        @unknown default:
            fatalError("Invalid authorization status")
        }
      }
    }
}

Link do Github

📘

Observação

  • You need to import the AppTrackingTransparency framework to call requestTrackingAuthorization.
  • De acordo com a documentação da Apple:
    • requestTrackingAuthorization is invoked only if the app is in the UIApplicationStateActive state.
    • requestTrackingAuthorization não pode ser invocado a partir das Extensões de Aplicativo.

Customizing the ATT consent dialog

The ATT consent dialog can be customized by modifying your Xcode project's info.plist:

Para obter instruções detalhadas, consulte a documentação da Apple.

Attributing App Clips

Apple App Clips attribution was introduced in iOS SDK V6.0.8. See our App Clips integration guide for detailed instructions.

Sending SKAN postback copies to AppsFlyer

iOS 15
Configure seu aplicativo para enviar cópias de postback para a AppsFlyer.

Para registrar o endpoint da AppsFlyer:

  1. Adicione o NSAdvertisingAttributionReportEndpoint key to your app's info.plist.
  2. Set the key's value to https://appsflyer-skadnetwork.com/.

De acordo com a Apple, você pode definir apenas um ponto final. Cópias de postbacks recebidos estão disponíveis no relatório de cópia de postbacks.

Ativação do modo de depuração

You can enable debug logs by setting isDebug to true:

[AppsFlyerLib shared].isDebug = true;
AppsFlyerLib.shared().isDebug = true

📘

Observação

To see full debug logs, make sure to set isDebug before invoking other SDK methods.

Veja o exemplo.

🚧

Aviso

Para evitar o vazamento de informações confidenciais, verifique se os registros de depuração estão desativados antes de distribuir o aplicativo.

Testando a integração

Para obter instruções detalhadas de teste de integração, consulte o guia de teste de integração do SDK do iOS.


A seguir