SDKの実装

iOS SDKを初期化し開始する方法を説明します。

始める前に

Get started with our SDK integration wizard

  • 実装の前に、SDKをインストールする必要があります。
  • このドキュメントには実装の例が含まれています。次の部分を置き換えて実装してください。
    • <YOUR_DEV_KEY>:AppsFlyer Devキー。
    • <APPLE_APP_ID>: The Apple App ID (without the id prefix).
    • 必要に応じて、追加のプレースホルダー。

iOS SDKの初期化

ステップ1:依存関係のインポート
インポート AppsFlyerLib:

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

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@end
import UIKit
import AppsFlyerLib

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

ステップ2:SDKの初期化
In didFinishLaunchingWithOptions configure your Apple App ID and AppsFlyer dev key:

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

iOS SDKの開始

In applicationDidBecomeActive, call start:

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

Add SceneDelegate support

オプション
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

オプション
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
            }
        })

#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 = @"<YOUR_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 {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        AppsFlyerLib.shared().appsFlyerDevKey = "<YOUR_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()
    }
// ...
}

Githubリンク

カスタマーユーザーID の設定

オプション
カスタマーユーザー ID (CUID) は、アプリの所有者(事業主側)が採番する一意のユーザー識別子です。SDKで利用できる場合は、インストールやその他のアプリ内イベントに関連付けることができます。これらのCUIDタグ付きイベントは、他のデバイスやアプリケーションのユーザデータと相互参照できます。

Set the CUID

CUIDを設定する:

[AppsFlyerLib shared].customerUserID = @"my user id";
AppsFlyerLib.shared().customerUserID = "my user id"

📘

注意

The Customer User ID must be set with every app launch.

Associate the CUID with the install event

If it’s important for you to associate the install event with the CUID, you should set to set the customerUserId before calling the start method. This is because start sends the install event to AppsFlyer. If the CUID is set after calling start, it will not be associated with the install event.

- (void)applicationDidBecomeActive:(UIApplication *)application {
  	// Your custom logic of retrieving CUID
    NSString *customUserId = [[NSUserDefaults standardUserDefaults] stringForKey:@"customerUserId"];  
    if (customUserId != nil && ![customUserId  isEqual: @""]) {
        // Set CUID in AppsFlyer SDK for this session
        [AppsFlyerLib shared].customerUserID = customUserId; 
        // Start
        [[AppsFlyerLib shared] start]; 
    }
}
func applicationDidBecomeActive(_ application: UIApplication) {
  //  your logic to retrieve CUID
  let customUserId = UserDefaults.standard.string(forKey: "customUserId") 
  
  if(customUserId != nil && customUserId != ""){
     // Set CUID in AppsFlyer SDK for this session
    AppsFlyerLib.shared().customerUserID = customUserId    
    AppsFlyerLib.shared().start() // Start
  }
}

Log sessions

The SDK sends an af_app_opened message whenever the app is opened or brought to the foreground, providing that start is called in the didBecomeActive lifecycle event method. Before the message is sent, the SDK makes sure that the time passed since sending the last message is not smaller than a predefined interval.

Setting the time interval between app launches

設定済 minTimeBetweenSessions to the minimal time interval that must lapse between two af_app_opened messages. The default interval is 5 seconds.

iOS 14サポート

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.

🚧

注記

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

ステップ1:セットアップ waitForATTUserAuthorization
When Initializing the SDK, before calling start In applicationDidBecomeActive, call waitForATTUserAuthorization:

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

Githubリンク

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

  • アプリの初回起動時にATTのポップアップが表示される場合には、60秒程度の設定で十分でしょう。
  • チュートリアル完了の後にATTのポップアップが表示され、チュートリアルの完了までに約 2 分かかるのであれば、180秒程度の設定で十分でしょう。

ステップ2:呼び出し 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")
        }
      }
    }
}

Githubリンク

📘

注意

  • You need to import the AppTrackingTransparency framework to call requestTrackingAuthorization.
  • Appleのドキュメントによると:
    • requestTrackingAuthorization is invoked only if the app is in the UIApplicationStateActive state.
    • requestTrackingAuthorization は App Extenions からは呼び出すことはできません

Customizing the ATT consent dialog

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

詳しい説明は、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
ポストバックのコピーをAppsFlyerに送信するようにアプリを設定してください。

AppsFlyerのエンドポイントを登録する方法:

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

Appleによると、1つのエンドポイントのみを設定できます。受信したポストバックのコピーはポストバックコピーレポートにて確認できます。

デバッグモードの有効化

You can enable debug logs by setting isDebug to true:

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

📘

注意

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

を参照してください。

🚧

警告

機密情報の漏洩を防ぐため、アプリをリリースする前にデバッグログが無効になっていることを確認してください。

連携のテスト

連携テストの詳細な手順は、iOS SDK連携テストガイドを参照してください。