Intégration du SDK de Braze
Découvrez comment intégrer le SDK de Braze dans votre application mobile. Chaque SDK est hébergé dans son propre dépôt public GitHub, qui comprend des exemples d’applications entièrement constructibles que vous pouvez utiliser pour tester les fonctionnalités de Braze ou mettre en œuvre parallèlement à vos propres applications. Pour en savoir plus, consultez les références, les référentiels et les exemples d’applications. Pour plus d’informations générales sur le SDK, consultez le site Getting started : Aperçu de l’intégration.
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.** { *; }
Integrating the Swift SDK
You can integrate and customize the Braze Swift SDK using the Swift Package Manager (SPM), CocoaPods, or manual integration methods. For more information about the various SDK symbols, see Braze Swift reference documentation.
Prerequisites
Before you start, verify your environment is supported by the latest Braze Swift SDK version.
Step 1: Install the Braze Swift SDK
We recommend using the Swift Package Manager (SwiftPM) or CocoaPods to install the Braze Swift SDK. Alternatively, you can install the SDK manually.
Step 1.1: Import SDK version
Open your project and navigate to your project’s settings. Select the Swift Packages tab and click on the add button below the packages list.
Starting in version 7.4.0, the Braze Swift SDK has additional distribution channels as static XCFrameworks and dynamic XCFrameworks. If you’d like to use either of these formats instead, follow the installation instructions from its respective repository.
Enter the URL of our iOS Swift SDK repository https://github.com/braze-inc/braze-swift-sdk
in the text field. Under the Dependency Rule section, select the SDK version. Finally, click Add Package.
Step 1.2: Select your packages
The Braze Swift SDK separates features into standalone libraries to provide developers with more control over which features to import into their projects.
Package | Details |
---|---|
BrazeKit |
Main SDK library providing support for analytics and push notifications. |
BrazeLocation |
Location library providing support for location analytics and geofence monitoring. |
BrazeUI |
Braze-provided user interface library for in-app messages, Content Cards, and Banners. Import this library if you intend to use the default UI components. |
About Extension libraries
BrazeNotificationService and BrazePushStory are extension modules that provide additional functionality and should not be added directly to your main application target. Instead follow the linked guides to integrate them separately into their respective target extensions.
Package | Details |
---|---|
BrazeNotificationService |
Notification service extension library providing support for rich push notifications. |
BrazePushStory |
Notification content extension library providing support for Push Stories. |
Select the package that best suits your needs and click Add Package. Make sure you select BrazeKit
at a minimum.
Step 1.1: Install CocoaPods
For a full walkthrough, see CocoaPods’ Getting Started Guide. Otherwise, you can run the following command to get started quickly:
1
$ sudo gem install cocoapods
If you get stuck, checkout CocoaPods’ Troubleshooting Guide.
Step 1.2: Constructing the Podfile
Next, create a file in your Xcode project directory named Podfile
.
Starting in version 7.4.0, the Braze Swift SDK has additional distribution channels as static XCFrameworks and dynamic XCFrameworks. If you’d like to use either of these formats instead, follow the installation instructions from its respective repository.
Add the following line to your Podfile:
1
2
3
target 'YourAppTarget' do
pod 'BrazeKit'
end
BrazeKit
contains the main SDK library, providing support for analytics and push notifications.
We suggest you version Braze so pod updates automatically grab anything smaller than a minor version update. This looks like pod 'BrazeKit' ~> Major.Minor.Build
. If you want to automatically integrate the latest Braze SDK version, even with major changes, you can use pod 'BrazeKit'
in your Podfile.
About additional libraries
The Braze Swift SDK separates features into standalone libraries to provide developers with more control over which features to import into their projects. In addition to BrazeKit
, you may add the following libraries to your Podfile:
Library | Details |
---|---|
pod 'BrazeLocation' |
Location library providing support for location analytics and geofence monitoring. |
pod 'BrazeUI' |
Braze-provided user interface library for in-app messages, Content Cards, and Banners. Import this library if you intend to use the default UI components. |
Extension libraries
BrazeNotificationService and BrazePushStory are extension modules that provide additional functionality and should not be added directly to your main application target. Instead, you will need to create separate extension targets for each of these modules and import the Braze modules into their corresponding targets.
Library | Details |
---|---|
pod 'BrazeNotificationService' |
Notification service extension library providing support for rich push notifications. |
pod 'BrazePushStory' |
Notification content extension library providing support for Push Stories. |
Step 1.3: Install the SDK
To install the Braze SDK CocoaPod, navigate to the directory of your Xcode app project within your terminal and run the following command:
1
pod install
At this point, you should be able to open the new Xcode project workspace created by CocoaPods. Make sure to use this Xcode workspace instead of your Xcode project.
Updating the SDK using CocoaPods
To update a CocoaPod, simply run the following command within your project directory:
1
pod update
Step 1.1: Download the Braze SDK
Go to the Braze SDK release page on GitHub, then download braze-swift-sdk-prebuilt.zip
.
Step 1.2: Choose your frameworks
The Braze Swift SDK contains a variety of standalone XCFrameworks, which gives you the freedom to integrate the features you want—without needing to integrate them all. Reference the following table to choose your XCFrameworks:
Package | Required? | Description |
---|---|---|
BrazeKit |
Yes | Main SDK library that provides support for analytics and push notifications. |
BrazeLocation |
No | Location library that provides support for location analytics and geofence monitoring. |
BrazeUI |
No | Braze-provided user interface library for in-app messages, Content Cards, and Banners. Import this library if you intend to use the default UI components. |
BrazeNotificationService |
No | Notification service extension library that provides support for rich push notifications. Do not add this library directly to your main application target, instead add the BrazeNotificationService library separately. |
BrazePushStory |
No | Notification content extension library that provides support for Push Stories. Do not add this library directly to your main application target, instead add the BrazePushStory library separately. |
BrazeKitCompat |
No | Compatibility library containing all the Appboy and ABK* classes and methods that were available in the Appboy-iOS-SDK version 4.X.X. For usage details, refer to the minimal migration scenario in the migration guide. |
BrazeUICompat |
No | Compatibility library containing all the ABK* classes and methods that were available in the AppboyUI library from Appboy-iOS-SDK version 4.X.X. For usage details, refer to the minimal migration scenario in the migration guide. |
SDWebImage |
No | Dependency used only by BrazeUICompat in the minimal migration scenario. |
Step 1.3: Prepare your files
Decide whether you want to use Static or Dynamic XCFrameworks, then prepare your files:
- Create a temporary directory for your XCFrameworks.
- In
braze-swift-sdk-prebuilt
, open thedynamic
directory and moveBrazeKit.xcframework
into your directory. Your directory should be similar to the following:1 2
temp_dir └── BrazeKit.xcframework
- Move each of your chosen XCFrameworks into your temporary directory. Your directory should be similar to the following:
1 2 3 4 5
temp_dir ├── BrazeKit.xcframework ├── BrazeKitCompat.xcframework ├── BrazeLocation.xcframework └── SDWebImage.xcframework
Step 1.4: Integrate your frameworks
Next, integrate the Dynamic or Static XCFrameworks you prepared previously:
In your Xcode project, select your build target, then General. Under Frameworks, Libraries, and Embedded Content, drag and drop the files you prepared previously.
Starting with the Swift SDK 12.0.0, you should always select Embed & Sign for the Braze XCFrameworks for both the static and dynamic variants. This ensures that the frameworks resources are properly embedded in your app bundle.
To enable GIF support, add SDWebImage.xcframework
, located in either braze-swift-sdk-prebuilt/static
or braze-swift-sdk-prebuilt/dynamic
.
Common errors for Objective-C projects
If your Xcode project only contains Objective-C files, you may get “missing symbol” errors when you try to build your project. To fix these errors, open your project and add an empty Swift file to your file tree. This will force your build toolchain to embed Swift Runtime and link to the appropriate frameworks during build time.
1
FILE_NAME.swift
Replace FILE_NAME
with any non-spaced string. Your file should look similar to the following:
1
empty_swift_file.swift
Step 2: Set up delayed initialization (optional)
You can choose to delay when the Braze Swift SDK is initialized, which is useful if your app needs to load config or wait for user consent before starting the SDK. Delayed initialization ensures Braze push notifications are queued until the SDK is ready.
To enable this, call Braze.prepareForDelayedInitialization()
as early as possible—ideally inside or before your application(_:didFinishLaunchingWithOptions:)
.
This only applies to push notifications from Braze. Other push notifications are handled normally by system delegates.
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
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@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
- (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:)
accepts an optional pushAutomation
parameter. If set to nil
, all push automation features are enabled, except requesting push authorization at launch.
Step 3: Update your app delegate
The following assumes you’ve already added an AppDelegate
to your project (which are not generated by default). If you don’t plan on using one, be sure to initialize the Braze SDK as early as possible, like during the app’s launch.
Add the following line of code to your AppDelegate.swift
file to import the features included in the Braze Swift SDK:
1
import BrazeKit
Next, add a static property to your AppDelegate
class to keep a strong reference to the Braze instance throughout your application’s lifetime:
1
2
3
class AppDelegate: UIResponder, UIApplicationDelegate {
static var braze: Braze? = nil
}
Finally, in AppDelegate.swift
, add the following snippet to your application:didFinishLaunchingWithOptions:
method:
1
2
3
4
5
6
let configuration = Braze.Configuration(
apiKey: "YOUR-APP-IDENTIFIER-API-KEY",
endpoint: "YOUR-BRAZE-ENDPOINT"
)
let braze = Braze(configuration: configuration)
AppDelegate.braze = braze
Update YOUR-APP-IDENTIFIER-API-KEY
and YOUR-BRAZE-ENDPOINT
with the correct value from your App Settings page. Check out our API identifier types for more information on where to find your app identifier API key.
Add the following line of code to your AppDelegate.m
file:
1
@import BrazeKit;
Next, add a static variable to your AppDelegate.m
file to keep a reference to the Braze instance throughout your application’s lifetime:
1
2
3
4
5
6
7
8
9
10
11
static Braze *_braze;
@implementation AppDelegate
+ (Braze *)braze {
return _braze;
}
+ (void)setBraze:(Braze *)braze {
_braze = braze;
}
@end
Finally, within your AppDelegate.m
file, add the following snippet within your application:didFinishLaunchingWithOptions:
method:
1
2
3
4
BRZConfiguration *configuration = [[BRZConfiguration alloc] initWithApiKey:"YOUR-APP-IDENTIFIER-API-KEY"
endpoint:"YOUR-BRAZE-ENDPOINT"];
Braze *braze = [[Braze alloc] initWithConfiguration:configuration];
AppDelegate.braze = braze;
Update YOUR-APP-IDENTIFIER-API-KEY
and YOUR-BRAZE-ENDPOINT
with the correct value from your Manage Settings page. Check out our API documentation for more information on where to find your app identifier API key.
Optional configurations
Logging
Log levels
The default log level for the Braze Swift SDK is .error
—it’s also the minimum supported level when logs are enabled. These are the full list of log levels:
Swift | Objective-C | Description |
---|---|---|
.debug |
BRZLoggerLevelDebug |
(Default) Log debugging information + .info + .error . |
.info |
BRZLoggerLevelInfo |
Log general SDK information (user changes, etc.) + .error . |
.error |
BRZLoggerLevelError |
Log errors. |
.disabled |
BRZLoggerLevelDisabled |
No logging occurs. |
Setting the log level
You can assign the log level at runtime in your Braze.Configuration
object. For complete usage details, see Braze.Configuration.Logger
.
1
2
3
4
5
6
7
let configuration = Braze.Configuration(
apiKey: "<BRAZE_API_KEY>",
endpoint: "<BRAZE_ENDPOINT>"
)
// Enable logging of general SDK information (such as user changes, etc.)
configuration.logger.level = .info
let braze = Braze(configuration: configuration)
1
2
3
4
5
BRZConfiguration *configuration = [[BRZConfiguration alloc] initWithApiKey:self.APIKey
endpoint:self.apiEndpoint];
// Enable logging of general SDK information (such as user changes, etc.)
[configuration.logger setLevel:BRZLoggerLevelInfo];
Braze *braze = [[Braze alloc] initWithConfiguration:configuration];
À propos du SDK de Braze
Le SDK Web Braze vous permet de collecter des analyses/analytiques et d’afficher des messages in-app riches, des messages push et des cartes de contenu à vos utilisateurs web. Pour plus d’informations, consultez la documentation de référence JavaScript de .
This guide uses code samples from the Braze Web SDK 4.0.0+. To upgrade to the latest Web SDK version, see SDK Upgrade Guide.
Intégration du SDK Web
Vous ne savez pas si la méthode d’intégration standard vous convient ? Consultez nos autres méthodes d’intégration avant de poursuivre.
Étape 1 : Installer la bibliothèque Braze
Vous pouvez installer la bibliothèque Braze en utilisant l’une des méthodes suivantes. Si votre site web utilise un Content-Security-Policy
, consultez notre guide sur les en-têtes de la politique de sécurité du contenu avant d’installer la bibliothèque.
La plupart des bloqueurs de publicités ne bloqueront pas le SDK Web de Braze, mais certains bloqueurs de publicités plus restrictifs sont connus pour causer des problèmes.
Si votre site utilise les gestionnaires de paquets NPM ou Yarn, vous pouvez ajouter le paquet NPM de Braze comme dépendance.
Les définitions TypeScript sont désormais comprises dans la version v3.0.0. Pour obtenir les notes sur la mise à jour de 2.x vers 3.x, consultez notre journal des modifications.
1
2
3
npm install --save @braze/web-sdk
# or, using yarn:
# yarn add @braze/web-sdk
Une fois installé, vous pouvez import
ou require
la bibliothèque de la manière habituelle :
1
2
3
import * as braze from "@braze/web-sdk";
// or, using `require`
const braze = require("@braze/web-sdk");
Le SDK Web de Braze peut être installé à partir de la bibliothèque de modèles de Google Tag Manager. Deux balises sont prises en charge :
- Balise d’initialisation : charge le SDK pour le Web sur votre site Internet et définit facultativement l’ID d’utilisateur externe.
- Balise Actions : utilisée pour déclencher des événements personnalisés, des achats, modifier des ID utilisateur ou basculer le suivi du SDK.
Consultez le guide d’intégration de Google Tag Manager pour plus d’informations.
Ajoutez le SDK Braze pour le Web directement à votre code HTML en faisant référence à notre script hébergé par le CDN (réseau de diffusion de contenu), qui charge la bibliothèque asynchrone.
Étape 2 : Initialiser le SDK (facultatif)
Si vous avez configuré vos options d’initialisation Braze dans un gestionnaire de balises, vous pouvez ignorer cette étape.
Sinon, une fois le SDK Web de Braze ajouté à votre site Web, initialisez la bibliothèque avec la clé API et l’URL de l’endpoint du SDK que vous trouverez dans Paramètres > Paramètres de l’application dans votre tableau de bord de Braze. Pour obtenir une liste complète des options de braze.initialize()
, ainsi que de nos autres méthodes JavaScript, consultez la documentation JavaScript de Braze.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// initialize the SDK
braze.initialize('YOUR-API-KEY-HERE', {
baseUrl: "YOUR-SDK-ENDPOINT-HERE"
});
// optionally show all in-app messages without custom handling
braze.automaticallyShowInAppMessages();
// if you use Content Cards
braze.subscribeToContentCardsUpdates(function(cards){
// cards have been updated
});
// optionally set the current user's external ID before starting a new session
// you can also call `changeUser` later in the session after the user logs in
if (isLoggedIn){
braze.changeUser(userIdentifier);
}
// `openSession` should be called last - after `changeUser` and `automaticallyShowInAppMessages`
braze.openSession();
Les utilisateurs anonymes sur des appareils mobiles ou web peuvent être comptabilisés dans votre MAU. Par conséquent, vous pouvez charger ou initialiser conditionnellement le SDK pour exclure ces utilisateurs de votre décompte de MAU.
Configurations optionnelles
Journalisation
Pour activer rapidement la journalisation, vous pouvez ajouter ?brazeLogging=true
comme paramètre à l’URL de votre site web. Vous pouvez également activer la journalisation de base ou personnalisée.
Journalisation de base
Utilisez enableLogging
pour enregistrer des messages de débogage de base dans la console JavaScript avant l’initialisation du SDK.
1
enableLogging: true
Votre méthode doit être similaire à la suivante :
1
2
3
4
5
braze.initialize('API-KEY', {
baseUrl: 'API-ENDPOINT',
enableLogging: true
});
braze.openSession();
Utilisez braze.toggleLogging()
pour enregistrer des messages de débogage de base dans la console JavaScript après l’initialisation du SDK. Votre méthode doit être similaire à la suivante :
1
2
3
4
5
6
braze.initialize('API-KEY', {
baseUrl: 'API-ENDPOINT',
});
braze.openSession();
...
braze.toggleLogging();
Les journaux de base sont visibles par tous les utilisateurs, il faut donc envisager de les désactiver ou de passer à setLogger
avant de mettre votre code en production.
Journalisation personnalisée
Utilisez setLogger
pour enregistrer des messages de débogage personnalisés dans la console JavaScript. Contrairement aux journaux de base, ces journaux ne sont pas visibles par les utilisateurs.
1
setLogger(loggerFunction: (message: STRING) => void): void
Remplacez STRING
par votre message sous la forme d’une chaîne de caractères unique. Votre méthode doit être similaire à la suivante :
1
2
3
4
5
braze.initialize('API-KEY');
braze.setLogger(function(message) {
console.log("Braze Custom Logger: " + message);
});
braze.openSession();
Mise à niveau du SDK
This guide uses code samples from the Braze Web SDK 4.0.0+. To upgrade to the latest Web SDK version, see SDK Upgrade Guide.
Lorsque vous consultez le SDK Braze pour le Web de notre réseau de diffusion de contenu, par exemple, https://js.appboycdn.com/web-sdk/a.a/braze.min.js
(tel que recommandé par nos instructions d’intégration par défaut), vos utilisateurs recevront des mises à jour mineures (correctifs de bogues et fonctions rétrocompatibles, versions) a.a.a
par a.a.z
dans les exemples ci-dessus) automatiquement lorsqu’ils actualisent votre site.
Cependant, lorsque nous publions des changements majeurs, nous vous demandons de mettre à niveau manuellement le SDK Braze pour le Web afin de vous assurer que rien dans votre intégration ne sera affecté par des pannes. De plus, si vous téléchargez notre SDK et l’hébergez vous-même, vous ne recevrez aucune mise à jour automatique et vous devrez le mettre à niveau manuellement pour obtenir les dernières fonctionnalités et corrections de bogues.
Vous pouvez vous tenir au courant de notre dernière version en suivant notre flux de publication avec le lecteur RSS ou le service de votre choix, et consulter notre journal des modifications pour un compte-rendu complet de l’historique des versions de notre SDK Web. Pour mettre à niveau le SDK Braze pour le Web :
- Mettez à jour la version de la bibliothèque Braze en modifiant le numéro de version de
https://js.appboycdn.com/web-sdk/[OLD VERSION NUMBER]/braze.min.js
ou dans les dépendances de votre responsable de packages. - Si vous avez intégré des notifications push pour le Web, mettez à jour le fichier du service de traitement sur votre site. Par défaut, ce paramètre est situé à
/service-worker.js
dans le répertoire racine de votre site, mais l’emplacement peut être personnalisé dans certaines intégrations. Vous devez accéder au répertoire racine pour héberger un fichier de service de traitement.
Ces deux fichiers doivent être mis à jour en coordination l’un avec l’autre pour fonctionner correctement.
Google Tag Manager
Google Tag Manager (GTM) vous permet d’ajouter, de supprimer et de modifier à distance des tags sur votre site web, sans nécessiter de code de production ni de ressources techniques. Braze propose les modèles GTM suivants :
Type d’étiquette | Cas d’utilisation |
---|---|
Étiquette d’initialisation : | L’étiquette d’initialisation peut être utilisée pour initialiser le SDK de Braze Web. |
Étiquette d’action : | L’étiquette d’action peut être utilisée pour gérer les cartes de contenu et enregistrer les analyses/analytiques. |
Ces deux tags peuvent être ajoutés à votre espace de travail à partir de la galerie communautaire de Google ou en recherchant Braze lors de l’ajout d’une nouvelle étiquette à partir des modèles communautaires.
Mise à jour des règles de consentement des utilisateurs de Google dans l’UE
Google met à jour ses règles de consentement des utilisateurs de l’Union européenne en réponse aux changements apportés à la loi sur les marchés numériques (DMA), en vigueur à partir du 6 mars 2024. Ce nouveau changement oblige les annonceurs à divulguer certaines informations à leurs utilisateurs finaux de l’EEE et du Royaume-Uni, et à obtenir d’eux les consentements nécessaires. Consultez la documentation suivante pour en savoir plus.
Dans le cadre de la politique de consentement de l’utilisateur de l’UE de Google, les attributs personnalisés booléens suivants doivent être enregistrés dans les profils utilisateurs :
$google_ad_user_data
$google_ad_personalization
Si vous les définissez via l’intégration GTM, les attributs personnalisés nécessitent la création d’une balise HTML personnalisée. L’exemple suivant montre comment enregistrer ces valeurs en tant que types de données booléennes (et non en tant que chaînes de caractères) :
1
2
3
<script>
window.braze.getUser().setCustomUserAttribute("$google_ad_personalization", true);
</script>
Pour plus d’informations, reportez-vous à la section Synchronisation de l’audience avec Google.
Autres méthodes d’intégration
Pages mobiles accélérées (AMP)
Voir plus d’informations
Étape 1 : Inclure le script de notification push pour le Web en AMP
Ajoutez la balise de script asynchrone suivante à votre en-tête :
1
<script async custom-element="amp-web-push" src="https://cdn.ampproject.org/v0/amp-web-push-0.1.js"></script>
Étape 2 : Ajouter des widgets d’abonnement
Ajoutez un widget dans le corps de votre HTML qui permet aux utilisateurs de s’abonner et de se désabonner de push.
1
2
3
4
5
6
7
8
9
<!-- A subscription widget -->
<amp-web-push-widget visibility="unsubscribed" layout="fixed" width="250" height="80">
<button on="tap:amp-web-push.subscribe">Subscribe to Notifications</button>
</amp-web-push-widget>
<!-- An unsubscription widget -->
<amp-web-push-widget visibility="subscribed" layout="fixed" width="250" height="80">
<button on="tap:amp-web-push.unsubscribe">Unsubscribe from Notifications</button>
</amp-web-push-widget>
Étape 3 : Ajoutez helper-iframe
et permission-dialog
Le composant AMP Web Push crée une fenêtre contextuelle pour gérer les abonnements push. Vous devrez donc ajouter les fichiers d’aide suivants à votre projet pour activer cette fonctionnalité :
Étape 4 : Créer un fichier de service de traitement
Créez un fichier service-worker.js
dans le répertoire racine de votre site web et ajoutez l’extrait de code suivant :
Étape 5 : Configurer l’élément HTML des notifications push pour le Web en AMP
Ajoutez l’élément HTML amp-web-push
suivant au corps de votre HTML. Gardez à l’esprit que vous devez ajouter vos apiKey
et baseUrl
en tant que paramètres de requête à service-worker-URL
.
1
2
3
4
5
6
7
<amp-web-push
layout="nodisplay"
id="amp-web-push"
helper-iframe-url="FILE_PATH_TO_YOUR_HELPER_IFRAME"
permission-dialog-url="FILE_PATH_TO_YOUR_PERMISSION_DIALOG"
service-worker-url="FILE_PATH_TO_YOUR_SERVICE_WORKER?apiKey={YOUR_API_KEY}&baseUrl={YOUR_BASE_URL}"
>
AMD : Désactiver le soutien
Si votre site utilise RequireJS ou un autre chargeur de modules AMD, mais que vous préférez charger le SDK Braze via l’une des autres options de cette liste, vous pouvez charger une version de la bibliothèque qui n’inclut pas la prise en charge AMD. Il est possible de charger cette version de la bibliothèque depuis l’endroit suivant du CDN :
AMD : Chargeur de modules
Si vous utilisez RequireJS ou d’autres chargeurs de module AMD, nous vous recommandons d’auto-héberger une copie de notre bibliothèque et de la référencer comme vous le feriez avec d’autres ressources :
1
2
3
4
5
require(['path/to/braze.min.js'], function(braze) {
braze.initialize('YOUR-API-KEY-HERE', { baseUrl: 'YOUR-SDK-ENDPOINT' });
braze.automaticallyShowInAppMessages();
braze.openSession();
});
Electron
Electron ne prend pas officiellement en charge les notifications push Web (voir ce problème GitHub). Il existe d’autres solutions de contournement open source que vous pouvez essayer mais qui n’ont pas été testées par Braze.
Cadre Jest
Lorsque vous utilisez Jest, vous pouvez visualiser une erreur similaire à SyntaxError: Unexpected token 'export'
. Pour la réparer, ajustez votre configuration dans package.json
pour ignorer le Braze SDK :
1
2
3
4
5
"jest": {
"transformIgnorePatterns": [
"/node_modules/(?!@braze)"
]
}
Cadres de la RSS
Si vous utilisez un cadre de rendu côté serveur (SSR) tel que Next.js, vous risquez de rencontrer des erreurs car le SDK est conçu pour être exécuté dans un environnement de navigateur. Vous pouvez résoudre ces problèmes en important le SDK de façon dynamique.
Vous pouvez conserver les bénéfices du nettoyage lorsque vous y procédez en exportant les parties du SDK dont vous avez besoin dans un fichier séparé et en important ensuite de façon dynamique ce fichier dans votre composant.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// MyComponent/braze-exports.js
// export the parts of the SDK you need here
export { initialize, openSession } from "@braze/web-sdk";
// MyComponent/MyComponent.js
// import the functions you need from the braze exports file
useEffect(() => {
import("./braze-exports.js").then(({ initialize, openSession }) => {
initialize("YOUR-API-KEY-HERE", {
baseUrl: "YOUR-SDK-ENDPOINT",
enableLogging: true,
});
openSession();
});
}, []);
Alternativement, si vous utilisez un pack Web pour regrouper votre application, vous pouvez tirer parti de ses commentaires magiques pour importer de façon dynamique uniquement les parties du SDK dont vous avez besoin.
1
2
3
4
5
6
7
8
9
10
11
12
13
// MyComponent.js
useEffect(() => {
import(
/* webpackExports: ["initialize", "openSession"] */
"@braze/web-sdk"
).then(({ initialize, openSession }) => {
initialize("YOUR-API-KEY-HERE", {
baseUrl: "YOUR-SDK-ENDPOINT",
enableLogging: true,
});
openSession();
});
}, []);
Tealium iQ
Tealium iQ propose une intégration de base de Braze. Pour configurer l’intégration, recherchez Braze dans l’interface Tealium Tag Management et fournissez la clé API du SDK pour le Web à partir de votre tableau de bord.
Pour plus de détails ou une assistance approfondie sur la configuration de Tealium, consultez notre documentation sur l’intégration ou contactez votre gestionnaire de compte Tealium.
Vite
Si vous utilisez Vite et voyez un avertissement autour des dépendances circulaires ou Uncaught TypeError: Class extends value undefined is not a constructor or null
, vous pourriez devoir exclure le SDK de Braze de sa découverte de dépendance :
1
2
3
optimizeDeps: {
exclude: ['@braze/web-sdk']
},
Autres gestionnaires de balises
Braze peut également être compatible avec d’autres solutions de gestion des balises en suivant nos instructions d’intégration au sein d’une balise HTML personnalisée. Contactez un conseiller Braze si vous avez besoin d’aide pour évaluer ces solutions.
Integrating the Cordova SDK
Prerequisites
Before you start, verify your environment is supported by the latest Braze Cordova SDK version.
Step 1: Add the SDK to your project
Only add the Braze Cordova SDK using the methods below. Do not attempt to install using other methods as it could lead to a security breach.
If you’re on Cordova 6 or later, you can add the SDK directly from GitHub. Alternatively, you can download a ZIP of the GitHub repository and add the SDK manually.
If you don’t plan on using location collection and geofences, use the master
branch from GitHub.
1
cordova plugin add https://github.com/braze-inc/braze-cordova-sdk#master
If you plan on using location collection and geofences, use the geofence-branch
from GitHub.
1
cordova plugin add https://github.com/braze-inc/braze-cordova-sdk#geofence-branch
You can switch between master
and geofence-branch
at anytime by repeating this step.
Step 2: Configure your project
Next, adding the following preferences to the platform
element in your project’s config.xml
file.
1
2
<preference name="com.braze.ios_api_key" value="BRAZE_API_KEY" />
<preference name="com.braze.ios_api_endpoint" value="CUSTOM_API_ENDPOINT" />
1
2
<preference name="com.braze.android_api_key" value="BRAZE_API_KEY" />
<preference name="com.braze.android_api_endpoint" value="CUSTOM_API_ENDPOINT" />
Replace the following:
Value | Description |
---|---|
BRAZE_API_KEY |
Your Braze REST API key. |
CUSTOM_API_ENDPOINT |
A custom API endpoint. This endpoint is used to route your Braze instance data to the correct App Group in your Braze dashboard. |
The platform
element in your config.xml
file should be similar to the following:
1
2
3
4
<platform name="ios">
<preference name="com.braze.ios_api_key" value="BRAZE_API_KEY" />
<preference name="com.braze.ios_api_endpoint" value="sdk.fra-01.braze.eu" />
</platform>
1
2
3
4
<platform name="android">
<preference name="com.braze.android_api_key" value="BRAZE_API_KEY" />
<preference name="com.braze.android_api_endpoint" value="sdk.fra-01.braze.eu" />
</platform>
Platform-specific syntax
The following section covers the platform-specific syntax when using Cordova with iOS or Android.
Integers
Integer preferences are read as string representations, like in the following example:
1
2
3
4
<platform name="ios">
<preference name="com.braze.ios_flush_interval_seconds" value="10" />
<preference name="com.braze.ios_session_timeout" value="5" />
</platform>
Due to how the Cordova 8.0.0+ framework handles preferences, integer-only preferences (such as sender IDs) must be set to strings prepended with str_
, like in the following example:
1
2
3
4
<platform name="android">
<preference name="com.braze.android_fcm_sender_id" value="str_64422926741" />
<preference name="com.braze.android_default_session_timeout" value="str_10" />
</platform>
Booleans
Boolean preferences are read by the SDK using YES
and NO
keywords as a string representation, like in the following example:
1
2
3
4
<platform name="ios">
<preference name="com.braze.should_opt_in_when_push_authorized" value="YES" />
<preference name="com.braze.ios_disable_automatic_push_handling" value="NO" />
</platform>
Boolean preferences are read by the SDK using true
and false
keywords as a string representation, like in the following example:
1
2
3
4
<platform name="android">
<preference name="com.braze.should_opt_in_when_push_authorized" value="true" />
<preference name="com.braze.is_session_start_based_timeout_enabled" value="false" />
</platform>
Optional configurations
You can add any of the following preferences to the platform
element in your project’s config.xml
file:
Method | Description |
---|---|
ios_api_key |
Sets the API key for your application. |
ios_api_endpoint |
Sets the SDK endpoint for your application. |
ios_disable_automatic_push_registration |
Sets whether automatic push registration should be disabled. |
ios_disable_automatic_push_handling |
Sets whether automatic push handling should be disabled. |
ios_enable_idfa_automatic_collection |
Sets whether the Braze SDK should automatically collect the IDFA information. For more information, see the Braze IDFA method documentation. |
enable_location_collection |
Sets whether the automatic location collection is enabled (if the user permits). The geofence-branch |
geofences_enabled |
Sets whether geofences are enabled. |
ios_session_timeout |
Sets the Braze session timeout for your application in seconds. Defaults to 10 seconds. |
sdk_authentication_enabled |
Sets whether to enable the SDK Authentication feature. |
display_foreground_push_notifications |
Sets whether push notifications should be displayed while the application is in the foreground. |
ios_disable_un_authorization_option_provisional |
Sets whether UNAuthorizationOptionProvisional should be disabled. |
trigger_action_minimum_time_interval_seconds |
Sets the minimum time interval in seconds between triggers. Defaults to 30 seconds. |
ios_push_app_group |
Sets the app group ID for iOS push extensions. |
ios_forward_universal_links |
Sets if the SDK should automatically recognize and forward universal links to the system methods. |
ios_log_level |
Sets the minimum logging level for Braze.Configuration.Logger . |
ios_use_uuid_as_device_id |
Sets if a randomly generated UUID should be used as the device ID. |
ios_flush_interval_seconds |
Sets the interval in seconds between automatic data flushes. Defaults to 10 seconds. |
ios_use_automatic_request_policy |
Sets whether the request policy for Braze.Configuration.Api should be automatic or manual. |
should_opt_in_when_push_authorized |
Sets if a user’s notification subscription state should automatically be set to optedIn when push permissions are authorized. |
For more detailed information, see GitHub: Braze iOS Cordova plugin.
Method | Description |
---|---|
android_api_key |
Sets the API key for your application. |
android_api_endpoint |
Sets the SDK endpoint for your application. |
android_small_notification_icon |
Sets the notification small icon. |
android_large_notification_icon |
Sets the notification large icon. |
android_notification_accent_color |
Sets the notification accent color using a hexadecimal representation. |
android_default_session_timeout |
Sets the Braze session timeout for your application in seconds. Defaults to 10 seconds. |
android_handle_push_deep_links_automatically |
Sets whether the Braze SDK should automatically handle push deep links. |
android_log_level |
Sets the log level for your application. The default log level is 4 and will minimally log info. To enable verbose logging for debugging, use log level 2. |
firebase_cloud_messaging_registration_enabled |
Sets whether to use Firebase Cloud Messaging for push notifications. |
android_fcm_sender_id |
Sets the Firebase Cloud Messaging sender ID. |
enable_location_collection |
Sets whether the automatic location collection is enabled (if the user permits). |
geofences_enabled |
Sets whether geofences are enabled. |
android_disable_auto_session_tracking |
Disable the Android Cordova plugin from automatically tracking sessions. For more information, see Disabling automatic session tracking |
sdk_authentication_enabled |
Sets whether to enable the SDK Authentication feature. |
trigger_action_minimum_time_interval_seconds |
Sets the minimum time interval in seconds between triggers. Defaults to 30 seconds. |
is_session_start_based_timeout_enabled |
Sets whether the session timeout behavior to be based either on session start or session end events. |
default_notification_channel_name |
Sets the user-facing name as seen via NotificationChannel.getName for the Braze default NotificationChannel . |
default_notification_channel_description |
Sets the user-facing description as seen via NotificationChannel.getDescription for the Braze default NotificationChannel . |
does_push_story_dismiss_on_click |
Sets whether a Push Story is automatically dismissed when clicked. |
is_fallback_firebase_messaging_service_enabled |
Sets whether the use of a fallback Firebase Cloud Messaging Service is enabled. |
fallback_firebase_messaging_service_classpath |
Sets the classpath for the fallback Firebase Cloud Messaging Service. |
is_content_cards_unread_visual_indicator_enabled |
Sets whether the Content Cards unread visual indication bar is enabled. |
is_firebase_messaging_service_on_new_token_registration_enabled |
Sets whether the Braze SDK will automatically register tokens in com.google.firebase.messaging.FirebaseMessagingService.onNewToken . |
is_push_deep_link_back_stack_activity_enabled |
Sets whether Braze will add an activity to the back stack when automatically following deep links for push. |
push_deep_link_back_stack_activity_class_name |
Sets the activity that Braze will add to the back stack when automatically following deep links for push. |
should_opt_in_when_push_authorized |
Sets if Braze should automatically opt-in the user when push is authorized. |
For more detailed information, see GitHub: Braze Android Cordova plugin.
The following is an example config.xml
file with additional configurations:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<platform name="ios">
<preference name="com.braze.ios_disable_automatic_push_registration" value="NO"/"YES" />
<preference name="com.braze.ios_disable_automatic_push_handling" value="NO"/"YES" />
<preference name="com.braze.ios_enable_idfa_automatic_collection" value="YES"/"NO" />
<preference name="com.braze.enable_location_collection" value="NO"/"YES" />
<preference name="com.braze.geofences_enabled" value="NO"/"YES" />
<preference name="com.braze.ios_session_timeout" value="5" />
<preference name="com.braze.sdk_authentication_enabled" value="YES"/"NO" />
<preference name="com.braze.display_foreground_push_notifications" value="YES"/"NO" />
<preference name="com.braze.ios_disable_un_authorization_option_provisional" value="NO"/"YES" />
<preference name="com.braze.trigger_action_minimum_time_interval_seconds" value="30" />
<preference name="com.braze.ios_push_app_group" value="PUSH_APP_GROUP_ID" />
<preference name="com.braze.ios_forward_universal_links" value="YES"/"NO" />
<preference name="com.braze.ios_log_level" value="2" />
<preference name="com.braze.ios_use_uuid_as_device_id" value="YES"/"NO" />
<preference name="com.braze.ios_flush_interval_seconds" value="10" />
<preference name="com.braze.ios_use_automatic_request_policy" value="YES"/"NO" />
<preference name="com.braze.should_opt_in_when_push_authorized" value="YES"/"NO" />
</platform>
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
<platform name="android">
<preference name="com.braze.android_small_notification_icon" value="RESOURCE_ENTRY_NAME_FOR_ICON_DRAWABLE" />
<preference name="com.braze.android_large_notification_icon" value="RESOURCE_ENTRY_NAME_FOR_ICON_DRAWABLE" />
<preference name="com.braze.android_notification_accent_color" value="str_ACCENT_COLOR_INTEGER" />
<preference name="com.braze.android_default_session_timeout" value="str_SESSION_TIMEOUT_INTEGER" />
<preference name="com.braze.android_handle_push_deep_links_automatically" value="true"/"false" />
<preference name="com.braze.android_log_level" value="str_LOG_LEVEL_INTEGER" />
<preference name="com.braze.firebase_cloud_messaging_registration_enabled" value="true"/"false" />
<preference name="com.braze.android_fcm_sender_id" value="str_YOUR_FCM_SENDER_ID" />
<preference name="com.braze.enable_location_collection" value="true"/"false" />
<preference name="com.braze.geofences_enabled" value="true"/"false" />
<preference name="com.braze.android_disable_auto_session_tracking" value="true"/"false" />
<preference name="com.braze.sdk_authentication_enabled" value="true"/"false" />
<preference name="com.braze.trigger_action_minimum_time_interval_seconds" value="str_MINIMUM_INTERVAL_INTEGER" />
<preference name="com.braze.is_session_start_based_timeout_enabled" value="false"/"true" />
<preference name="com.braze.default_notification_channel_name" value="DEFAULT_NAME" />
<preference name="com.braze.default_notification_channel_description" value="DEFAULT_DESCRIPTION" />
<preference name="com.braze.does_push_story_dismiss_on_click" value="true"/"false" />
<preference name="com.braze.is_fallback_firebase_messaging_service_enabled" value="true"/"false" />
<preference name="com.braze.fallback_firebase_messaging_service_classpath" value="FALLBACK_FIREBASE_MESSAGING_CLASSPATH" />
<preference name="com.braze.is_content_cards_unread_visual_indicator_enabled" value="true"/"false" />
<preference name="com.braze.is_firebase_messaging_service_on_new_token_registration_enabled" value="true"/"false" />
<preference name="com.braze.is_push_deep_link_back_stack_activity_enabled" value="true"/"false" />
<preference name="com.braze.push_deep_link_back_stack_activity_class_name" value="DEEPLINK_BACKSTACK_ACTIVITY_CLASS_NAME" />
<preference name="com.braze.should_opt_in_when_push_authorized" value="true"/"false" />
</platform>
Disabling automatic session tracking (Android only)
By default, the Android Cordova plugin automatically tracks sessions. To disable automatic session tracking, add the following preference to the platform
element in your project’s config.xml
file:
1
2
3
<platform name="android">
<preference name="com.braze.android_disable_auto_session_tracking" value="true" />
</platform>
To start tracking sessions again, call BrazePlugin.startSessionTracking()
. Keep in mind, only sessions started after the next Activity.onStart()
will be tracked.
À propos du SDK de Flutter Braze
Après avoir intégré le SDK Flutter de Braze sur Android et iOS, vous pourrez utiliser l’API de Braze au sein de vos applications Flutter écrites en Dart. Ce plug-in offre une fonctionnalité d’analytique de base et vous permet d’intégrer des messages in-app et des cartes de contenu pour iOS et Android à l’aide d’une base de code unique.
Intégration du SDK Flutter
Conditions préalables
Avant d’intégrer le SDK Flutter de Braze, vous devrez effectuer les opérations suivantes :
Prérequis | Description |
---|---|
Identifiant de l’application API de Braze | Pour localiser l’identifiant de votre application, allez dans Emplacements > API et identifiants > Identifiants d’application. Pour plus d’informations, voir Types d’identifiants API. |
Endpoint REST Braze | L’URL de votre endpoint REST. Votre endpoint dépendra de l’URL de Braze pour votre instance. |
SDK Flutter | Installez le SDK officiel de Flutter et assurez-vous qu’il correspond à la version minimale prise en charge par le SDK de Braze Flutter. |
Étape 1 : Intégrez la bibliothèque Braze
Ajoutez le kit SDK Braze pour Flutter à partir de la ligne de commande. Cela ajoutera la ligne appropriée à votre pubspec.yaml
.
1
flutter pub add braze_plugin
Étape 2 : Configuration complète du SDK natif
Pour vous connecter aux serveurs Braze, créez un fichier braze.xml
dans le dossier android/res/values
de votre projet. Collez le code suivant et remplacez la clé d’identification API et l’endpoint par vos valeurs :
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>
Ajoutez les autorisations requises à votre fichier AndroidManifest.xml
:
1
2
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Ajoutez l’importation SDK Braze en haut du fichier AppDelegate.swift
:
1
2
import BrazeKit
import braze_plugin
Dans le même fichier, créez l’objet de configuration Braze dans la méthode application(_:didFinishLaunchingWithOptions:)
et remplacez la clé API et le endpoint par les valeurs de votre application. Ensuite, créez l’instance Braze à l’aide de la configuration et créez une propriété statique sur AppDelegate
pour un accès facile :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
static var braze: Braze? = nil
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil
) -> Bool {
// Setup Braze
let configuration = Braze.Configuration(
apiKey: "<BRAZE_API_KEY>",
endpoint: "<BRAZE_ENDPOINT>"
)
// - Enable logging or customize configuration here
configuration.logger.level = .info
let braze = BrazePlugin.initBraze(configuration)
AppDelegate.braze = braze
return true
}
Importez BrazeKit
en haut du fichier AppDelegate.m
:
1
@import BrazeKit;
Dans le même fichier, créez l’objet de configuration Braze dans la méthode application:didFinishLaunchingWithOptions:
et remplacez la clé API et le endpoint par les valeurs de votre application. Ensuite, créez l’instance Braze à l’aide de la configuration et créez une propriété statique sur AppDelegate
pour un accès facile :
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
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Setup Braze
BRZConfiguration *configuration =
[[BRZConfiguration alloc] initWithApiKey:@"<BRAZE_API_KEY>"
endpoint:@"<BRAZE_ENDPOINT>"];
// - Enable logging or customize configuration here
configuration.logger.level = BRZLoggerLevelInfo;
Braze *braze = [BrazePlugin initBraze:configuration];
AppDelegate.braze = braze;
[self.window makeKeyAndVisible];
return YES;
}
#pragma mark - AppDelegate.braze
static Braze *_braze = nil;
+ (Braze *)braze {
return _braze;
}
+ (void)setBraze:(Braze *)braze {
_braze = braze;
}
Étape 3 : Configurer le plugin
Pour importer le plug-in dans votre code Dart, utilisez ce qui suit :
1
import 'package:braze_plugin/braze_plugin.dart';
Ensuite, initialisez une instance du plug-in Braze en appelant new BrazePlugin()
comme dans notre exemple d’application.
Pour éviter les comportements indéfinis, n’allouez et n’utilisez qu’une seule instance de BrazePlugin
dans votre code Dart.
Tester l’intégration
Vous pouvez vérifier que le SDK est intégré en consultant les statistiques de session dans le tableau de bord. Si vous exécutez votre application sur l’une ou l’autre plateforme, vous devriez voir une nouvelle session dans le tableau de bord (dans la section Aperçu ).
Ouvrez une session pour un utilisateur particulier en appelant le code suivant dans votre application.
1
2
BrazePlugin braze = BrazePlugin();
braze.changeUser("{some-user-id}");
Recherchez l’utilisateur avec {some-user-id}
dans le tableau de bord sous Audience > Recherche d’utilisateurs. Vous pouvez y vérifier que les données de session et d’appareil ont été enregistrées.
À propos du SDK React Native de Braze
L’intégration du SDK React Native Braze fournit des fonctionnalités d’analyse/analytique de base et vous permet d’intégrer des messages in-app et des cartes de contenu pour iOS et Android avec une seule base de code.
Compatibilité avec la nouvelle architecture
La version minimale suivante du SDK est compatible avec toutes les apps utilisant la nouvelle architecture de React Native:
À partir de la version 6.0.0 du SDK, Braze utilise un module React Native Turbo, qui est compatible à la fois avec la nouvelle architecture et l’ancienne architecture de pont - ce qui signifie qu’aucune configuration supplémentaire n’est nécessaire.
Si votre app iOS est conforme à RCTAppDelegate
et suit notre précédente configuration AppDelegate
, passez en revue les exemples dans Complete native setup pour éviter tout plantage lors de l’abonnement à des événements dans le module Turbo.
Intégration du SDK React Native
Conditions préalables
Pour intégrer le SDK, la version 0.71 ou ultérieure de React Native est nécessaire. Pour obtenir la liste complète des versions prises en charge, consultez notre référentiel GitHub du SDK React Native.
Étape 1 : Intégrez la bibliothèque Braze
1
npm install @braze/react-native-sdk
1
yarn add @braze/react-native-sdk
Étape 2 : Choisissez une option de configuration
Vous pouvez gérer le SDK de Braze à l’aide du plugin Braze Expo ou via l’une des couches natives. Avec le plugin Expo, vous pouvez configurer certaines fonctionnalités du SDK sans écrire de code dans les couches natives. Choisissez l’option qui répond le mieux aux besoins de votre application.
Étape 2.1 : Installer le plugin Braze Expo
Assurez-vous que votre version du SDK React Native de Braze correspond au minimum à 1.37.0. Pour obtenir la liste complète des versions prises en charge, consultez le référentiel React Native de Braze.
Pour installer le plugin Braze Expo, exécutez la commande suivante :
1
expo install @braze/expo-plugin
Étape 2.2 : Ajoutez le plug-in à votre app.json
Dans votre app.json
, ajoutez le Plugin Braze Expo. Vous pouvez fournir les options de configuration suivantes :
Méthode | Type | Description |
---|---|---|
androidApiKey |
chaîne de caractères | Obligatoire. La clé API de votre application Android, située dans votre tableau de bord de Braze sous Gérer les paramètres. |
iosApiKey |
chaîne de caractères | Obligatoire. La clé API de votre application iOS, située dans votre tableau de bord de Braze sous Gérer les paramètres. |
baseUrl |
chaîne de caractères | Obligatoire. Le endpoint SDK de votre application, situé dans votre tableau de bord de Braze sous Gérer les paramètres. |
enableBrazeIosPush |
booléen | iOS uniquement. Si vous devez utiliser Braze pour gérer les notifications push sur iOS. Introduites dans le SDK React Native v1.38.0 et Expo Plugin v0.4.0. |
enableFirebaseCloudMessaging |
booléen | Android uniquement. Si vous devez utiliser Firebase Cloud Messaging pour les notifications push. Introduites dans le SDK React Native v1.38.0 et Expo Plugin v0.4.0. |
firebaseCloudMessagingSenderId |
chaîne de caractères | Android uniquement. Votre ID expéditeur Firebase Cloud Messaging. Introduites dans le SDK React Native v1.38.0 et Expo Plugin v0.4.0. |
sessionTimeout |
Entier | Le délai de session Braze pour votre application en secondes. |
enableSdkAuthentication |
booléen | Détermine si la fonctionnalité Authentification SDK est activée. |
logLevel |
Entier | Le niveau de journal pour votre application. Le niveau de journal par défaut est de 8 et va journaliser le minimum d’informations. Pour activer la journalisation verbeuse pour le débogage, utilisez le niveau 0 du journal. |
minimumTriggerIntervalInSeconds |
Entier | Intervalle minimum en secondes entre les déclenchements. 30 secondes par défaut. |
enableAutomaticLocationCollection |
booléen | Collecte des données de localisation automatique activée ou non (si l’utilisateur l’autorise). |
enableGeofence |
booléen | Activation ou non des géorepérages. |
enableAutomaticGeofenceRequests |
booléen | Demandes de géorepérage automatique ou non. |
dismissModalOnOutsideTap |
booléen | iOS uniquement. Le message in-app modal sera rejeté ou non lorsque l’utilisateur clique à l’extérieur du message in-app. |
androidHandlePushDeepLinksAutomatically |
booléen | Android uniquement. Si le SDK Braze doit gérer automatiquement les liens profonds de notification push. |
androidPushNotificationHtmlRenderingEnabled |
booléen | Android uniquement. Définit si le contenu textuel d’une notification push doit être interprété et rendu en tant que HTML en utilisant android.text.Html.fromHtml . |
androidNotificationAccentColor |
chaîne de caractères | Android uniquement. Définit la couleur d’accentuation de la notification Android. |
androidNotificationLargeIcon |
chaîne de caractères | Android uniquement. Définit l’icône large de la notification Android. |
androidNotificationSmallIcon |
chaîne de caractères | Android uniquement. Définit l’icône de notification petite d’Android. |
iosRequestPushPermissionsAutomatically |
booléen | iOS uniquement. Détermine si l’utilisateur doit être automatiquement invité à autoriser les notifications push au lancement de l’application. |
enableBrazeIosRichPush |
booléen | iOS uniquement. Faut-il activer les fonctionnalités push enrichies pour iOS. |
enableBrazeIosPushStories |
booléen | iOS uniquement. Activer ou non les histoires push Braze pour iOS. |
iosPushStoryAppGroup |
chaîne de caractères | iOS uniquement. Le groupe d’applications utilisé pour les histoires Push iOS. |
Exemple de configuration :
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
{
"expo": {
"plugins": [
[
"@braze/expo-plugin",
{
"androidApiKey": "YOUR-ANDROID-API-KEY",
"iosApiKey": "YOUR-IOS-API-KEY",
"baseUrl": "YOUR-SDK-ENDPOINT",
"sessionTimeout": 60,
"enableGeofence": false,
"enableBrazeIosPush": false,
"enableFirebaseCloudMessaging": false,
"firebaseCloudMessagingSenderId": "YOUR-FCM-SENDER-ID",
"androidHandlePushDeepLinksAutomatically": true,
"enableSdkAuthentication": false,
"logLevel": 0,
"minimumTriggerIntervalInSeconds": 0,
"enableAutomaticLocationCollection": false,
"enableAutomaticGeofenceRequests": false,
"dismissModalOnOutsideTap": true,
"androidPushNotificationHtmlRenderingEnabled": true,
"androidNotificationAccentColor": "#ff3344",
"androidNotificationLargeIcon": "@drawable/custom_app_large_icon",
"androidNotificationSmallIcon": "@drawable/custom_app_small_icon",
"iosRequestPushPermissionsAutomatically": false,
"enableBrazeIosPushStories": true,
"iosPushStoryAppGroup": "group.com.example.myapp.PushStories"
}
],
]
}
}
Étape 2.3 : Créer et exécuter votre application
La préconstruction de votre application générera les fichiers natifs nécessaires au fonctionnement du plugin Braze Expo.
1
expo prebuild
Exécutez votre application tel qu’indiqué dans la documentation Expo. Gardez à l’esprit que si vous modifiez les options de configuration, vous devrez préconstruire et exécuter à nouveau l’application.
Étape 2.1 : Ajouter notre référentiel
Dans votre projet de niveau supérieur build.gradle
, ajoutez ce qui suit sous buildscript
> dependencies
:
1
2
3
4
5
6
7
buildscript {
dependencies {
...
// Choose your Kotlin version
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:1.8.10")
}
}
Cela ajoutera Kotlin à votre projet.
Étape 2.2 : Configurer le SDK Braze
Pour vous connecter aux serveurs Braze, créez un fichier braze.xml
dans le dossier res/values
de votre projet. Collez le code suivant et remplacez la clé API et le point de terminaison par vos valeurs :
1
2
3
4
5
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="com_braze_api_key">YOU_APP_IDENTIFIER_API_KEY</string>
<string translatable="false" name="com_braze_custom_endpoint">YOUR_CUSTOM_ENDPOINT_OR_CLUSTER</string>
</resources>
Ajoutez les autorisations requises à votre fichier AndroidManifest.xml
:
1
2
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Avec la version 12.2.0 du SDK de Braze ou une version ultérieure, vous pouvez intégrer automatiquement la bibliothèque android-sdk-location en définissant importBrazeLocationLibrary=true
dans votre fichier gradle.properties
.
Étape 2.3 : Implémentez le suivi de session utilisateur
Les appels vers openSession()
et closeSession()
sont gérées automatiquement.
Ajoutez le code suivant à la méthode onCreate()
de votre classe MainApplication
:
1
2
3
4
5
6
7
8
import com.braze.BrazeActivityLifecycleCallbackListener;
@Override
public void onCreate() {
super.onCreate();
...
registerActivityLifecycleCallbacks(new BrazeActivityLifecycleCallbackListener());
}
1
2
3
4
5
6
7
import com.braze.BrazeActivityLifecycleCallbackListener
override fun onCreate() {
super.onCreate()
...
registerActivityLifecycleCallbacks(BrazeActivityLifecycleCallbackListener())
}
Étape 2.4 : Gérer les mises à jour d’intention
Si votre activité principale a android:launchMode
défini sur singleTask
, ajoutez le code suivant à votre classe MainActivity
:
1
2
3
4
5
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
1
2
3
4
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
}
Étape 2.1 : (Facultatif) Configurer le Podfile pour les XCFrameworks dynamiques
Pour importer certaines bibliothèques Braze, telles que BrazeUI, dans un fichier Objective-C++, vous devrez utiliser la syntaxe #import
. À partir de la version 7.4.0 du SDK Braze Swift, les binaires ont un canal de distribution facultatif sous forme de XCFrameworks dynamiques qui sont compatibles avec cette syntaxe.
Si vous souhaitez utiliser ce canal de distribution, remplacez manuellement les emplacements des sources CocoaPods dans votre Podfile. Référez-vous à l’exemple ci-dessous et remplacez {your-version}
par la version pertinente que vous souhaitez importer :
1
2
3
pod 'BrazeKit', :podspec => 'https://raw.githubusercontent.com/braze-inc/braze-swift-sdk-prebuilt-dynamic/{your-version}/BrazeKit.podspec'
pod 'BrazeUI', :podspec => 'https://raw.githubusercontent.com/braze-inc/braze-swift-sdk-prebuilt-dynamic/{your-version}/BrazeUI.podspec'
pod 'BrazeLocation', :podspec => 'https://raw.githubusercontent.com/braze-inc/braze-swift-sdk-prebuilt-dynamic/{your-version}/BrazeLocation.podspec'
Étape 2.2 : Installer les pods
Comme React Native lie automatiquement les bibliothèques à la plateforme native, vous pouvez installer le SDK avec l’aide de CocoaPods.
Dans le dossier racine du projet :
1
2
3
4
5
# To install using the React Native New Architecture
cd ios && RCT_NEW_ARCH_ENABLED=1 pod install
# To install using the React Native legacy architecture
cd ios && pod install
Étape 2.3 : Configurer le SDK Braze
Ajoutez le SDK Braze en haut du fichier AppDelegate.swift
:
1
import BrazeKit
Dans la méthode application(_:didFinishLaunchingWithOptions:)
, remplacez la clé API et le point de terminaison par les valeurs de votre application. Ensuite, créez l’instance Braze à l’aide de la configuration et créez une propriété statique sur AppDelegate
pour un accès facile :
Notre exemple suppose une implémentation de RCTAppDelegate, qui fournit un certain nombre d’abstractions dans la configuration de React Native. Si vous utilisez une configuration différente pour votre application, assurez-vous d’ajuster votre implémentation en conséquence.
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
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil
) -> Bool {
// Setup Braze
let configuration = Braze.Configuration(
apiKey: "{BRAZE_API_KEY}",
endpoint: "{BRAZE_ENDPOINT}")
// Enable logging and customize the configuration here.
configuration.logger.level = .info
let braze = BrazeReactBridge.perform(
#selector(BrazeReactBridge.initBraze(_:)),
with: configuration
).takeUnretainedValue() as! Braze
AppDelegate.braze = braze
/* Other configuration */
return true
}
// MARK: - AppDelegate.braze
static var braze: Braze? = nil
Ajoutez le SDK Braze en haut du fichier AppDelegate.m
:
1
2
#import <BrazeKit/BrazeKit-Swift.h>
#import "BrazeReactBridge.h"
Dans la méthode application:didFinishLaunchingWithOptions:
, remplacez la clé API et le point de terminaison par les valeurs de votre application. Ensuite, créez l’instance Braze à l’aide de la configuration et créez une propriété statique sur AppDelegate
pour un accès facile :
Notre exemple suppose une implémentation de RCTAppDelegate, qui fournit un certain nombre d’abstractions dans la configuration de React Native. Si vous utilisez une configuration différente pour votre application, assurez-vous d’ajuster votre implémentation en conséquence.
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
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Setup Braze
BRZConfiguration *configuration = [[BRZConfiguration alloc] initWithApiKey:@"{BRAZE_API_KEY}"
endpoint:@"{BRAZE_ENDPOINT}"];
// Enable logging and customize the configuration here.
configuration.logger.level = BRZLoggerLevelInfo;
Braze *braze = [BrazeReactBridge initBraze:configuration];
AppDelegate.braze = braze;
/* Other configuration */
return YES;
}
#pragma mark - AppDelegate.braze
static Braze *_braze = nil;
+ (Braze *)braze {
return _braze;
}
+ (void)setBraze:(Braze *)braze {
_braze = braze;
}
Étape 3 : Importer la bibliothèque
Ensuite, import
la bibliothèque dans votre code React Native. Pour plus de détails, consultez notre exemple de projet.
1
import Braze from "@braze/react-native-sdk";
Étape 4 : Testez l’intégration (facultatif)
Pour tester votre intégration SDK, démarrez une nouvelle session sur l’une ou l’autre plateforme pour un utilisateur en appelant le code suivant dans votre application.
1
Braze.changeUser("userId");
Par exemple, vous pouvez attribuer l’ID utilisateur au démarrage de l’application :
1
2
3
4
5
6
7
8
9
10
11
12
13
import React, { useEffect } from "react";
import Braze from "@braze/react-native-sdk";
const App = () => {
useEffect(() => {
Braze.changeUser("some-user-id");
}, []);
return (
<div>
...
</div>
)
Dans le tableau de bord de Braze, allez dans Recherche d’utilisateurs et recherchez l’utilisateur dont l’ID correspond à some-user-id
. Ici, vous pouvez vérifier que les données relatives à la session et à l’appareil ont été enregistrées.
Intégration du SDK Roku
Étape 1 : Ajouter des fichiers
Les fichiers du SDK Braze sont disponibles dans le répertoire sdk_files
du référentiel SDK Roku de Braze.
- Ajouter
BrazeSDK.brs
à votre application dans le répertoiresource
. - Ajouter
BrazeTask.brs
etBrazeTask.xml
à votre application dans le répertoirecomponents
.
Étape 2 : Ajouter des références
Ajouter une référence à BrazeSDK.brs
dans votre scène principale, en utilisant l’élément script
:
1
<script type="text/brightscript" uri="pkg:/source/BrazeSDK.brs"/>
Étape 3 : Configurer
Dans main.brs
, définissez la configuration Braze sur le nœud global :
1
2
3
4
5
6
7
8
globalNode = screen.getGlobalNode()
config = {}
config_fields = BrazeConstants().BRAZE_CONFIG_FIELDS
config[config_fields.API_KEY] = {YOUR_API_KEY}
' example endpoint: "https://sdk.iad-01.braze.com/"
config[config_fields.ENDPOINT] = {YOUR_ENDPOINT}
config[config_fields.HEARTBEAT_FREQ_IN_SECONDS] = 5
globalNode.addFields({brazeConfig: config})
Vous trouverez votre endpoint SDK et votre clé API dans le tableau de bord de Braze.
Étape 4 : Initialiser Braze
Initialiser l’instance Braze :
1
2
m.BrazeTask = createObject("roSGNode", "BrazeTask")
m.Braze = getBrazeInstance(m.BrazeTask)
Configurations optionnelles
Journalisation
Pour déboguer votre intégration Braze, vous pouvez afficher la console de débogage Roku pour les journaux Braze. Pour en savoir plus, reportez-vous au Code de débogage des développeurs Roku.
À propos du SDK d’Unity Braze
Pour obtenir la liste complète des types, fonctions, variables et autres, consultez le fichier de déclaration d’Unity. En outre, si vous avez déjà intégré Unity manuellement pour iOS, vous pouvez passer à une intégration automatisée à la place.
Intégration du SDK Unity
Conditions préalables
Avant de commencer, vérifiez que votre environnement est pris en charge par la dernière version du SDK Braze Unity.
Étape 1 : Choisissez votre package Braze Unity
Le .unitypackage
Braze regroupe des liaisons natives pour les plateformes Android et iOS, ainsi qu’une interface C#.
Plusieurs paquets de Braze Unity peuvent être téléchargés sur la page des versions de Braze Unity:
Appboy.unitypackage
- Ce package regroupe les SDK Android et iOS Braze et la dépendance SDWebImage du SDK iOS, nécessaire pour le fonctionnement approprié des messages in-app de Braze et des fonctionnalités de cartes de contenu sur iOS. L’infrastructure SDWebImage est utilisée pour télécharger et afficher des images, y compris des GIF. Si vous avez l’intention d’utiliser la fonctionnalité Braze dans son intégralité, téléchargez et importez ce package.
Appboy-nodeps.unitypackage
- Ce package est similaire à
Appboy.unitypackage
, à l’exception du framework SDWebImage qui n’est pas présent. Ce package est utile si vous ne souhaitez pas que l’infrastructure SDWebImage soit présente dans votre application iOS.
- Ce package est similaire à
À partir d’Unity 2.6.0, l’artefact groupé du SDK Braze Android nécessite les dépendances AndroidX. Si vous utilisiez auparavant un jetified unitypackage
, alors vous pouvez effectuer une transition en toute sécurité vers le unitypackage
correspondant.
Le .unitypackage
Braze regroupe des liaisons natives pour les plateformes Android et iOS, ainsi qu’une interface C#.
Le package Braze Unity est disponible au téléchargement sur la page des versions de Braze Unity avec deux options d’intégration :
Appboy.unitypackage
uniquement- Ce paquet regroupe les SDK Android et iOS de Braze sans aucune dépendance supplémentaire. Cette méthode d’intégration ne permet pas d’utiliser pleinement l’envoi de messages in-app et les fonctionnalités de cartes de contenu de Braze sur iOS. Si vous avez l’intention d’utiliser toutes les fonctionnalités de Braze sans code personnalisé, utilisez plutôt l’option ci-dessous.
- Pour utiliser cette option d’intégration, assurez-vous que la case à côté de
Import SDWebImage dependency
est décochée dans l’interface utilisateur Unity sous Configuration Braze.
Appboy.unitypackage
avecSDWebImage
- Cette option d’intégration regroupe les SDK Android et iOS de Braze et la dépendance SDwebimage pour le SDK iOS, qui est nécessaire au bon fonctionnement de la messagerie in-app de Braze, et des fonctionnalités des cartes de contenu sur iOS. Le cadre
SDWebImage
est utilisé pour télécharger et afficher des images, y compris des GIF. Si vous avez l’intention d’utiliser la fonctionnalité Braze dans son intégralité, téléchargez et importez ce package. - Pour importer automatiquement
SDWebImage
, veillez à cocher la case à côté deImport SDWebImage dependency
dans l’interface utilisateur Unity sous Configuration Braze.
- Cette option d’intégration regroupe les SDK Android et iOS de Braze et la dépendance SDwebimage pour le SDK iOS, qui est nécessaire au bon fonctionnement de la messagerie in-app de Braze, et des fonctionnalités des cartes de contenu sur iOS. Le cadre
Pour savoir si vous avez besoin de la dépendance SDWebimage pour votre projet iOS, consultez le site iOS in-app message documentation.
Étape 2 : Importer le package
Dans Unity Editor, importez le package dans votre projet Unity en sélectionnant Actifs > Importer un package > Personnaliser le package. Cliquez ensuite sur Importer.
Vous pouvez également suivre les instructions pour Importer un package d’actifs Unity pour accéder à un guide plus détaillé sur l’importation des packages Unity personnalisés.
Si vous souhaitez importer le plug-in iOS ou Android uniquement, désélectionnez le sous-répertoire Plugins/Android
ou Plugins/iOS
lors de l’importation du Braze .unitypackage
.
Dans Unity Editor, importez le package dans votre projet Unity en sélectionnant Actifs > Importer un package > Personnaliser le package. Cliquez ensuite sur Importer.
Vous pouvez également suivre les instructions pour Importer un package d’actifs Unity pour accéder à un guide plus détaillé sur l’importation des packages Unity personnalisés.
Si vous souhaitez importer le plug-in iOS ou Android uniquement, désélectionnez le sous-répertoire Plugins/Android
ou Plugins/iOS
lors de l’importation du Braze .unitypackage
.
Étape 3 : Configurer le SDK
Étape 3.1 : Configurer AndroidManifest.xml
Pour remplir AndroidManifest.xml
de fonctionner. Si votre application n’a pas de AndroidManifest.xml
, vous pouvez utiliser ce qui suit comme modèle. Sinon, si vous avez déjà un AndroidManifest.xml
, assurez-vous que l’une des sections manquantes suivantes est ajoutée à votre AndroidManifest.xml
existant.
- Allez dans le répertoire
Assets/Plugins/Android/
et ouvrez votre fichierAndroidManifest.xml
. Il s’agit de l’emplacement/localisation par défaut dans l’éditeur Unity. - Dans votre site
AndroidManifest.xml
, ajoutez les permissions et activités requises dans le modèle suivant. - Lorsque vous aurez terminé, votre site
AndroidManifest.xml
ne devrait contenir qu’une seule activité avec"android.intent.category.LAUNCHER"
.
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
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="REPLACE_WITH_YOUR_PACKAGE_NAME">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:icon="@drawable/app_icon"
android:label="@string/app_name">
<!-- Calls the necessary Braze methods to ensure that analytics are collected and that push notifications are properly forwarded to the Unity application. -->
<activity android:name="com.braze.unity.BrazeUnityPlayerActivity"
android:theme="@style/UnityThemeSelector"
android:label="@string/app_name"
android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen"
android:screenOrientation="sensor">
<meta-data android:name="android.app.lib_name" android:value="unity" />
<meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="true" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- A Braze specific FirebaseMessagingService used to handle push notifications. -->
<service android:name="com.braze.push.BrazeFirebaseMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
</application>
</manifest>
Toutes les classes d’activité enregistrées dans votre fichier AndroidManifest.xml
doivent être pleinement intégrées au SDK Android de Braze, sinon vos analyses/analytiques ne seront pas collectées. Si vous ajoutez votre propre classe d’activité, veillez à étendre le lecteur Braze Unity afin d’éviter ce problème.
Étape 3.2 : Mettez à jour AndroidManifest.xml
avec le nom de votre paquet
Pour trouver le nom de votre paquet, cliquez sur Fichier > Paramètres de création > Paramètres du lecteur > Onglet Android.
Dans votre AndroidManifest.xml
, toutes les instances de REPLACE_WITH_YOUR_PACKAGE_NAME
doivent être remplacées par Package Name
par rapport à l’étape précédente.
Étape 3.3 : Ajouter les dépendances gradle
Pour ajouter des dépendances gradle à votre projet Unity, activez d’abord “Custom Main Gradle Template” dans vos paramètres de publication. Ceci créera un modèle gradle que votre projet utilisera. Un fichier gradle gère la mise en place des dépendances et d’autres paramètres du projet au moment de la création. Pour plus d’informations, consultez l’exemple d’application Braze Unity à la rubrique mainTemplate.gradle.
Les dépendances suivantes sont requises :
1
2
3
4
5
6
implementation 'com.google.firebase:firebase-messaging:22.0.0'
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"
implementation "androidx.recyclerview:recyclerview:1.2.1"
implementation "org.jetbrains.kotlin:kotlin-stdlib:1.6.0"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.1"
implementation 'androidx.core:core:1.6.0'
Vous pouvez également définir ces dépendances à l’aide du gestionnaire de dépendances externes.
Étape 3.4 : Automatiser l’intégration d’Unity dans Android
Braze fournit une solution Unity native pour l’automatisation de l’intégration Unity Android.
- Dans Unity Editor, ouvrez les paramètres de configuration de Braze en sélectionnant Braze > Configuration Braze.
- Cochez la case Automatiser l’intégration d’Unity Android.
- Dans le champ Clé API Braze, saisissez la clé API de votre application qui se trouve dans Gérer les paramètres depuis le tableau de bord de Braze.
Cette intégration automatique ne doit pas être utilisée avec un fichier braze.xml
créé manuellement, car les valeurs de configuration peuvent entrer en conflit pendant le projet. Si vous avez besoin d’un braze.xml
manuel, désactivez l’intégration automatique.
Étape 3.1 : Définir votre clé API
Braze fournit une solution Unity native pour l’automatisation de l’intégration Unity iOS. Cette solution modifie le projet Xcode conçu à l’aide du PostProcessBuildAttribute
et des sous-classes UnityAppController
de Unity avec la macro IMPL_APP_CONTROLLER_SUBCLASS
.
- Dans Unity Editor, ouvrez les paramètres de configuration de Braze en sélectionnant Braze > Configuration Braze.
- Cochez la case Automatiser l’intégration d’Unity iOS.
- Dans le champ Clé API Braze, saisissez la clé API de votre application qui se trouve dans Gérer les paramètres.
Si votre application utilise déjà une autre sous-classe UnityAppController
, vous devrez fusionner votre implémentation de sous-classe avec AppboyAppDelegate.mm
.
Personnaliser le package Unity
Étape 1 : Cloner le dépôt
Dans votre terminal, clonez le dépôt GitHub Braze Unity SDK, puis naviguez jusqu’à ce dossier :
1
2
git clone [email protected]:braze-inc/braze-unity-sdk.git
cd ~/PATH/TO/DIRECTORY/braze-unity-sdk
1
2
git clone git@github.com:braze-inc/braze-unity-sdk.git
cd C:\PATH\TO\DIRECTORY\braze-unity-sdk
Étape 2 : Exporter un paquet à partir d’un référentiel
Tout d’abord, lancez Unity et laissez-le tourner en arrière-plan. Ensuite, à la racine du référentiel, exécutez la commande suivante pour exporter le paquet vers braze-unity-sdk/unity-package/
.
1
/Applications/Unity/Unity.app/Contents/MacOS/Unity -batchmode -nographics -projectPath "$(pwd)" -executeMethod Appboy.Editor.Build.ExportAllPackages -quit
1
"%UNITY_PATH%" -batchmode -nographics -projectPath "%PROJECT_ROOT%" -executeMethod Appboy.Editor.Build.ExportAllPackages -quit
Si vous rencontrez des problèmes après avoir exécuté ces commandes, consultez Unity : Arguments de la ligne de commande.
Étape 3 : Importer le paquet dans Unity
- Dans Unity, importez le paquet souhaité dans votre projet Unity en naviguant vers Assets > Import Package > Custom Package.
- S’il y a des fichiers que vous ne voulez pas importer, désélectionnez-les maintenant.
- Personnalisez le paquet Unity exporté, situé à l’emplacement/localisation
Assets/Editor/Build.cs
.
Passer à une intégration automatisée (Swift uniquement)
Pour profiter de l’intégration automatisée iOS proposée dans le SDK Unity de Braze, suivez ces étapes pour passer d’un mode manuel à une intégration automatisée.
- Supprimez tous les codes liés à Braze de votre sous-classe
UnityAppController
de projet Xcode. - Supprimez les bibliothèques iOS de Braze de votre projet Unity ou Xcode (telles que
Appboy_iOS_SDK.framework
etSDWebImage.framework
). - Importez à nouveau le paquet Braze Unity dans votre projet. Pour une description complète, voir Étape 2 : Importez le paquet.
- Définissez à nouveau votre clé API. Pour une description complète, voir Étape 3.1 : Définissez votre clé API.
Configurations optionnelles
Consignation prolixe
Pour activer la journalisation verbeuse dans l’éditeur Unity, procédez comme suit :
- Ouvrez les paramètres de configuration de Braze en sélectionnant Braze > Configuration de Braze.
- Cliquez sur le menu déroulant Afficher les paramètres Android de Braze.
- Dans le champ Niveau de journalisation du SDK, saisissez la valeur 0.
Compatibilité Prime 31
Pour utiliser le plug-in Unity de Braze avec les plug-ins Prime31, modifiez le AndroidManifest.xml
de votre projet pour utiliser les classes d’activité compatibles Prime31. Modifier toutes les références de
com.braze.unity.BrazeUnityPlayerActivity
vers com.braze.unity.prime31compatible.BrazeUnityPlayerActivity
Amazon Device Messaging (ADM)
Braze prend en charge l’intégration d’ADM push dans les applications Unity. Si vous souhaitez intégrer ADM push, créez un fichier appelé api_key.txt
contenant votre clé API ADM et placez-le dans le dossier Plugins/Android/assets/
. Pour plus d’informations sur l’intégration d’ADM avec Braze, consultez nos instructions d’intégration d’ADM push.
Extension du lecteur Braze Unity (Android uniquement)
L’exemple de fichier AndroidManifest.xml
fourni contient une classe d’activité enregistrée, BrazeUnityPlayerActivity
. Cette classe est intégrée au SDK Braze et étend UnityPlayerActivity
à la gestion des sessions, l’enregistrement des messages in-app, la journalisation des analyses des notifications push et bien plus encore. Voir Unity pour plus d’informations sur l’extension de la classe UnityPlayerActivity
.
Si vous créez votre propre UnityPlayerActivity
dans un projet de bibliothèque ou de plugin, vous devrez étendre notre BrazeUnityPlayerActivity
pour intégrer votre fonctionnalité personnalisée avec Braze. Avant de commencer à travailler sur l’extension BrazeUnityPlayerActivity
, suivez nos instructions pour intégrer Braze dans votre projet Unity.
- Ajoutez le SDK Android de Braze en tant que dépendance à votre bibliothèque ou à votre projet de plug-in comme décrit dans les instructions d’intégration du SDK Android de Braze.
- Intégrez notre
.aar
Unity, qui contient notre fonctionnalité spécifique à Unity, à votre projet de bibliothèque Android que vous constituez pour Unity. Leappboy-unity.aar
est disponible dans notre dépôt public. Une fois que notre bibliothèque Unity a été intégrée avec succès, modifiez votreUnityPlayerActivity
pour étendreBrazeUnityPlayerActivity
. - Exportez votre bibliothèque ou votre projet de plug-in et déposez-le dans
/<your-project>/Assets/Plugins/Android
de manière habituelle. N’incluez pas de code source Braze dans votre bibliothèque ou votre plug-in, car ils seront déjà présents dans/<your-project>/Assets/Plugins/Android
. - Modifier votre
/<your-project>/Assets/Plugins/Android/AndroidManifest.xml
pour spécifier votre sous-classeBrazeUnityPlayerActivity
comme activité principale.
Vous devriez maintenant pouvoir mettre en package un .apk
depuis l’IDE Unity qui est entièrement intégré à Braze et contient votre fonctionnalité UnityPlayerActivity
personnalisée.
Résolution des problèmes
Erreur : “Le fichier n’a pas pu être lu
Les erreurs ressemblant à ce qui suit peuvent être ignorées en toute sécurité. Le logiciel Apple utilise une extension PNG exclusive appelée CgBI, qu’Unity ne reconnaît pas. Ces erreurs n’affecteront ni votre iOS ni l’affichage approprié des images associées dans le paquet Braze.
1
Could not create texture from Assets/Plugins/iOS/AppboyKit/Appboy.bundle/...png: File could not be read
À propos du SDK du moteur Unreal Braze
Avec le plugin Braze Unreal SDK, vous pouvez :
- Évaluer et suivre les sessions dans votre application ou votre jeu
- Suivre des achats et des événements personnalisés dans l’application
- Mettre à jour les profils d’utilisateur avec des attributs standard et personnalisés
- Envoyer des notifications push
- Intégrer vos applications Unreal à des parcours Canvas plus importants
- Envoyer des communications cross-canaux, comme par exemple par e-mail ou SMS, en fonction des interactions dans l’application
Intégration du SDK d’Unreal Engine
Étape 1 : Ajouter le plugin Braze
Dans votre terminal, clonez le dépôt GitHub Unreal Engine Braze SDK.
1
git clone [email protected]:braze-inc/braze-unreal-sdk.git
Copiez ensuite le répertoire BrazeSample/Plugins/Braze
et ajoutez-le dans le dossier Plugin de votre application.
Étape 2 : Activer le plugin
Activez le plugin pour votre projet C++ ou Blueprint.
Pour les projets C++, configurez votre module pour qu’il fasse référence au module Braze. Dans votre \*.Build.cs file
, ajoutez "Braze"
à votre PublicDependencyModuleNames
.
1
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "Braze" });
Pour les projets Blueprint, allez dans Settings > Plugins, puis à côté de Braze cochez Enabled.
Étape 3 : Définissez votre clé API et votre endpoint.
Définissez votre clé API et votre endpoint dans le projet DefaultEngine.ini
.
1
2
3
4
5
[/Script/Braze.BrazeConfig]
bAutoInitialize=True ; true by default, initialize when the project starts
AndroidApiKey= ; your API key
IOSApiKey= ; your API key
CustomEndpoint= ; your endpoint
Pour les projets ciblant le SDK Android 31+, Unreal créera des builds qui échoueront lors de l’installation sur les appareils Android 12+ avec l’erreur INSTALL_PARSE_FAILED_MANIFEST_MALFORMED. Pour corriger ce problème, localisez le fichier patch UE4_Engine_AndroidSDK_31_Build_Fix.patch
git à la racine de ce dépôt et appliquez-le à votre création des sources d’Unreal.
Configurations optionnelles
Journalisation
Vous pouvez définir le niveau de journalisation au moment de l’exécution en utilisant C++ ou dans un nœud de Blueprint.
Pour définir le niveau de journalisation au moment de l’exécution, appelez UBrazeSubsystem::AndroidSetLogLevel
.
1
2
3
UBrazeSubsystem* const BrazeSubsystem = GEngine->GetEngineSubsystem<UBrazeSubsystem>();
BrazeSubsystem->AndroidSetLogLevel(EBrazeLogLevel::Verbose);
UBraze* const BrazeInstance = BrazeSubsystem->InitializeBraze();
Dans Blueprint, vous pouvez utiliser le nœud Android Set Log Level :
Afin de s’assurer que la journalisation est définie lorsque le SDK Braze Initialize est appelé, il est recommandé de l’appeler avant InitializeBraze
.
Pour activer le niveau de journalisation sur le site info.plist
, allez dans Réglages > Réglages du projet, puis sélectionnez iOS sous Plateformes. Sous Extra PList Data, recherchez Additional Plist Data, puis entrez votre niveau de journal :
1
2
3
4
5
<key>Appboy</key>
<dict>
<key>LogLevel</key>
<string>0</string>
</dict>
Le niveau de journalisation par défaut est 8, ce qui correspond à une journalisation minimale. Pour en savoir plus sur les niveaux de journalisation : Autres personnalisations du SDK
Integrating the Xamarin SDK
Integrating the Braze Xamarin SDK will provide you with basic analytics functionality as well as working in-app messages with which you can engage your users.
Prerequisites
Before you can integrate the Xamarin Braze SDK, be sure you meet the following requirements:
- Starting in
version 3.0.0
, this SDK requires using .NET 6+ and removes support for projects using the Xamarin framework. - Starting in
version 4.0.0
, this SDK dropped support for Xamarin & Xamarin.Forms and added support for .NET MAUI. See Microsoft’s policy around the end of support for Xamarin.
Step 1: Get the Xamarin binding
A Xamarin binding is a way to use native libraries in Xamarin apps. The implementation of a binding consists of building a C# interface to the library, and then using that interface in your application. See the Xamarin documentation. There are two ways to include the Braze SDK binding: using NuGet or compiling from source.
The simplest integration method involves getting the Braze SDK from the NuGet.org central repository. In the Visual Studio sidebar, right click Packages
folder and click Add Packages...
. Search for ‘Braze’ and install the BrazePlatform.BrazeAndroidBinding
package into your project.
The second integration method is to include the binding source. Under appboy-component/src/androidnet6
you will find our binding source code; adding a project reference to the BrazeAndroidBinding.csproj
in your Xamarin application will cause the binding to be built with your project and provide you access to the Braze Android SDK.
The iOS bindings for Xamarin SDK version 4.0.0 and later use the Braze Swift SDK, while previous versions use the legacy AppboyKit SDK.
A Xamarin binding is a way to use native libraries in Xamarin apps. The implementation of a binding consists of building a C# interface to the library and then using that interface in your application. There are two ways to include the Braze SDK binding: using NuGet or compiling from source.
The simplest integration method involves getting the Braze SDK from the NuGet.org central repository. In the Visual Studio sidebar, right-click Packages
folder and click Add Packages...
. Search for ‘Braze’ and install the latest Xamarin iOS NuGet packages: Braze.iOS.BrazeKit, Braze.iOS.BrazeUI, and Braze.iOS.BrazeLocation into your project.
We also provide the compatibility libraries packages: Braze.iOS.BrazeKitCompat and Braze.iOS.BrazeUICompat, to help make your migration to .NET MAUI easier.
The second integration method is to include the binding source. Under appboy-component/src/iosnet6
you will find our binding source code; adding a project reference to the BrazeiOSBinding.csproj
in your Xamarin application will cause the binding to be built with your project and provide you access to the Braze iOS SDK. Make sure BrazeiOSBinding.csproj
is showing in your project’s “Reference” folder.
Step 2: Configure your Braze instance
Step 2.1: Configure the Braze SDK in Braze.xml
Now that the libraries have been integrated, you have to create an Braze.xml
file in your project’s Resources/values
folder. The contents of that file should resemble the following code snippet:
Be sure to substitute YOUR_API_KEY
with the API key located at Settings > API Keys in the Braze dashboard.
If you are using the older navigation, you can find API keys at Developer Console > API Settings..
1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string translatable="false" name="com_braze_api_key">YOUR_API_KEY</string>
<string translatable="false" name="com_braze_custom_endpoint">YOUR_CUSTOM_ENDPOINT_OR_CLUSTER</string>
<string-array name="com_braze_internal_sdk_metadata">
<item>XAMARIN</item>
<item>NUGET</item>
</string-array>
</resources>
If you are including the binding source manually, remove <item>NUGET</item>
from your code.
To see an example Braze.xml
, check out our Android MAUI sample app.
Step 2.2: Add required permissions to Android manifest
Now that you’ve added your API key, you need to add the following permissions to your AndroidManifest.xml
file:
1
<uses-permission android:name="android.permission.INTERNET" />
For an example of your AndroidManifest.xml
, see the Android MAUI sample application.
Step 2.3: Track user sessions and registering for in-app messages
To enable user session tracking and register your app for in-app messages, add the following call to the OnCreate()
lifecycle method of the Application
class in your app:
1
RegisterActivityLifecycleCallbacks(new BrazeActivityLifecycleCallbackListener());
When setting up your Braze instance, add the following snippet to configure your instance:
Be sure to substitute YOUR_API_KEY
with the API key located at Settings > API Keys in the Braze dashboard.
If you are using the older navigation, you can find API keys at Developer Console > API Settings..
1
2
3
var configuration = new BRZConfiguration("YOUR_API_KEY", "YOUR_ENDPOINT");
configuration.Api.AddSDKMetadata(new[] { BRZSDKMetadata.Xamarin });
braze = new Braze(configuration);
See the App.xaml.cs
file in the iOS MAUI sample application.
Step 3: Test the integration
Now you can launch your application and see sessions being logged to the Braze dashboard (along with device information and other analytics). For a more in-depth discussion of best practices for the basic SDK integration, consult the Android integration instructions.
Now you can launch your application and see sessions being logged to the Braze dashboard. For a more in-depth discussion of best practices for the basic SDK integration, consult the iOS integration instructions.
Our current public Xamarin binding for the iOS SDK does not connect to the iOS Facebook SDK (linking social data) and does not include sending the IDFA to Braze.
Lors de l’assurance qualité de votre intégration SDK, utilisez le débogueur SDK pour résoudre les problèmes sans avoir à activer l’enregistrement des données pour votre application.