Braze SDKの初期化
ランタイム、遅延初期化、Google タグマネージャなどの方法を使用してBraze SDK を初期化する方法について説明します。
Integrating the Android SDK
Step 1: Update your build.gradle
In your build.gradle
, add mavenCentral()
to your list of repositories.
1
2
3
repositories {
mavenCentral()
}
Next, add Braze to your dependencies.
If you don’t plan on using Braze UI components, add the following code to your build.gradle
. Replace SDK_VERSION
with the current version of your Android Braze SDK. For the full list of versions, see Changelogs.
1
2
3
4
dependencies {
implementation 'com.braze:android-sdk-base:SDK_VERSION' // (Required) Adds dependencies for the base Braze SDK.
implementation 'com.braze:android-sdk-location:SDK_VERSION' // (Optional) Adds dependencies for Braze location services.
}
If you plan on using Braze UI components later, add the following code to your build.gradle
. Replace SDK_VERSION
with the current version of your Android Braze SDK. For the full list of versions, see Changelogs.
1
2
3
4
dependencies {
implementation 'com.braze:android-sdk-ui:SDK_VERSION' // (Required) Adds dependencies for the Braze SDK and Braze UI components.
implementation 'com.braze:android-sdk-location:SDK_VERSION' // (Optional) Adds dependencies for Braze location services.
}
Step 2: Configure your braze.xml
As of December 2019, custom endpoints are no longer given out, if you have a pre-existing custom endpoint, you may continue to use it. For more details, refer to our list of available endpoints.
Create a braze.xml
file in your project’s res/values
folder. If you are on a specific data cluster or have a pre-existing custom endpoint, you need to specify the endpoint in your braze.xml
file as well.
The contents of that file should resemble the following code snippet. Make sure to substitute YOUR_APP_IDENTIFIER_API_KEY
with the identifier found in the Manage Settings page of the Braze dashboard. Log in at dashboard.braze.com to find your cluster address.
1
2
3
4
5
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="com_braze_api_key">YOUR_APP_IDENTIFIER_API_KEY</string>
<string translatable="false" name="com_braze_custom_endpoint">YOUR_CUSTOM_ENDPOINT_OR_CLUSTER</string>
</resources>
Step 3: Add permissions to AndroidManifest.xml
Next, add the following permissions to your AndroidManifest.xml
:
1
2
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
With the release of Android M, Android switched from an install-time to a runtime permissions model. However, both of these permissions are normal permissions and are granted automatically if listed in the app manifest. For more information, visit Android’s permission documentation.
Step 4: Enable user session tracking
When you enable user session tracking, calls to openSession()
, closeSession()
,ensureSubscribedToInAppMessageEvents()
, and InAppMessageManager
registration can be handled automatically.
To register activity lifecycle callbacks, add the following code to the onCreate()
method of your Application
class.
1
2
3
4
5
6
7
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(new BrazeActivityLifecycleCallbackListener());
}
}
1
2
3
4
5
6
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
registerActivityLifecycleCallbacks(BrazeActivityLifecycleCallbackListener())
}
}
For the list of available parameters, see BrazeActivityLifecycleCallbackListener
.
Testing session tracking
You can also use the SDK Debugger to diagnose SDK issues.
If you experience issues while testing, enable verbose logging, then use logcat to detect missing openSession
and closeSession
calls in your activities.
- In Braze, go to Overview, select your app, then in the Display Data For dropdown choose Today.
- Open your app, then refresh the Braze dashboard. Verify that your metrics have increased by 1.
- Navigate through your app and verify that only one session has been logged to Braze.
- Send the app to the background for at least 10 seconds, then bring it to the foreground. Verify that a new session was logged.
Optional configurations
Runtime configuration
To set your Braze options in code rather than your braze.xml
file, use runtime configuration. If a value exists in both places, the runtime value will be used instead. After all required settings are supplied at runtime, you can delete your braze.xml
file.
In the following example, a builder object is created and then passed to Braze.configure()
. Note that only some of the available runtime options are shown—refer to our KDoc for the full list.
1
2
3
4
5
6
7
8
BrazeConfig brazeConfig = new BrazeConfig.Builder()
.setApiKey("api-key-here")
.setCustomEndpoint("YOUR_CUSTOM_ENDPOINT_OR_CLUSTER")
.setSessionTimeout(60)
.setHandlePushDeepLinksAutomatically(true)
.setGreatNetworkDataFlushInterval(10)
.build();
Braze.configure(this, brazeConfig);
1
2
3
4
5
6
7
8
val brazeConfig = BrazeConfig.Builder()
.setApiKey("api-key-here")
.setCustomEndpoint("YOUR_CUSTOM_ENDPOINT_OR_CLUSTER")
.setSessionTimeout(60)
.setHandlePushDeepLinksAutomatically(true)
.setGreatNetworkDataFlushInterval(10)
.build()
Braze.configure(this, brazeConfig)
Looking for another example? Check out our Hello Braze sample app.
Google Advertising ID
The Google Advertising ID (GAID) is an optional user-specific, anonymous, unique, and resettable ID for advertising, provided by Google Play services. GAID gives users the power to reset their identifier, opt-out of interest-based ads within Google Play apps, and provides developers with a simple, standard system to continue to monetize their apps.
The Google Advertising ID is not automatically collected by the Braze SDK and must be set manually via the Braze.setGoogleAdvertisingId()
method.
1
2
3
4
5
6
7
8
9
10
11
new Thread(new Runnable() {
@Override
public void run() {
try {
AdvertisingIdClient.Info idInfo = AdvertisingIdClient.getAdvertisingIdInfo(getApplicationContext());
Braze.getInstance(getApplicationContext()).setGoogleAdvertisingId(idInfo.getId(), idInfo.isLimitAdTrackingEnabled());
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
suspend fun fetchAndSetAdvertisingId(
context: Context,
scope: CoroutineScope = GlobalScope
) {
scope.launch(Dispatchers.IO) {
try {
val idInfo = AdvertisingIdClient.getAdvertisingIdInfo(context)
Braze.getInstance(context).setGoogleAdvertisingId(
idInfo.id,
idInfo.isLimitAdTrackingEnabled
)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
Google requires the Advertising ID to be collected on a non-UI thread.
Location tracking
To enable Braze location collection, set com_braze_enable_location_collection
to true
in your braze.xml
file:
1
<bool name="com_braze_enable_location_collection">true</bool>
Starting with Braze Android SDK version 3.6.0, Braze location collection is disabled by default.
Logging
By default, the Braze Android SDK log level is set to INFO
. You can suppress these logs or set a different log level, such as VERBOSE
, DEBUG
, or WARN
.
Enabling logs
To help troubleshoot issues in your app, or reduce turnaround times with Braze Support, you’ll want to enable verbose logs for the SDK. When you send verbose logs to Braze Support, ensure they begin as soon as you launch your application and end far after your issue occurs.
Keep in mind, verbose logs are only intended for your development environment, so you’ll want to disable them before releasing your app.
Enable verbose logs before any other calls in Application.onCreate()
to ensure your logs are as complete as possible.
To enable logs directly in your app, add the following to your application’s onCreate()
method before any other methods.
1
BrazeLogger.setLogLevel(Log.MIN_LOG_LEVEL);
1
BrazeLogger.logLevel = Log.MIN_LOG_LEVEL
Replace MIN_LOG_LEVEL
with the Constant of the log level you’d like to set as your minimum log level. Any logs at a level >=
to your set MIN_LOG_LEVEL
will be forwarded to Android’s default Log
method. Any logs <
your set MIN_LOG_LEVEL
will be discarded.
Constant | Value | Description |
---|---|---|
VERBOSE |
2 | Logs the most detailed messages for debugging and development. |
DEBUG |
3 | Logs descriptive messages for debugging and development. |
INFO |
4 | Logs informational messages for general highlights. |
WARN |
5 | Logs warning messages for identifying potentially harmful situations. |
ERROR |
6 | Logs error messages for indicating application failure or serious issues. |
ASSERT |
7 | Logs assertion messages when conditions are false during development. |
For example, the following code will forward log levels 2
, 3
, 4
, 5
, 6
, and 7
to the Log
method.
1
BrazeLogger.setLogLevel(Log.VERBOSE);
1
BrazeLogger.logLevel = Log.VERBOSE
To enable logs in the braze.xml
, add the following to your file:
1
<integer name="com_braze_logger_initial_log_level">MIN_LOG_LEVEL</integer>
Replace MIN_LOG_LEVEL
with the Value of the log level you’d like to set as your minimum log level. Any logs at a level >=
to your set MIN_LOG_LEVEL
will be forwarded to Android’s default Log
method. Any logs <
your set MIN_LOG_LEVEL
will be discarded.
Constant | Value | Description |
---|---|---|
VERBOSE |
2 | Logs the most detailed messages for debugging and development. |
DEBUG |
3 | Logs descriptive messages for debugging and development. |
INFO |
4 | Logs informational messages for general highlights. |
WARN |
5 | Logs warning messages for identifying potentially harmful situations. |
ERROR |
6 | Logs error messages for indicating application failure or serious issues. |
ASSERT |
7 | Logs assertion messages when conditions are false during development. |
For example, the following code will forward log levels 2
, 3
, 4
, 5
, 6
, and 7
to the Log
method.
1
<integer name="com_braze_logger_initial_log_level">2</integer>
Verifying verbose logs
To verify that your logs are set to VERBOSE
, check if V/Braze
occurs somewhere in your logs. If it does, then verbose logs have been successfully enabled. For example:
1
2077-11-19 16:22:49.591 ? V/Braze v9.0.01 .bo.app.d3: Request started
Suppressing logs
To suppress all logs for the Braze Android SDK, set the log level to BrazeLogger.SUPPRESS
in your application’s onCreate()
method before any other methods.
1
BrazeLogger.setLogLevel(BrazeLogger.SUPPRESS);
1
BrazeLogger.setLogLevel(BrazeLogger.SUPPRESS)
Multiple API keys
The most common use case for multiple API keys is separating API keys for debug and release build variants.
To easily switch between multiple API keys in your builds, we recommend creating a separate braze.xml
file for each relevant build variant. A build variant is a combination of build type and product flavor. By default, new Android projects are configured with debug
and release
build types and no product flavors.
For each relevant build variant, create a new braze.xml
in the src/<build variant name>/res/values/
directory. When the build variant is compiled, it will use the new API key.
1
2
3
4
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="com_braze_api_key">REPLACE_WITH_YOUR_BUILD_VARIANT_API_KEY</string>
</resources>
To learn how to set up the API key in your code, see Runtime configuration.
Exclusive in-app message TalkBack
In adherence to the Android accessibility guidelines, the Braze Android SDK offers Android Talkback by default. To ensure that only the contents of in-app messages are read out loud—without including other screen elements like the app title bar or navigation—you can enable exclusive mode for TalkBack.
To enable exclusive mode for in-app messages:
1
<bool name="com_braze_device_in_app_message_accessibility_exclusive_mode_enabled">true</bool>
1
2
3
val brazeConfigBuilder = BrazeConfig.Builder()
brazeConfigBuilder.setIsInAppMessageAccessibilityExclusiveModeEnabled(true)
Braze.configure(this, brazeConfigBuilder.build())
1
2
3
BrazeConfig.Builder brazeConfigBuilder = new BrazeConfig.Builder()
brazeConfigBuilder.setIsInAppMessageAccessibilityExclusiveModeEnabled(true);
Braze.configure(this, brazeConfigBuilder.build());
R8 and ProGuard
Code shrinking configuration is automatically included with your Braze integration.
Client apps that obfuscate Braze code must store release mapping files for Braze to interpret stack traces. If you want to continue to keep all Braze code, add the following to your ProGuard file:
1
2
-keep class bo.app.** { *; }
-keep class com.braze.** { *; }
guide/prerequisites/swift.md developer_ %}
遅延初期化の使用
Braze Swift SDK は非同期に初期化できますが、プッシュ通知の処理は保持されます。これは、サーバーから構成データを取得したり、ユーザーの同意を待ったりするなど、SDK を初期化する前に他のサービスを設定する必要がある場合に役立ちます。
考慮事項
Braze.prepareForDelayedInitialization(pushAutomation:)
を使用すると、SDK が自動的にプッシュ通知自動化機能を使用するように設定されます。プッシュ通知を処理するシステムデリゲートメソッドは、Brazeから発信されたプッシュ通知に対しては呼び出されない。
SDK は、SDK が初期化された後にのみ、Braze プッシュ通知とその結果のアクションを処理します。例えば、ユーザーがディープリンクを開くプッシュ通知をタップした場合、ディープリンクは Braze
インスタンスが初期化された後にのみ開きます。
Braze プッシュ通知で追加の処理を実行する必要がある場合は、[プッシュ通知更新を購読する] を参照してください。以前にキューに登録されたプッシュ通知の更新を受信するには、SDK を初期化した後、サブスクリプションハンドラを直接実装する必要があることに留意してください。
ステップ1:SDKの準備
デフォルトでは、アプリが終了状態にあるときにエンドユーザーがプッシュ通知を開いた場合、SDK が初期化されるまでプッシュ通知を処理できません。
Braze Swift SDK バージョン 10.1.0 以降では、静的ヘルパーメソッド Braze.prepareForDelayedInitialization(pushAutomation:) を使用してこれを処理できます。このメソッドは、プッシュオートメーションシステムを設定することで、遅延初期化用に SDK を準備します。
SDKが初期化される前に、Brazeから発信されるすべてのプッシュ通知がキャプチャされ、キューに入れられる。SDK が初期化されると、それらのプッシュ通知は SDK によって処理されます。このメソッドは、アプリケーションのライフサイクルのできるだけ早い段階で、AppDelegate
の application(_:didFinishLaunchingWithOptions:)
メソッド内またはその前に呼び出す必要があります。
Swift SDK は Braze 以外のプッシュ通知をキャプチャしません。そのような通知は引き続きシステムデリゲートメソッドによって処理されます。
1
2
3
4
5
6
7
8
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Prepare the SDK for delayed initialization
Braze.prepareForDelayedInitialization()
// ... Additional non-Braze setup code
return true
}
SwiftUI アプリケーションはprepareForDelayedInitialization()
メソッドを呼び出すために@UIApplicationDelegateAdaptorプロパティラッパーを実装する必要がある。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@main
struct MyApp: App {
@UIApplicationDelegateAdaptor var appDelegate: AppDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
// Prepare the SDK for delayed initialization
Braze.prepareForDelayedInitialization()
// ... Additional non-Braze setup code
return true
}
}
1
2
3
4
5
6
7
8
9
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Prepare the SDK for delayed initialization
[Braze prepareForDelayedInitialization];
// ... Additional non-Braze setup code
return YES;
}
Braze.prepareForDelayedInitialization(pushAutomation:) は、プッシュ通知のオートメーション設定を表すオプションの pushAutomation
パラメータを取ります。Braze.Configuration.Push.Automation が nil
の場合、起動時に承認を要求することを除き、すべてのオートメーション機能が有効になります。
ステップ2:SDK の初期化
遅延初期化用に SDK を準備したら、将来いつでも SDK を非同期的に初期化できます。次に、SDK は Braze から発信されキューに入れられたすべてのプッシュ通知イベントを処理します。
Braze SDK を初期化するには、標準の Swift SDK 初期化プロセスに従います。
Google タグマネージャの使用
Braze Swift SDK は、Google Tag Manager 内で設定されたタグによって初期化および制御できます。
次の例では、音楽ストリーミングアプリは、ユーザーが曲を聴くときに異なるイベントを記録することを求めています。Google Tag Manager for iOS を使用すると、Braze のサードパーティベンダーのどのベンダーがこのイベントを受信し、Braze に固有のタグを作成するかを制御できます。
ステップ1:カスタムイベントのトリガーを作成する
カスタムイベントは、logEvent
に設定した actionType
によってログに記録されます。この例では、Braze カスタムタグプロバイダは、eventName
を使用してカスタムイベント名を設定することを期待しています。
まず、played song
に等しいeventName
を探すトリガを作成します。
次に、新しいタグ(“Function Call”とも呼ばれます)を作成し、この記事で後述するカスタムタグプロバイダーのクラスパスを入力します。このタグは、played song
イベントをログに記録するとトリガーされます。eventName
はplayed song
に設定されているため、Braze に記録されるカスタムイベント名として使用されます。
カスタムイベントを送信する場合、actionType
をlogEvent
に設定し、eventName
の値を設定すると、Braze は正しいイベント名とアクションを受け取ります。
また、追加のキーと値のペア引数をタグに含めることもできます。この引数は、カスタムイベントプロパティとして Braze に送信されます。eventName
および actionType
は、カスタムイベントプロパティで無視されません。次の例のタグでは、genre
を渡します。これは、Google タグマネージャでタグ変数を使用して定義され、アプリに記録されたカスタムイベントから取得されます。
genre
イベントプロパティが、「Firebase - Event Parameter」変数として Google Tag Manager に送信されます。Google Tag Manager for iOS では、Firebase がデータレイヤーとして使用されるためです。
ユーザがアプリで曲を再生すると、Firebase とGoogle Tag Manager を介して、タグのトリガ名played song
に一致するFirebase 分析イベント名を使用してイベントをログに記録します。
1
2
3
let parameters: [String: Any] = ["genre": "pop",
"number of times listened": 42]
Analytics.logEvent("played song", parameters: parameters)
1
2
3
NSDictionary *parameters = @{@"genre" : @"pop",
@"number of times listened" : @42};
[FIRAnalytics logEventWithName:@"played song" parameters:parameters];
ステップ2:カスタム属性のログ
カスタム属性は、customAttribute
に設定された actionType
を介して設定されます。Braze カスタムタグプロバイダーは、カスタム属性のキーと値が customAttributeKey
および customAttributeValue
を介して設定されることを想定しています。
1
2
3
let parameters: [String: Any] = ["customAttributeKey": "favoriteSong",
"customAttributeValue": "Private Eyes"]
FIRAnalytics.logEvent(withName:"customAttribute", parameters: parameters)
1
2
3
NSDictionary *parameters = @{@"customAttributeKey" : @"favoriteSong",
@"customAttributeValue" : @"Private Eyes"};
[FIRAnalytics logEventWithName:@"customAttribute" parameters:parameters];
ステップ 3:コール changeUser()
changeUser()
の呼び出しは、changeUser
に設定された actionType
を介して行われます。Braze カスタムタグプロバイダーは、Braze ユーザー ID がタグ内のキーと値のペア externalUserId
を介して設定されることを想定しています。
1
2
let parameters: [String: Any] = ["externalUserId": "favorite userId"]
Analytics.logEvent(withName:"changeUser", parameters: parameters)
1
2
NSDictionary *parameters = @{@"externalUserId" : userId};
[FIRAnalytics logEventWithName:@"changeUser" parameters:parameters];
ステップ 4:カスタムタグプロバイダの追加
タグとトリガーが設定されたら、iOS アプリに Google Tag Manager を実装する必要もあります。これについては、Google のドキュメントに記載されています。
Googleタグマネージャがアプリにインストールされたら、カスタムタグプロバイダを追加して、Googleタグマネージャで設定したタグに基づいてBraze SDK メソッドを呼び出します。
Google Tag Managerコンソールでタグを設定するときに入力するのは、ファイルに”Class Path”を必ず書き留めておいてください。
この例では、カスタムタグプロバイダを構築するさまざまな方法の1 つを強調表示します。具体的には、GTM タグから送信されたactionType
キーと値のペアに基づいて、どのBraze SDK メソッドを呼び出すかを決定する方法を示します。この例では、AppDelegate で変数として Braze インスタンスを割り当てていると仮定しています。
この例でサポートされているactionType
は、logEvent
、customAttribute
、およびchangeUser
ですが、タグプロバイダーによるGoogle タグマネージャからのデータの処理方法を変更することをお勧めします。
以下のコードを BrazeGTMTagManager.swift
ファイルに追加します。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import FirebaseAnalytics
import GoogleTagManager
import BrazeKit
let ActionTypeKey: String = "actionType"
// Custom Events
let LogEventAction: String = "logEvent"
let LogEventName: String = "eventName"
// Custom Attributes
let CustomAttributeAction: String = "customAttribute"
let CustomAttributeKey: String = "customAttributeKey"
let CustomAttributeValueKey: String = "customAttributeValue"
// Change User
let ChangeUserAction: String = "changeUser"
let ChangeUserExternalUserId: String = "externalUserId"
@objc(BrazeGTMTagManager)
final class BrazeGTMTagManager : NSObject, TAGCustomFunction {
@objc func execute(withParameters parameters: [AnyHashable : Any]!) -> NSObject! {
var parameters: [String : Any] = parameters as! [String : Any]
guard let actionType: String = parameters[ActionTypeKey] as? String else {
print("There is no Braze action type key in this call. Doing nothing.")
return nil
}
parameters.removeValue(forKey: ActionTypeKey)
if actionType == LogEventAction {
logEvent(parameters: parameters)
} else if actionType == CustomAttributeAction {
logCustomAttribute(parameters: parameters)
} else if actionType == ChangeUserAction {
changeUser(parameters: parameters)
}
return nil
}
func logEvent(parameters: [String : Any]) {
var parameters: [String : Any] = parameters
guard let eventName: String = parameters[LogEventName] as? String else { return }
parameters.removeValue(forKey: LogEventName)
AppDelegate.braze?.logCustomEvent(name: eventName, properties: parameters)
}
func logCustomAttribute(parameters: [String: Any]) {
guard let customAttributeKey = parameters[CustomAttributeKey] as? String else { return }
let customAttributeValue = parameters[CustomAttributeValueKey]
if let customAttributeValue = customAttributeValue as? String {
AppDelegate.braze?.user.setCustomAttribute(key: customAttributeKey, value: customAttributeValue)
} else if let customAttributeValue = customAttributeValue as? Date {
AppDelegate.braze?.user.setCustomAttribute(key: customAttributeKey, value: customAttributeValue)
} else if let customAttributeValue = customAttributeValue as? Double {
AppDelegate.braze?.user.setCustomAttribute(key: customAttributeKey, value: customAttributeValue)
} else if let customAttributeValue = customAttributeValue as? Bool {
AppDelegate.braze?.user.setCustomAttribute(key: customAttributeKey, value: customAttributeValue)
} else if let customAttributeValue = customAttributeValue as? Int {
AppDelegate.braze?.user.setCustomAttribute(key: customAttributeKey, value: customAttributeValue)
} else if let customAttibuteValue = customAttributeValue as? [String] {
AppDelegate.braze?.user.setCustomAttributeArray(key: customAttributeKey, array: customAttibuteValue)
}
}
func changeUser(parameters: [String: Any]) {
guard let userId = parameters[ChangeUserExternalUserId] as? String else { return }
AppDelegate.braze?.changeUser(userId: userId)
}
}
以下のコードを BrazeGTMTagManager.h
ファイルに追加します。
1
2
3
4
5
6
@import Firebase;
@import GoogleTagManager;
@interface BrazeGTMTagManager : NSObject <TAGCustomFunction>
@end
以下のコードを BrazeGTMTagManager.m
ファイルに追加します。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#import <Foundation/Foundation.h>
#import "BrazeGTMTagManager.h"
#import "BrazeKit"
#import "AppDelegate.h"
static NSString *const ActionTypeKey = @"actionType";
// Custom Events
static NSString *const LogEventAction = @"logEvent";
static NSString *const LogEventEventName = @"eventName";
// Custom Attributes
static NSString *const CustomAttributeAction = @"customAttribute";
static NSString *const CustomAttributeKey = @"customAttributeKey";
static NSString *const CustomAttributeValueKey = @"customAttributeValue";
// Change User
static NSString *const ChangeUserAction = @"changeUser";
static NSString *const ChangeUserExternalUserId = @"externalUserId";
@implementation BrazeGTMTagManager
- (NSObject *)executeWithParameters:(NSDictionary *)parameters {
NSMutableDictionary *mutableParameters = [parameters mutableCopy];
NSString *actionType = mutableParameters[ActionTypeKey];
if (!actionType) {
NSLog(@"There is no Braze action type key in this call. Doing nothing.", nil);
return nil;
}
[mutableParameters removeObjectForKey:ActionTypeKey];
if ([actionType isEqualToString:LogEventAction]) {
[self logEvent:mutableParameters];
} else if ([actionType isEqualToString:CustomAttributeAction]) {
[self logCustomAttribute:mutableParameters];
} else if ([actionType isEqualToString:ChangeUserAction]) {
[self changeUser:mutableParameters];
} else {
NSLog(@"Invalid action type. Doing nothing.");
}
return nil;
}
- (void)logEvent:(NSMutableDictionary *)parameters {
NSString *eventName = parameters[LogEventEventName];
[parameters removeObjectForKey:LogEventEventName];
[AppDelegate.braze logCustomEvent:eventName
properties:parameters];
}
- (void)logCustomAttribute:(NSMutableDictionary *)parameters {
NSString *customAttributeKey = parameters[CustomAttributeKey];
id customAttributeValue = parameters[CustomAttributeValueKey];
if ([customAttributeValue isKindOfClass:[NSString class]]) {
[AppDelegate.braze logCustomEvent:customAttributeKey
properties:parameters];
} else if ([customAttributeValue isKindOfClass:[NSDate class]]) {
[AppDelegate.braze.user setCustomAttributeWithKey:customAttributeKey
dateValue:customAttributeValue];
} else if ([customAttributeValue isKindOfClass:[NSNumber class]]) {
if (strcmp([customAttributeValue objCType], [@(YES) objCType]) == 0) {
[AppDelegate.braze.user setCustomAttributeWithKey:customAttributeKey
boolValue:[(NSNumber *)customAttributeValue boolValue]];
} else if (strcmp([customAttributeValue objCType], @encode(short)) == 0 ||
strcmp([customAttributeValue objCType], @encode(int)) == 0 ||
strcmp([customAttributeValue objCType], @encode(long)) == 0) {
[AppDelegate.braze.user setCustomAttributeWithKey:customAttributeKey
intValue:[(NSNumber *)customAttributeValue integerValue]];
} else if (strcmp([customAttributeValue objCType], @encode(float)) == 0 ||
strcmp([customAttributeValue objCType], @encode(double)) == 0) {
[AppDelegate.braze.user setCustomAttributeWithKey:customAttributeKey
doubleValue:[(NSNumber *)customAttributeValue doubleValue]];
} else {
NSLog(@"Could not map NSNumber value to Braze custom attribute:%@", customAttributeValue);
}
} else if ([customAttributeValue isKindOfClass:[NSArray class]]) {
[AppDelegate.braze.user setCustomAttributeArrayWithKey:customAttributeKey
array:customAttributeValue];
}
}
- (void)changeUser:(NSMutableDictionary *)parameters {
NSString *userId = parameters[ChangeUserExternalUserId];
[AppDelegate.braze changeUser:userId];
}
@end
Googleタグマネージャーを使う
ステップ1:プッシュセットアップ(オプション)
オプションで、Google タグマネージャをプッシュ送信できるようにするには、まずpush integration のガイドラインに従い、以下の手順を実行します。
- サイトのサービスワーカーを設定し、サイトのルートディレクトリに配置します
- ブラウザ登録を設定する- サービスワーカーが設定されたら、
braze.requestPushPermission()
メソッドをアプリまたはカスタムHTML タグ(GTM ダッシュボードを使用) でネイティブに設定する必要があります。また、SDK が初期化された後にタグが実行されるようにする必要があります。
ステップ2:初期化タグの選択
コミュニティーテンプレートギャラリーでBrazeを検索し、Braze初期化タグを選択します。
ステップ3: 設定の構成
Braze API アプリ 識別子キーとSDKエンドポイントを入力します。これは、ダッシュボードの設定の管理 ページにあります。Web SDKの最新のmajor.minor
バージョンを入力します。たとえば、最新バージョンが4.1.2
の場合、4.1
と入力します。SDKのバージョン一覧は変更履歴で見ることができる。
ステップ 4:初期化オプションの選択
初期設定 ガイドで説明されている追加の初期化オプションのオプションセットから選択します。
ステップ5: 検証とQA
このタグを展開したら、次の2つの方法で適切な統合を確認できます。
- Googleタグマネージャーのデバッグツールを使って、設定したページやイベントでBraze初期化タグがトリガーされたことを確認する。
- Braze に対して行われたネットワークリクエストが表示され、グローバル
window.braze
ライブラリが Web ページで定義されます。
guide/prerequisites/unreal_engine.md developer_ %}
SDKを初期化する
Brazeが初期化されるタイミングを正確にコントロールしたい場合は、DefaultEngine.ini
ファイルでAutoInitialize
を無効にすることができる。AutoInitialize
を無効にした後は、ネイティブC++またはBlueprintからBrazeを手動で初期化する必要がある。
ネイティブC++でBrazeSubsystemにアクセスし、InitializeBraze()
を呼び出す。オプションでConfigを渡し、Engine.ini の設定を上書きする。
1
2
UBrazeSubsystem* const BrazeSubsystem = GEngine->GetEngineSubsystem<UBrazeSubsystem>();
UBraze* const BrazeInstance = BrazeSubsystem->InitializeBraze();
ブループリントでは、ブループリント・ノードと同じ機能にアクセスできる:
GetBrazeSubsystem
ノードを使って、そのInitialize
ノードを呼び出す。
オプションで、BrazeConfigオブジェクトをBlueprintで作成し、以下に渡すことができる。 Initialize