# developer Salesforce Engagement SDK (marketing-cloud-mobilepush) - Full Documentation # Action **Package:** `com.salesforce.marketingcloud.pushmodels.data` **Module:** Push Models Module v1.0.2 ```kotlin sealed class Action : Parcelable ``` ## Description Actions define the behavior of user events on push notifications. ## Inheritors - [OpenApp](#openapp) - [Deeplink](#deeplink) - [Url](#url) - [CloudPage](#cloudpage) - [Dismiss](#dismiss) ## Types ### CloudPage ```kotlin data class CloudPage(val url: String) : Action ``` Opens cloud page via a URL in the default browser. **Parameters:** - `url`: String - The URL to the cloud page --- ### Deeplink ```kotlin data class Deeplink(val url: String) : Action ``` Opens a deep link via UrlHandler. **Parameters:** - `url`: String - The deep link URL --- ### Url ```kotlin data class Url(val url: String) : Action ``` Opens a URL in the default browser. **Parameters:** - `url`: String - The URL to open --- ### OpenApp ```kotlin object OpenApp : Action ``` Launches the integrating app. --- ### Dismiss ```kotlin object Dismiss : Action ``` Dismisses the notification. --- ### Type ```kotlin enum Type : Enum ``` Enum representing action types. --- ### Companion ```kotlin object Companion ``` Companion object for the Action class. ## Properties ### type ```kotlin val type: Int ``` The type identifier for the action. ## Functions ### toJson ```kotlin fun toJson(): JSONObject ``` Converts the Action to a JSON representation. **Returns:** `JSONObject` - JSON representation of the action # Add Beacons Use the Salesforce Engagement SDK to trigger proximity-based notifications when users come near Bluetooth beacons. Follow these steps to add beacon support to your Android app. 1. Add `AltBeacon` and `Google Play Service Location` dependencies to your build. ``` dependencies { implementation 'com.google.android.gms:play-services-location:{currentLocationVersion}' implementation 'org.altbeacon:android-beacon-library:{currentBeaconVersion}' } ``` **important:** To ensure compatibility with the current SDK, replace `{currentBeaconVersion}` with `2.20-beta1` and `{currentLocationVersion}` with `21.0.1`. These versions have been tested with the latest SDK version. Other versions of these dependencies aren't guaranteed to be compatible, which can lead to unexpected behavior. 2. Add these permissions to your application's `AndroidManifest.xml`. ```xml ``` 3. Enable beacon messaging during SDK initialization with the configuration shown in these examples. ::::::tabset{tabs='["SDK v10+", "SDK v8", "SDK v7"]'} :::::tab For SDK version 10 or higher, use this example. ```java SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { engagementModuleConfig = MarketingCloudConfig.builder().apply { // Other configuration values setProximityNotificationOptions( // Required config to show foreground notification ProximityNotificationCustomizationOptions.create(R.mipmap.ic_notification_foreground) ) setProximityEnabled(true) // Enable Beacon messaging, default = false }.build(applicationContext) }) { // Handle initialization status } ``` ::::: :::::tab For SDK version 8, use this example. ```java SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { pushModuleConfig = MarketingCloudConfig.builder().apply { // Other configuration values setProximityEnabled(true) // Enable Beacon messaging, default = false }.build(applicationContext) }) { // Handle initialization status } ``` ::::: :::::tab For SDK version 7, use this example. ```java MarketingCloudSdk.init(applicationContext as Application, with(MarketingCloudConfig.builder()) { // Other configuration values setProximityEnabled(true) // Enable Beacon messaging, default = false build(applicationContext) }) { // Handle initialization status } ``` ::::: :::::: **important:** To troubleshoot information related to beacon messaging, examine the [`InitializationStatus`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud/-initialization-status/index.html) returned during the SDK's initialization call. For more information about troubleshooting the SDK, see [Troubleshoot Initialization Errors](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_troubleshooting/mc_engagement_troubleshooting_android.md). 4. To enable proximity messaging, request the required location permissions from your users at runtime. For users on devices that run [Android 10](https://developer.android.com/about/versions/10/privacy/changes#app-access-device-location) and later, request both the [ACCESS_FINE_LOCATION](https://developer.android.com/reference/android/Manifest.permission#ACCESS_FINE_LOCATION) and [ACCESS_BACKGROUND_LOCATION](https://developer.android.com/reference/android/Manifest.permission#ACCESS_BACKGROUND_LOCATION) permissions. For users with devices that run earlier versions of Android, request only the `ACCESS_FINE_LOCATION` permission. 5. To enable proximity messaging, request the required location permissions from your users at runtime. For users on devices running Android 11 and later, add request for [BLUETOOTH_CONNECT](https://developer.android.com/reference/android/Manifest.permission#BLUETOOTH_CONNECT). For users on devices running Android 12 and later, also request for [BLUETOOTH_SCAN](https://developer.android.com/reference/android/Manifest.permission#BLUETOOTH_SCAN) permission. For users on devices that run [Android 14](https://developer.android.com/about/versions/14/changes/fgs-types-required) and later, also request for [FOREGROUND_SERVICE](https://developer.android.com/reference/android/Manifest.permission#FOREGROUND_SERVICE). **note:** For information on requesting runtime permissions, see [Request runtime permissions](https://developer.android.com/training/permissions/requesting.html). For more information on requesting location updates, see [Request location updates](https://developer.android.com/preview/privacy/device-location). 6. After all the permissions are granted, enable beacon messaging by calling [enableProximityMessaging()](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages/-region-message-manager/enable-proximity-messaging.html) at runtime. Alternatively, call [disableProximityMessaging()](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages/-region-message-manager/disable-proximity-messaging.html) to disable beacon messaging. ::::::tabset{tabs='["SDK v10+", "SDK v8", "SDK v7"]'} :::::tab For SDK version 10 or higher, use this example. ```java MarketingCloudSdk.requestSdk { it.regionMessageManager.enableProximityMessaging() // Disable beacon messaging // it.regionMessageManager.disableProximityMessaging() } ``` ::::: :::::tab For SDK version 8, use this example. ```java SFMCSdk.requestSdk { sdk -> sdk.mp { it.regionMessageManager.enableProximityMessaging() // Disable beacon messaging // it.regionMessageManager.disableProximityMessaging() } } ``` ::::: :::::tab For SDK version 7, use this example. ```java MarketingCloudSdk.requestSdk { sdk -> sdk.regionMessageManager.enableProximityMessaging() // Disable beacon messaging // sdk.regionMessageManager.disableProximityMessaging() } ``` ::::: :::::: **important:** The SDK suppresses beacon messages that don't contain any content. If you include AMPscript or a merge field in your message that returns an empty string, your app doesn't display that message to the user. For information about how beacons behave in different situations, see _Salesforce Help_: [MobilePush Beacon Scenarios](https://help.salesforce.com/articleView?id=mktg.mc_mp_beacon_behavior.htm). # Add Geofences Enable geofence messaging to trigger location-based notifications when users cross geofence boundaries. Follow these steps to add geofence support to your Android app. ## Add Dependencies Add `Google Play Service Location` dependency to your `build.gradle` file. ``` dependencies { implementation 'com.google.android.gms:play-services-location:{currentSupportedVersion}' } ``` **important:** To be compatible with the current version of the SDK, replace `{currentSupportedVersion}` with `21.0.1`. The SDK has been tested using this version of Google Play Services. Compatibility with other versions isn't guaranteed. ## Add Permissions Add these permissions to your application's `AndroidManifest.xml`. ```xml ``` ## Enable During SDK Initialization Enable geofence messaging during SDK initialization with the configuration shown in these examples.
SDK v10+ For SDK version 10 or higher, use this example. ```java SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { engagementModuleConfig = MarketingCloudConfig.builder().apply { // Other configuration values setGeofencingEnabled(true) // Enable Geofence messaging, default = false }.build(applicationContext) }) { // Handle initialization status } ```
SDK v8 For SDK version 8, use this example. ```java SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { pushModuleConfig = MarketingCloudConfig.builder().apply { // Other configuration values setGeofencingEnabled(true) // Enable Geofence messaging, default = false }.build(applicationContext) }) { // TODO handle initialization status } ```
SDK v7 For SDK version 7, use this example. ```java MarketingCloudSdk.init(applicationContext as Application, with(MarketingCloudConfig.builder()) { // Other configuration values setGeofencingEnabled(true) // Enable Geofence messaging, default = false build(applicationContext) }) { // TODO Handle initialization status } ```
**important:** To troubleshoot information related to geofence messaging, examine the [InitializationStatus](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud/-initialization-status/index.html) returned during the initialization call for the SDK. See [Troubleshoot Initialization Errors](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_troubleshooting/mc_engagement_troubleshooting_android_initialization_errors.md). ## Request Location Permissions To enable geofence messaging, request the required location permissions from your users at runtime. For users on devices that run [Android 10](https://developer.android.com/about/versions/10/privacy/changes#app-access-device-location) or later, request both the [`ACCESS_FINE_LOCATION`](https://developer.android.com/reference/android/Manifest.permission#ACCESS_FINE_LOCATION) and [`ACCESS_BACKGROUND_LOCATION`](https://developer.android.com/reference/android/Manifest.permission#ACCESS_BACKGROUND_LOCATION) permissions. For users on devices older than Android 10, you can request only the `ACCESS_FINE_LOCATION` permission. **note:** For more information on requesting location updates, see [Request location updates](https://developer.android.com/preview/privacy/device-location). For information on requesting runtime permissions, see [Request runtime permissions](https://developer.android.com/training/permissions/requesting.html). ## Enable or Disable at Runtime After the permission is granted, enable geofence messaging by calling [`enableGeofenceMessaging()`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages/-region-message-manager/enable-geofence-messaging.html) at runtime. Alternatively, call [`disableGeofenceMessaging()`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages/-region-message-manager/disable-geofence-messaging.html) to disable geofence messaging.
SDK v10+ For SDK version 10 or higher, use this example. ```java MarketingCloudSdk.requestSdk { it.regionMessageManager.enableGeofenceMessaging() // Disable geofence messaging //it.regionMessageManager.disableGeofenceMessaging() } ```
SDK v8 For SDK version 8, use this example. ```java SFMCSdk.requestSdk { sdk -> sdk.mp { it.regionMessageManager.enableGeofenceMessaging() // Disable geofence messaging //it.regionMessageManager.disableGeofenceMessaging() } } ```
SDK v7 For SDK version 7, use this example. ```java MarketingCloudSdk.requestSdk { sdk -> sdk.regionMessageManager.enableGeofenceMessaging() // Disable geofence messaging //sdk.regionMessageManager.disableGeofenceMessaging() } ```
**important:** The SDK suppresses geofence messages with no content. If you include AMPscript or a merge field in your message that returns an empty string, your app doesn't display that message to the user. # Add the SDK Dependencies by using CocoaPods To add the Mobile App Messaging SDK as a dependency in your app’s Podfile, add the pod to your Xcode project. See _Using CocoaPods_: [Adding Pods to an Xcode project](https://guides.cocoapods.org/using/using-cocoapods.html). 1. Use this code example to specify the dependencies in your app’s Podfile. ```swift target 'MyApp' do pod 'SFPushFeatureSDK' pod 'SFMobileAppMessagingSDK' pod 'SFInAppMessagingFeatureSDK' end ``` **important:** The pods listed in this example include the `SFMCSDK` module automatically. Don't add the module to your podfile manually. 2. Open the `.xcworkspace` created by the installation process in Xcode. **important:** Don’t open `.xcodeproj` directly. Opening a project file instead of a workspace can lead to errors. 3. After you add the dependencies, [configure the SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_integrate_ios_configure.md). # Add the SDK Dependencies by using Swift Package Manager You can add the Mobile App Messaging, In-App Messaging, and Push Messaging modules as dependencies in your app’s Podfile using Swift Package Manager (SPM). 1. In your Xcode project, go to the **Package Dependencies** tab of your project’s settings. ![The Xcode project settings page with the Package Dependencies tab highlighted](https://developer.salesforce.com/media/quickstart/ios-spm-add-dependancy.png) 2. Add a package by clicking the plus sign (**+**). 3. Search for [Mobile App Messaging](https://github.com/salesforce-marketingcloud/mam-core-sdk-ios.git), [In-App Messaging](https://github.com/salesforce-marketingcloud/iam-feature-sdk-ios.git), and [Push Messaging](https://github.com/salesforce-marketingcloud/push-feature-sdk-ios.git) modules. ![The Swift Package Manager screen with the mam-core-sdk-ios package highlighted](https://developer.salesforce.com/media/quickstart/ios-spm-search-mam-dependency.png) 4. Select the packages to include them in your app. ![A list of package products in Swift Package Manager for the mam-core-sdk-ios package](https://developer.salesforce.com/media/quickstart/ios-spm-select-mam-dependency.png) After you add the dependencies, [configure the SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_integrate_ios_configure.md). # Add the SDK Dependencies Manually To manually add the dependencies for the Mobile App Messaging SDK in your app’s Podfile, complete these steps. **important:** Download these frameworks only from the linked GitHub repositories. 1. Download these SDKs: - [`MobileAppMessagingSDK`](https://github.com/salesforce-marketingcloud/mam-core-sdk-ios) - [`SFMCSDK`](https://github.com/salesforce-marketingcloud/sfmc-sdk-ios) - [`AppGroupSDK`](https://github.com/salesforce-marketingcloud/app-group-internal-sdk) - [`PushFeatureSDK`](https://github.com/salesforce-marketingcloud/push-feature-sdk-ios) - [`InAppFeatureSDK`](https://github.com/salesforce-marketingcloud/iam-feature-sdk-ios) 2. Copy these directories from your downloads folder to your project directory: - `AppGroupSDK.xcframework` - `InAppMessagingFeatureSDK.xcframework` - `MobileAppMessagingSDK.xcframework` - `PushFeatureSDK.xcframework` - `SFMCSDK.xcframework` 3. Open your application project and select the appropriate target. ![An Xcode project, showing a target selected](https://developer.salesforce.com/media/quickstart/configure-core-sdk-2-3.png) 4. Add `AppGroupSDK.xcframework`, `InAppMessagingFeatureSDK.xcframework`, `MobileAppMessagingSDK.xcframework`, `PushFeatureSDK.xcframework`, and `SFMCSDK.xcframework` to **Frameworks, Libraries, and Embedded Content** in your target’s **General** settings. ![The target’s General settings, showing the frameworks added to the Frameworks, Libraries, and Embedded Content section](https://developer.salesforce.com/media/quickstart/mam-manual-configure-sdk-3.png) 5. Add `-ObjC` to your target’s **Other Linker Flags** build settings. ![The Build Settings tab, showing the -ObjC option added to the Other Linker Flags section](https://developer.salesforce.com/media/quickstart/configure-the-ios-sdk-5.png) After you add the dependencies, [configure the SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_integrate_ios_configure.md). # addTag Add a tag to the device's registration. ## Syntax `MCCordovaPlugin.addTag(tag, [successCallback], [errorCallback])` ## Kind Static method of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | ----------------------- | ---------- | -------------------------------------------------------------------- | | `tag` | `string` | The tag to add to the list of tags in the registration. | | `successCallback` | `function` | | | `successCallback.saved` | `boolean` | Whether the value passed in for `tag` was saved in the registration. | | `errorCallback` | `function` | | ## See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/MarketingCloudSdk/8.0/-marketing%20-cloud%20-s-d-k/com.salesforce.marketingcloud.registration/-registration-manager/-editor/add-tag.html) - _SDK Reference for iOS_: [addTag() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/ios-sdk-v11/mce-sdk/classes/marketingcloudsdk.md#addtag_) # addTag Adds a tag to the device for targeted messaging. ## Syntax ```dart Future addTag(String tag) ``` ## Parameters - `tag` (String) - The tag to add ## Returns - `Future` - Completes when the tag has been added. ## Example ```dart try { await SfmcSdk.addTag('premium_user'); await SfmcSdk.addTag('newsletter_subscriber'); print('Tags added successfully'); } catch (e) { print('Failed to add tag: $e'); } ``` ## Related Methods - [removeTag()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_removeTag.md) - [getTags()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getTags.md) # addTag Adds a tag to the list of tags in the registration. ## Syntax ```javascript MCReactModule.addTag(tag); ``` ## Parameters | Parameter | Type | Description | | --------- | -------- | ------------------------------------------------------- | | `tag` | `string` | The tag to add to the list of tags in the registration. | ## Returns - `void` - No return value. ## Example ```javascript import { MCReactModule } from "react-native-marketingcloudsdk"; const addUserTags = () => { try { MCReactModule.addTag("premium_user"); MCReactModule.addTag("newsletter_subscriber"); console.log("Tags added successfully"); } catch (error) { console.error("Error adding tag:", error); } }; ``` ## See Also - [removeTag() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_removeTag.md) - [getTags() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_getTags.md) - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/MarketingCloudSdk/8.0/-marketing%20-cloud%20-s-d-k/com.salesforce.marketingcloud.registration/-registration-manager/-editor/add-tag.html) - _SDK Reference for iOS_: [MarketingCloudSdk Class](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/ios-sdk-v11/mce-sdk/classes/marketingcloudsdk.md) # AddToCartEvent `Class` ## Package ```kotlin com.salesforce.marketingcloud.sfmcsdk.components.events ``` ## Description An e-commerce event that represents when a user adds an item to their shopping cart. This class is part of the Salesforce Marketing Cloud Unified SDK and extends `CartEvent` to provide functionality for tracking add-to-cart actions in e-commerce applications. ## Declaration ```kotlin class AddToCartEvent : CartEvent ``` **Platform:** androidJvm **SDK Version:** 11.0.0 ## Inheritance Hierarchy ``` Event └── EngagementEvent └── CartEvent └── AddToCartEvent ``` ## Inherited Properties ### `lineItems` A list of line items associated with the cart event. ```kotlin val lineItems: List ``` **Type:** `List` **Access:** Read-only **Inherited from:** `CartEvent` --- ### `category` The event category name. Category contains list of allowed values. ```kotlin open override var category: Event.Category ``` **Type:** `Event.Category` **Access:** Read/write **Inherited from:** `EngagementEvent` --- ### `priority` Priority level for this event. ```kotlin open override val priority: Priority ``` **Type:** `Priority` **Access:** Read-only **Inherited from:** `EngagementEvent` --- ## Inherited Methods ### `attributes()` Returns the event attributes for this event. ```kotlin open override fun attributes(): Map ``` **Returns:** `Map` - A map containing the event's attributes as key-value pairs. **Inherited from:** `EngagementEvent` --- ### `name()` Returns the name for the event. This value must match the Event Name used when creating the event in the Marketing Cloud UI for any action to result from tracking this event. ```kotlin open override fun name(): String ``` **Returns:** `String` - The event name. **Inherited from:** `EngagementEvent` --- ## Related Types ### LineItem Data class that describes purchasable items for Cart & Order events. #### Constructor ```kotlin @JvmOverloads constructor( catalogObjectType: String, catalogObjectId: String, quantity: Int, price: Double? = null, currency: String? = null, attributes: Map = mapOf() ) ``` #### Parameters | Parameter | Type | Required | Description | | ------------------- | ------------------ | -------- | --------------------------------------------------- | | `catalogObjectType` | `String` | Yes | Type name for the catalog object in the line item | | `catalogObjectId` | `String` | Yes | Unique identifier for the catalog object | | `quantity` | `Int` | Yes | Number of catalog objects in this line item | | `price` | `Double?` | No | Price of the catalog object (defaults to null) | | `currency` | `String?` | No | Currency for the price field (defaults to null) | | `attributes` | `Map` | No | Map of user-supplied values (defaults to empty map) | #### Properties | Property | Type | Mutability | Description | | ------------------- | ------------------ | ---------- | --------------------------------------------------- | | `catalogObjectType` | `String` | Read-only | Type name for the referenced catalog object | | `catalogObjectId` | `String` | Read-only | Unique identifier for the referenced catalog object | | `quantity` | `Int` | Read-only | Number of catalog objects in the line item | | `price` | `Double?` | Mutable | Price of the referenced catalog object | | `currency` | `String?` | Mutable | Currency for the price field | | `attributes` | `Map` | Mutable | Map of user-supplied values | --- ## See Also - **CartEvent** - Base sealed class for cart-related events - **RemoveFromCartEvent** - Event for when a user removes an item from their shopping cart - **ReplaceCartEvent** - Event for when a user replaces their shopping cart with a list of items - **EngagementEvent** - Base sealed class for engagement-related events - **EventManager** - Manages event tracking (initialized during `SFMCSdk.configure` call) - **LineItem** - Data class describing purchasable items # Advanced Push Notification Customization for the Android SDK When providing a builder to the [NotificationCustomizationOptions](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.notifications/-notification-customization-options/index.html) class, you’re responsible for managing all aspects of the notification’s display properties and tap actions, including Notification Channel creation, Launch Intent action, and so on. You can access the [NotificationCompat.Builder](https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder) that would have been used by the SDK and use it as a baseline for modifications. Additionally, the SDK can create a default [`NotificationChannel`](https://developer.android.com/reference/android/app/NotificationChannel) for your application. **note:** To have Marketing Cloud Engagement collect notification open analytics for your notifications, wrap your `PendingIntent` in the SDK’s analytics helper method [NotificationManager.redirectForAnalytics()](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.notifications/-notification-manager/-companion/redirect-intent-for-analytics.html). ::::::tabset{tabs='["SDK v10+", "SDK v8", "SDK v7"]'} :::::tab ```java SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { pushFeatureModuleConfig = PushFeatureConfig.builder().apply { // Other configuration values setNotificationCustomizationOptions( NotificationCustomizationOptions.create { context, notificationMessage -> val builder = NotificationManager.getDefaultNotificationBuilder( context, notificationMessage, NotificationManager.createDefaultNotificationChannel(context), R.drawable.ic_notification_icon ) builder.setContentIntent( NotificationManager.redirectIntentForAnalytics( context, PendingIntent.getActivity( context, Random().nextInt(), Intent(context, MainActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ), notificationMessage, true ) ) } ) }.build() }) { // Handle initialization status } ``` ::::: :::::tab ```java SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { pushModuleConfig = MarketingCloudConfig.builder().apply { // Other configuration values setNotificationCustomizationOptions( NotificationCustomizationOptions.create { context, notificationMessage -> val builder = NotificationManager.getDefaultNotificationBuilder( context, notificationMessage, NotificationManager.createDefaultNotificationChannel(context), R.drawable.ic_notification_icon ) builder.setContentIntent( NotificationManager.redirectIntentForAnalytics( context, PendingIntent.getActivity( context, Random().nextInt(), Intent(context, MainActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ), notificationMessage, true ) ) } ) }.build(applicationContext) }) { // TODO handle initialization status } ``` ::::: :::::tab ```java MarketingCloudSdk.init(applicationContext as Application, MarketingCloudConfig.builder().apply { // Other configuration values setNotificationCustomizationOptions( NotificationCustomizationOptions.create { context, notificationMessage -> val builder = NotificationManager.getDefaultNotificationBuilder( context, notificationMessage, NotificationManager.createDefaultNotificationChannel(context), R.drawable.ic_notification_icon ) builder.setContentIntent( NotificationManager.redirectIntentForAnalytics( context, PendingIntent.getActivity( context, Random().nextInt(), Intent(context, MainActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ), notificationMessage, true ) ) } ) }.build(applicationContext)) { status -> // TODO Handle initialization status } ``` ::::: :::::: # Alert + Inbox Messages The Alert + Inbox feature is designed to enable users to tap on an inbox push notification and get redirected to the corresponding inbox message. The inbox data is added to the push notification payload. Because of restrictions on the payload size, you can't add all inbox fields to the push payload. However, users are still redirected to the message without issues, and all fields become available when they return to the inbox. Initially, these fields aren't available in the Alert + Inbox Message dictionary: - `sendDateUtc` - `startDateUtc` - `endDateUtc` - `subject` ## Mark Inbox Read on Notification Clicked for Alert + Inbox Message To automatically mark an inbox message as read after a user taps an inbox push notification, enable the `setMarkMessageReadOnInboxNotificationOpen` feature in the `PushConfigBuilder`. ## Mark Inbox Read When a Notification is Clicked By default, if user taps on the notification for an `Alert+Inbox` message, the SDK marks the inbox message as read. You can toggle this behavior by changing the value of [markMessageReadOnInboxNotificationOpen](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud/-marketing-cloud-config/mark-message-read-on-inbox-notification-open.html) in [MarketingCloudConfig](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud/-marketing-cloud-config/index.html). **important:** The SDK doesn't automatically present URLs from `Alert+CloudPage` push messages. To handle the URLs from these messages, [customize notification handling](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_push_notifications/mc_engagement_push_notifications_android_customize.md) for the app. # Alert + Inbox Messages The Alert + Inbox feature enables users to tap on an inbox push notification and get redirected to the corresponding inbox message. The inbox data is added to the push notification payload. However, due to Apple's payload size restrictions, not all inbox fields can be added to the push payload. Nevertheless, users are still redirected to the message without issues, and all fields become available when they return to the inbox. Initially, these fields aren't available in the Alert + Inbox Message dictionary: - `sendDateUtc` - `startDateUtc` - `endDateUtc` - `subject` - `statusDirty` ## Mark Inbox Read on Notification Clicked To automatically mark an inbox message as read when a user taps on an inbox push notification, enable or disable the `setMarkMessageReadOnInboxNotificationOpen` feature in the `PushConfigBuilder`. ## Refresh Inbox Messages When Application is in The Foreground When the application receives an Alert + Inbox notification while it's in the foreground, call the `refreshMessages` method to fetch the latest inbox messages. This step makes sure that the UI contains the most recent content. For an example, see the [iOS LearningApp](https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS/blob/spm/examples/LearningApp/LearningApp/InboxTableViewController.swift). # Analytics Track user engagement and behavior in your mobile app with the analytics features of the SDK. ## Getting Started Configure analytics in your app to track push notifications, inbox messages, and Einstein Recommendations events. For Android apps, see [Enable and Use Analytics on Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_analytics_android_implement.md). For iOS apps, see [Enable and Use Analytics on iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_analytics_ios_implement.md). ## Einstein Recommendations Integration Integrate with Einstein Recommendations to attribute analytics to specific users and track commerce activities. For iOS apps, see [Integrate Einstein Recommendations and Collect API on iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_analytics_ios_recommendations_integrate.md) For Android apps, see [Integrate Einstein Recommendations and Collect API on Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_analytics_android_recommendations_integrate.md) ## Additional Analytics Integration Use Google Analytics 4 to obtain metrics for your MobilePush apps by logging campaign details from push notification payloads. See [Send Custom Campaign Details to Google Analytics 4](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_analytics_ga4_send.md). # Analytics The SDK tracks user interactions with your app and collects analytics data automatically. Enable analytics to measure engagement with push notifications, in-app messages, and other messaging campaigns. Analytics run in the background and capture events when users interact with SDK features. The data helps you understand campaign performance and user behavior. ## Enable Analytics Enable analytics for your mobile app based on your platform: - [Enable and Use Analytics on Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_analytics_android.md) - [Enable and Use Analytics on iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_analytics_ios.md) ## What Analytics Track When you enable analytics, the SDK automatically collects information about these events: - Push notification opens and dismissals - In-app message impressions and interactions - App launches and sessions - Custom events you define The SDK sends this data to Marketing Cloud Next. You can view the data in reports and use it to measure the effectiveness of your campaigns. # Analytics in Android Apps that Use SDK Version 10 The processes for enabling and using analytics features have been updated in version 10 of the SDK. To upgrade your app to version 10 of the SDK, first [update the initialization code](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v10.md). Then, use these code examples to update the analytics code in your app. ## Enable Analytics Use this code example to enable analytics during SDK initialization. ```kotlin SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { engagementModuleConfig = MarketingCloudConfig.builder().apply { // Other configuration values setAnalyticsEnabled(true) // Enable ET Analytics, default = false setPiAnalyticsEnabled(true) // Enable Predictive Intelligence Analytics, default = false /* To explicitly control PI analytic attribution setUseLegacyPiIdentifier to false and set a value for the Predictive Intelligence Identifier in the SDK’s AnalyticsManager. */ setUseLegacyPiIdentifier(false) }.build(applicationContext) }) { // TODO handle initialization status } ``` ## Analytics Attribution Use this code example to set the Predictive Intelligence Identifier in the SDK’s AnalyticsManager. ```kotlin MarketingCloudSdk.requestSdk { engagementSdk -> val analyticsManager = engagementSdk.analyticsManager // Set the PI ID analyticsManager.piIdentifier = "developer@salesforce.com" // Clear the PI ID analyticsManager.piIdentifier = null } ``` ## Track Cart Contents Use this code example to track the contents of an in-app shopping cart. ```kotlin MarketingCloudSdk.requestSdk { engagementSdk -> val analyticsManager = engagementSdk.analyticsManager val cartItem = PiCartItem("Burger", 2, 2.99, "burger_123") val cart = PiCart(listOf(cartItem)) analyticsManager.trackCartContents(cart) } ``` ## Track Cart Conversion Use this code example to track the conversion of an in-app shopping cart. ```kotlin MarketingCloudSdk.requestSdk { engagementSdk -> val analyticsManager = engagementSdk.analyticsManager val cartItem = PiCartItem("Burger", 2, 2.99, "burger_123") val cart = PiCart(listOf(cartItem)) val order = PiOrder(cart, "ABC1234", 4.99, .2) analyticsManager.trackCartConversion(order) } ``` ## Track Page Views Use this code example to track the page views in your app. ```kotlin MarketingCloudSdk.requestSdk { engagementSdk -> val analyticsManager = engagementSdk.analyticsManager // trackPageView() requires a String representing the in-app URL to be tracked. // Additional overloaded methods are available. See the Javadoc for details. analyticsManager.trackPageView("url") analyticsManager.trackPageView("url", "title") analyticsManager.trackPageView("url", "title", "item") analyticsManager.trackPageView("url", "title", "item", "searchTerms") } ``` ## Track Inbox Message Opens Use this code example to track the opens of an inbox message. ```kotlin MarketingCloudSdk.requestSdk { engagementSdk -> val analyticsManager = engagementSdk.analyticsManager analyticsManager.trackInboxOpenEvent(message as InboxMessage) } ``` # Analytics in iOS Apps that Use SDK Version 10 The processes for enabling and using analytics features have been updated in version 10 of the SDK. To upgrade your app to version 10 of the SDK, first [update the initialization code](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v10.md). Then, use these code examples to update the analytics code in your app. ## Enable Analytics During SDK Initialization Use this code example to enable analytics during SDK initialization. ```swift // The method is called on the delegate when the user responds to the // notification by opening the app, dismissing the notification, or choosing a // UNNotificationAction. Set the delegate before the app returns from // applicationDidFinishLaunching:. func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void ) { // tell the SDK about the notification PushFeature.requestSdk { pushFeature in pushFeature?.setNotificationResponse(response) } completionHandler() } ``` ## Analytics Attribution Use this code example to set the Predictive Intelligence Identifier in the SDK’s AnalyticsManager. ```swift MarketingCloudSdk.requestSdk { mc in // Example: Setting and clearing pi identifier. // Setting the pi identifier mc?.setPiIdentifier("example@email.com") // Clearing the pi identifier mc?.setPiIdentifier(nil) } ``` ## Track Cart Contents Use this code example to track the contents of an in-app shopping cart. ```swift MarketingCloudSdk.requestSdk { mc in let cartItem = mc?.cartItemDictionary( price: 1.10, quantity: 1, item: "123456", uniqueId: "uniqueId_123456" ) let cart = mc?.cartDictionary(cartItem: [cartItem]) mc?.trackCartContents(cart!) } ``` ## Track Cart Conversion Use this code example to track the conversion of an in-app shopping cart. ```swift MarketingCloudSdk.requestSdk { mc in let cartItem = mc?.cartItemDictionary( price: 1.10, quantity: 1, item: "123456", uniqueId: "uniqueId_123456" ) let cart = mc?.cartDictionary(cartItem: [cartItem]) let order = mc?.orderDictionary( orderNumber: "123456", shipping: 2.11, discount: 4.99, cart: cart! ) mc?.trackCartConversion(order!) } ``` ## Track Page Views Use this code example to track the page views in your app. ```swift MarketingCloudSdk.requestSdk { mc in mc?.trackPageView( url: "http://my.example.com", title: "page title", item: "item name", search: "search term" ) } ``` ## Track Inbox Message Opens Use this code example to track the opens of an inbox message. ```swift func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let inboxMessage = dataSourceArray[indexPath.row] MarketingCloudSdk.requestSdk { mc in mc?.trackMessageOpened(inboxMessage) } // Your selection handling } ``` # AnalyticsManager **Package:** `com.salesforce.marketingcloud.analytics` **Type:** `interface` **SDK Version:** 11.0.0 ## Overview Public facing interface for interacting with the Marketing Cloud SDK's analytics features. ## Methods ### areAnalyticsEnabled ```kotlin abstract fun areAnalyticsEnabled(): Boolean ``` Indicates whether the ET analytics are enabled or disabled. **Returns:** `Boolean` --- ### arePiAnalyticsEnabled ```kotlin abstract fun arePiAnalyticsEnabled(): Boolean ``` Indicates whether the Pi analytics are enabled or disabled. **Returns:** `Boolean` --- ### disableAnalytics ```kotlin abstract fun disableAnalytics() ``` This method allows you to disable the collection of ET Analytics through the SDK. --- ### disablePiAnalytics ```kotlin abstract fun disablePiAnalytics() ``` This method allows you to disable the collection of Pi Analytics through the SDK. --- ### enableAnalytics ```kotlin abstract fun enableAnalytics() ``` This method allows you to activate the collection of ET Analytics through the SDK. --- ### enablePiAnalytics ```kotlin abstract fun enablePiAnalytics() ``` This method allows you to activate the collection of Pi Analytics through the SDK. --- ### getPiIdentifier ```kotlin @Nullable abstract fun getPiIdentifier(): String ``` Returns the value set by `setPiIdentifier`. **Returns:** `String` (nullable) --- ### setPiIdentifier ```kotlin abstract fun setPiIdentifier( @Nullable @Size(min = 1) piIdentifier: String ) ``` Set the Predictive Intelligence Identifier to be associated with your Predictive Intelligence analytics. **Parameters:** - `piIdentifier`: `String` (nullable, minimum size = 1) --- ### trackCartContents ```kotlin abstract fun trackCartContents(@NonNull cart: PiCart) ``` PI Analytics Convenience method to track a shopping cart. **Parameters:** - `cart`: `PiCart` (non-null) --- ### trackCartConversion ```kotlin abstract fun trackCartConversion(@NonNull order: PiOrder) ``` PI Analytics Convenience method to track a purchase. **Parameters:** - `order`: `PiOrder` (non-null) --- ### trackInboxOpenEvent ```kotlin abstract fun trackInboxOpenEvent(@NonNull message: InboxMessage) ``` Track the opening of an `InboxMessage` in ETAnalytics. **Parameters:** - `message`: `InboxMessage` (non-null) --- ### trackPageView ```kotlin abstract fun trackPageView(@NonNull @Size(min = 1) url: String) abstract fun trackPageView( @NonNull @Size(min = 1) url: String, @Nullable title: String ) abstract fun trackPageView( @NonNull @Size(min = 1) url: String, @Nullable title: String, @Nullable item: String ) abstract fun trackPageView( @NonNull @Size(min = 1) url: String, @Nullable title: String, @Nullable item: String, @Nullable searchTerms: String ) ``` Track page views within your application **Parameters:** - `url`: `String` (non-null, minimum size = 1) - Required page URL - `title`: `String` (nullable) - Optional page title - `item`: `String` (nullable) - Optional item identifier - `searchTerms`: `String` (nullable) - Optional search terms # AnalyticsManager **Package:** `com.salesforce.marketingcloud.mobileappmessaging.analytics` **SDK Version:** Mobile App Messaging SDK v1.1.0 (Salesforce Marketing Cloud Unified SDK 11.0.0) **Platform:** androidJvm ## Overview ```kotlin interface AnalyticsManager ``` Public interface for interacting with the MobileAppMessaging Analytics features. Provides status checking and configuration-based analytics control following SDK patterns. > **Note:** Analytics state is controlled by the `analyticsEnabled` configuration parameter and cannot be changed at runtime. The enable/disable methods are provided for API compatibility but will only log warnings about the current configuration state. ## Functions ### areAnalyticsEnabled ```kotlin abstract fun areAnalyticsEnabled(): Boolean ``` Indicates whether the MobileAppMessaging analytics are enabled or disabled. **Returns:** `Boolean` - The current analytics state **Note:** The state is determined by the `analyticsEnabled` configuration parameter. --- ### disableAnalytics ```kotlin abstract fun disableAnalytics() ``` Disable analytics collection. **Note:** Analytics state is controlled by configuration and cannot be changed at runtime. This method logs a warning about the current configuration state. --- ### enableAnalytics ```kotlin abstract fun enableAnalytics() ``` Enable analytics collection. **Note:** Analytics state is controlled by configuration and cannot be changed at runtime. This method logs a warning about the current configuration state. # Android SDK v11 Reference ## Modules - [SFMC SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmc-sdk/sfmc-sdk_android_index.md) - [Marketing Cloud SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/marketing-cloud-sdk/marketing-cloud-sdk_index.md) - [Push Feature Module](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/push-feature-module/push-feature-module_index.md) - [Push Models Module](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/push-models-module/push-models-module_index.md) - [Common](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/common/common_common_index.md) - [In App Messaging Feature Module](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/in-app-messaging-feature-module/in-app-messaging-feature-module_index.md) - [In App Messaging Models Module](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/in-app-messaging-models-module/in-app-messaging-models-module_index.md) - [Mobile App Messaging SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/mobile-app-messaging-sdk/mobile-app-messaging-sdk_index.md) # Apple Privacy Manifest A privacy manifest is a file that details the privacy practices of an app or its third-party SDKs. In iOS version 17 and later, Apple requires SDKs to provide a privacy manifest. Your app must include this information in its privacy manifest: - The types of data your app collects. Apple provides a list of data categories. - The reasons for collecting the data. - The privacy manifest for all third-party SDKs that the app uses. ## Required Reason API Usage Apple provides a list of the [required reason APIs](https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_use_of_required_reason_api) for data usage. Apple requires the Salesforce Engagement SDK to declare the APIs it uses so that a developer can verify that the APIs are being used for the expected reasons. The privacy manifest for version 8.1.2 and later of the Engagement SDK uses the `NSPrivacyAccessedAPICategoryUserDefaults` Required Reason API to persist SDK settings related to data migration, SDK privacy mode, and API sync retry timestamp. ## Collected Data Type Declaration Apple requires that third-party SDKs, including the Engagement SDK, to declare the types of [data collected](https://developer.apple.com/documentation/bundleresources/describing-data-use-in-privacy-manifests) in privacy manifest files. Version 9.0.0 and later of the SDK use the `NSPrivacyCollectedDataTypePurposeAnalytics` Collected Data Type, which is declared in the SDK’s privacy manifest. The SDK uses `NSPrivacyCollectedDataTypePurposeAnalytics` to gather data that helps understand the effectiveness of existing features, plan new features, or measure audience size and characteristics. Data isn't linked to users or used for tracking. # Apple Push Notification Service Server Configuration To ensure the proper configuration of your Apple Push Notification Service (APNs) connection and delivery of push notifications for different types of app builds (development or production), keep these points in mind. - APNs Server Selection: If you select the **Development** option, Marketing Cloud Engagement attempts to contact the Sandbox APNs server, regardless of whether you use a `.p8` key or a `.p12` certificate. If you select the **Production** option, Marketing Cloud Engagement attempts to contact the Production APNs server. - Apps Built Using Development Certificates: To send notifications only to those devices with apps on `Debug` configuration, select **Development** on the MobilePush Administration page in Marketing Cloud Engagement. ![The MobilePush Administration page in Marketing Cloud Engagement, showing the Development option selected for APNs.](https://developer.salesforce.com/media/quickstart/Provision-For-Push-iOS-p12-Development-Cert.png '{"class": "image-lg"}') - Apps Built Using Production or Distribution Certificates: To send notifications only to those devices with apps on `Release` configuration, select **Production** on the MobilePush Administration page in Marketing Cloud Engagement. ![The MobilePush Administration page in Marketing Cloud Engagement, showing the Production option selected for APNs.](https://developer.salesforce.com/media/quickstart/Provision-For-Push-iOS-p12-Production-Cert.png '{"class": "image-lg"}') # AttributesEditor **Package:** `com.salesforce.marketingcloud.sfmcsdk.components.identity` **Platform:** androidJvm ## Overview The `AttributesEditor` class wraps the `Identity.Builder` attribute map functions to provide an idiomatic Kotlin syntax for managing user attributes in the Salesforce Marketing Cloud SDK. ## Usage Example ```kotlin SFMCSdk.requestSdk { sdk -> sdk.identity.edit { attributes["key"] = "value" // assignment syntax attributes += "key2" to "value2" // plus assignment syntax } } ``` ## Constructor ### AttributesEditor ```kotlin constructor(builder: Identity.Builder) ``` Creates an instance that wraps an `Identity.Builder` for attribute operations. **Parameters:** - `builder` - The Identity.Builder instance to wrap ## Methods ### clear ```kotlin fun clear(vararg keys: String) ``` Clears the value of the specified attributes, effectively setting them to null. **Parameters:** - `keys` - Variable number of attribute keys to clear --- ```kotlin fun clear(keys: List) ``` Clears the value of the specified attributes, effectively setting them to null. **Parameters:** - `keys` - List of attribute keys to clear --- ```kotlin fun clear(key: String) ``` Clears the value of the specified attribute, effectively setting it to null. **Parameters:** - `key` - The attribute key to clear ### clearAll ```kotlin fun clearAll() ``` Clears the value of all attributes, effectively setting them to null. ### plusAssign ```kotlin operator fun plusAssign(entry: Pair) ``` Updates or adds the value of an entry for the given key in the attribute map using the `+=` operator. **Parameters:** - `entry` - A Pair containing the key and nullable value to add/update ### put ```kotlin fun put(key: String, value: String?) ``` Updates or adds the value of an entry for the given key in the attribute map. **Parameters:** - `key` - The attribute key - `value` - The nullable attribute value ### putAll ```kotlin fun putAll(from: Map) ``` Updates or adds all the values from the passed in map. **Parameters:** - `from` - Map of attributes to add/update ### set ```kotlin fun set(from: Map) ``` First clears the values of all existing attributes. Then updates or adds the values from the passed in map. **Note:** Attribute keys cannot be removed, only the value can be cleared or set to null. **Parameters:** - `from` - Map of attributes to set --- ```kotlin operator fun set(key: String, value: String?) ``` Updates or adds the value of an entry for the given key in the attribute map using array-style indexing syntax. **Parameters:** - `key` - The attribute key - `value` - The nullable attribute value # BadMediaException ## Package `com.salesforce.marketingcloud.pushmodels.exceptions` ## Module Push Models Module v1.0.2 ## Platform androidJvm ## Inheritance Hierarchy ```kotlin PushException └── BadMediaException ``` ## Description This exception class is thrown when a media resource at a specified URL cannot be loaded. ## Class Declaration ```kotlin class BadMediaException(url: String) : PushException ``` ## Constructors ### BadMediaException ```kotlin constructor(url: String) ``` Creates a new `BadMediaException` instance. **Parameters:** - `url` (String) - The URL of the media resource that failed to load ## Members This class inherits members from `PushException` but does not define additional public methods or properties beyond the constructor. # Basic Push Notification Customization for Android The `NotificationCustomizationOptions` class facilitates push notification customization through a [`NotificationChannelIdProvider`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.notifications/-notification-manager/-notification-channel-id-provider/index.html), enabling the assignment of a specific [Notification Channel](https://developer.android.com/develop/ui/views/notifications/channels) for each `NotificationMessage`. Additionally, [NotificationLaunchIntentProvider](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.notifications/-notification-manager/-notification-launch-intent-provider/index.html) defines the action to take when a user taps a [NotificationMessage](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushmodelsmodule/com.salesforce.marketingcloud.pushmodels/-notification-message/index.html), alongside your application’s notification icon. **note:** When you target apps that run Android 12 or later, specify the mutability of your Pending Intent. See _Android Developer Documentation_: [Intents and Intent Filters](https://developer.android.com/guide/components/intents-filters#DeclareMutabilityPendingIntent). ```java SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { this.pushFeatureModuleConfig = PushFeatureConfig.builder().apply { // Other configuration values setNotificationCustomizationOptions( NotificationCustomizationOptions.create(R.drawable.ic_notification_icon, NotificationManager.NotificationLaunchIntentProvider { context, notificationMessage -> val requestCode = Random().nextInt() val url = notificationMessage.url when { url.isNullOrEmpty() -> PendingIntent.getActivity( context, requestCode, Intent(context, MainActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) else -> PendingIntent.getActivity( context, requestCode, Intent(Intent.ACTION_VIEW, url.toUri()), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) } }, NotificationManager.NotificationChannelIdProvider { context, notificationMessage -> if (TextUtils.isEmpty(notificationMessage.url)) { NotificationManager.createDefaultNotificationChannel(context) } else { "UrlNotification" } } ) ) }.build() }) { // Handle initialization status } ``` ### Icons The Mobile App Messaging SDK supports icons in various notification elements, including small icons in the status bar and notification header, large icons in the notification body, and rich button icons. You can use icons by placing icon files in the PNG format inside `drawables-**hdpi` folders within your client app’s resources. The SDK then references these icons by their resource names (for example, `ic_notification_icon`). For example, to use an icon named `ic_notification_icon.png`, place it in the appropriate `drawables-**hdpi` folder. Then, provide `ic_notification_icon` as the resource name. If it’s a small icon, you can also specify the resource ID in `NotificationCustomizationOptions` when using `MarketingCloudConfigBuilder`. ### Sound You can customize notification channels by setting priorities, colors, and sounds. To use a custom sound in notifications, follow these steps: 1. Add the sound file to the app’s `res/raw/` folder. 2. Create a notification channel for the audio file and configure it in the code using `NotificationChannelIdProvider`. This code example creates a notification channel named `myaudio`, enables badges and lights, and sets a default importance level. ```java /* Create a notification channel for the audio file */ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { androidNotificationManager.createNotificationChannel( NotificationChannel( "myaudio", "myaudio", AndroidNotificationManager.IMPORTANCE_DEFAULT ).apply { setShowBadge(true) enableLights(true) setSound( Uri.parse( "android.resource://${context.packageName}/${context.resources.getIdentifier("custom","raw", context.packageName)}" ), AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_NOTIFICATION_EVENT).build() ) } ) } ``` This sample code configures the Mobile App Messaging SDK for an Android application. It sets up notification customization options, including the small icon, launch intent, and notification channel ID. ```java SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { this.pushFeatureModuleConfig = PushFeatureConfig.builder().apply { // Other configuration values setNotificationCustomizationOptions( NotificationCustomizationOptions.create(R.drawable.ic_notification_icon, NotificationManager.NotificationLaunchIntentProvider { context, notificationMessage -> val requestCode = Random().nextInt() val url = notificationMessage.url when { url.isNullOrEmpty() -> PendingIntent.getActivity( context, requestCode, Intent(context, MainActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) else -> PendingIntent.getActivity( context, requestCode, Intent(Intent.ACTION_VIEW, url.toUri()), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) } }, NotificationManager.NotificationChannelIdProvider { context, notificationMessage -> if (TextUtils.isEmpty(notificationMessage.url)) { NotificationManager.createDefaultNotificationChannel(context) } else if(notificationMessage.sound == NotificationMessage.Sound.CUSTOM) { "CustomSoundNotification" } else { "UrlNotification" } } ) ) }.build() }) { // Handle initialization status } ``` # Beacon Messaging in Android Apps that Use SDK Version 10 The implementation for beacon messaging has been updated in version 10 of the SDK. To upgrade your app to version 10 of the SDK, first [update the initialization code](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v10.md). Then, use this code example to update the beacon messaging code in your app. ## Enable Beacon Messaging During SDK Initialization Use this code example to enable beacon messaging during SDK initialization. ```kotlin SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { engagementModuleConfig = MarketingCloudConfig.builder().apply { // Other configuration values setProximityNotificationOptions( ProximityNotificationCustomizationOptions.create( R.mipmap.ic_notification_foreground ) ) // required config to show foreground notification setProximityEnabled(true) // Enable Beacon messaging, default = false }.build(applicationContext) }) { // TODO handle initialization status } ``` ## Toggle Beacon Messaging at Runtime Use this code example to toggle beacon messaging at runtime. ```kotlin MarketingCloudSdk.requestSdk { //enable it.regionMessageManager.enableProximityMessaging() //disable it.regionMessageManager.disableProximityMessaging() } ``` # BeaconLogger **Package:** `com.salesforce.marketingcloud.proximity` **SDK Version:** 11.0.0 **Platform:** Android JVM ## Overview `BeaconLogger` is a class that extends the `Logger` interface, providing logging functionality for beacon-related operations in the Salesforce Marketing Cloud SDK. ## Class Declaration ```kotlin class BeaconLogger : Logger ``` ## Constructors ### BeaconLogger() ```kotlin constructor() ``` Default constructor for creating a BeaconLogger instance. ## Methods ### Debug Logging #### d(tag, message, objects) ```kotlin open fun d( tag: String, message: String, objects: Array ) ``` Logs a debug message with the specified tag and message format. **Parameters:** - `tag`: String - The tag for the log entry - `message`: String - The message to log - `objects`: Array - Variable arguments for message formatting #### d(throwable, tag, message, objects) ```kotlin open fun d( throwable: Throwable, tag: String, message: String, objects: Array ) ``` Logs a debug message with an associated throwable. **Parameters:** - `throwable`: Throwable - The exception or error to log - `tag`: String - The tag for the log entry - `message`: String - The message to log - `objects`: Array - Variable arguments for message formatting ### Error Logging #### e(tag, message, objects) ```kotlin open fun e( tag: String, message: String, objects: Array ) ``` Logs an error message. **Parameters:** - `tag`: String - The tag for the log entry - `message`: String - The error message - `objects`: Array - Variable arguments for message formatting #### e(throwable, tag, message, objects) ```kotlin open fun e( throwable: Throwable, tag: String, message: String, objects: Array ) ``` Logs an error message with an associated throwable. **Parameters:** - `throwable`: Throwable - The exception or error - `tag`: String - The tag for the log entry - `message`: String - The error message - `objects`: Array - Variable arguments for message formatting ### Info Logging #### i(tag, message, objects) ```kotlin open fun i( tag: String, message: String, objects: Array ) ``` Logs an informational message. **Parameters:** - `tag`: String - The tag for the log entry - `message`: String - The info message - `objects`: Array - Variable arguments for message formatting #### i(throwable, tag, message, objects) ```kotlin open fun i( throwable: Throwable, tag: String, message: String, objects: Array ) ``` Logs an informational message with an associated throwable. **Parameters:** - `throwable`: Throwable - The exception or error - `tag`: String - The tag for the log entry - `message`: String - The info message - `objects`: Array - Variable arguments for message formatting ### Verbose Logging #### v(tag, message, objects) ```kotlin open fun v( tag: String, message: String, objects: Array ) ``` Logs a verbose message. **Parameters:** - `tag`: String - The tag for the log entry - `message`: String - The verbose message - `objects`: Array - Variable arguments for message formatting #### v(throwable, tag, message, objects) ```kotlin open fun v( throwable: Throwable, tag: String, message: String, objects: Array ) ``` Logs a verbose message with an associated throwable. **Parameters:** - `throwable`: Throwable - The exception or error - `tag`: String - The tag for the log entry - `message`: String - The verbose message - `objects`: Array - Variable arguments for message formatting ### Warning Logging #### w(tag, message, objects) ```kotlin open fun w( tag: String, message: String, objects: Array ) ``` Logs a warning message. **Parameters:** - `tag`: String - The tag for the log entry - `message`: String - The warning message - `objects`: Array - Variable arguments for message formatting #### w(throwable, tag, message, objects) ```kotlin open fun w( throwable: Throwable, tag: String, message: String, objects: Array ) ``` Logs a warning message with an associated throwable. **Parameters:** - `throwable`: Throwable - The exception or error - `tag`: String - The tag for the log entry - `message`: String - The warning message - `objects`: Array - Variable arguments for message formatting # BeaconRegion **Package:** `com.salesforce.marketingcloud.proximity` **Full Class Name:** `com.salesforce.marketingcloud.proximity.BeaconRegion` ## Description A data class representing a beacon region in the Salesforce Marketing Cloud SDK. This class implements `Parcelable` for Android parcelization support. ## Inheritance - Implements: `android.os.Parcelable` ## Class Declaration ```kotlin data class BeaconRegion : Parcelable ``` ## Properties ### guid ```kotlin val guid: String ``` A unique identifier for the beacon region. ### id ```kotlin val id: String ``` The identifier of the beacon region. ### major ```kotlin val major: Int ``` The major value of the beacon region. ### minor ```kotlin val minor: Int ``` The minor value of the beacon region. ## Notes - This is a data class, which automatically provides `equals()`, `hashCode()`, `toString()`, and `copy()` methods - Available in Marketing Cloud SDK version 11.0.0.0 - Part of the proximity messaging functionality - Target platform: androidJvm # CancelOrderEvent ## Package `com.salesforce.marketingcloud.sfmcsdk.components.events` ## Description A class representing an e-commerce event triggered when a user cancels an order. ## Inheritance ```kotlin class CancelOrderEvent : OrderEvent ``` This class extends `OrderEvent` to provide specialized functionality for order cancellation tracking. ## Platform - **Target:** androidJvm ## SDK Information Part of the Salesforce Marketing Cloud Unified SDK (SFMC SDK v3.1.0) ## Overview `CancelOrderEvent` is used to track and record when users cancel their orders within an e-commerce application. This event type inherits from the base `OrderEvent` class and is part of the Marketing Cloud's event tracking system for monitoring user interactions and purchase behavior. ## Navigation - **Parent Module:** Salesforce Marketing Cloud Unified SDK - **Package:** com.salesforce.marketingcloud.sfmcsdk.components.events - **Parent Class:** OrderEvent # CarouselFullTemplate ## Package `com.salesforce.marketingcloud.pushmodels.rich.carousel` ## Description `CarouselFullTemplate` is a data class that extends `Template` and is used to display a list of items in a carousel format for push notifications. ## Class Declaration ```kotlin data class CarouselFullTemplate( val items: List, val selectedIndex: Int = DEFAULT_SELECTED_INDEX, val style: Style? = null ) : Template ``` ## Constructors ### Primary Constructor ```kotlin CarouselFullTemplate( items: List, selectedIndex: Int = DEFAULT_SELECTED_INDEX, style: Style? = null ) ``` **Parameters:** - **items**: `List` - The list of carousel items to display - **selectedIndex**: `Int` - The initially selected item index (defaults to `DEFAULT_SELECTED_INDEX`) - **style**: `Style?` - Optional styling configuration for the carousel (nullable, defaults to null) ## Properties | Property | Type | Override | Description | | --------------- | ----------------------------------------- | -------- | ------------------------------------------------------- | | `identifier` | `String?` | Yes | Optional identifier for the template (defaults to null) | | `items` | `List` | No | The list of items in the carousel | | `selectedIndex` | `Int` | No | The index of the currently selected item | | `style` | `Style?` | Yes | Optional style configuration | | `type` | `Template.Type` | Yes | The template type identifier | ## Methods ### toString() ```kotlin open override fun toString(): String ``` Returns a string representation of the CarouselFullTemplate object. ## Nested Types ### CarouselItem ```kotlin data class CarouselItem( val identifier: String, val media: Media, val title: Text? = null, val subTitle: Text? = null, val style: Style? = null, val actions: List? = listOf(Action.OpenApp) ) : Parcelable, PushView ``` A data class representing a single item in the carousel. **Constructor Parameters:** - **identifier**: `String` - Unique identifier for the carousel item - **media**: `Media` - Media content to display in the item - **title**: `Text?` - Optional title text (nullable, defaults to null) - **subTitle**: `Text?` - Optional subtitle text (nullable, defaults to null) - **style**: `Style?` - Optional styling for the item (nullable, defaults to null) - **actions**: `List?` - Optional list of actions (nullable, defaults to `listOf(Action.OpenApp)`) **Interfaces:** - `Parcelable` - Implements Android serialization - `PushView` - Implements push notification rendering ## Module Information - **Module**: Push Models Module v1.0.2 - **SDK**: Salesforce Marketing Cloud Unified SDK 11.0.0 - **Target**: androidJvm # CarouselItem ## Package `com.salesforce.marketingcloud.pushmodels.rich.carousel` ## Class Declaration ```kotlin data class CarouselItem( val identifier: String, val media: Media, val title: Text? = null, val subTitle: Text? = null, val style: Style? = null, val actions: List? = listOf(Action.OpenApp) ) : Parcelable, PushView ``` ## Description A data class representing an individual item within a carousel template for Salesforce Marketing Cloud push notifications. This class implements both `Parcelable` for Android serialization and `PushView` interface. ## Inheritance - `android.os.Parcelable` - `com.salesforce.marketingcloud.pushmodels.data.PushView` ## Constructors ### Primary Constructor ```kotlin constructor( identifier: String, media: Media, title: Text? = null, subTitle: Text? = null, style: Style? = null, actions: List? = listOf(Action.OpenApp) ) ``` ## Properties ### identifier ```kotlin val identifier: String ``` Unique identifier for the carousel item. ### media ```kotlin val media: Media ``` Media content associated with this carousel item. ### title ```kotlin val title: Text? ``` Optional title text for the carousel item. Default is `null`. ### subTitle ```kotlin val subTitle: Text? ``` Optional subtitle text for the carousel item. Default is `null`. ### style ```kotlin open override val style: Style? ``` Optional styling configuration for the carousel item. Default is `null`. Overrides the `style` property from `PushView`. ### actions ```kotlin open override val actions: List? ``` Optional list of actions for the carousel item. Defaults to `listOf(Action.OpenApp)`. Overrides the `actions` property from `PushView`. ## Methods ### toJson ```kotlin fun toJson(): JSONObject ``` Converts the carousel item to a JSON object representation. **Returns:** `JSONObject` - JSON representation of the carousel item. ### toString ```kotlin open override fun toString(): String ``` Returns a string representation of the carousel item. **Returns:** `String` - String representation of the object. # CartEvent **Package:** `com.salesforce.marketingcloud.sfmcsdk.components.events` **SDK Version:** 11.0.0 **Platform:** androidJvm ## Overview `CartEvent` is a sealed class representing cart-related events in the Salesforce Marketing Cloud SDK. It inherits from `EngagementEvent` and serves as the base class for various cart operations. ## Declaration ```kotlin sealed class CartEvent : EngagementEvent ``` ## Inheritance Hierarchy ``` EngagementEvent ↳ CartEvent ``` ## Inheritors The following classes inherit from `CartEvent`: - [AddToCartEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_AddToCartEvent.md) - Represents an event when items are added to the cart - [RemoveFromCartEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_RemoveFromCartEvent.md) - Represents an event when items are removed from the cart - [ReplaceCartEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_ReplaceCartEvent.md) - Represents an event when the cart contents are replaced ## Properties ### lineItems ```kotlin val lineItems: List ``` A list of line items associated with the cart event. **Type:** `List` **Access:** Read-only (val) ## Nested Types ### Companion ```kotlin object Companion ``` A companion object for the `CartEvent` class. # CatalogEvent **Package:** `com.salesforce.marketingcloud.sfmcsdk.components.events` **SDK Version:** 11.0.0 **Platform:** androidJvm --- ## Overview A sealed class representing catalog-related engagement events in the Salesforce Marketing Cloud Unified SDK. This class is used to track user interactions with catalog objects such as products or blog posts. ## Declaration ```kotlin sealed class CatalogEvent : EngagementEvent ``` ## Hierarchy - **Extends:** `EngagementEvent` --- ## Properties ### catalogObject ```kotlin val catalogObject: CatalogObject ``` The catalog object associated with this event. --- ## Inheritors The following classes inherit from `CatalogEvent`: - **`ViewCatalogEvent`** - Records when a user examines a catalog object - **`ViewCatalogDetailEvent`** - Records when a user views detailed information about a catalog object - **`QuickViewCatalogEvent`** - Records when a user performs a quick view of a catalog object - **`ShareCatalogEvent`** - Records when a user shares a catalog object - **`ReviewCatalogEvent`** - Records when a user reviews a catalog object - **`CommentCatalogEvent`** - Records when a user comments on a catalog object - **`FavoriteCatalogEvent`** - Records when a user favorites a catalog object --- ## Companion Object ```kotlin object Companion ``` A companion object for the `CatalogEvent` class. --- ## Related Classes ### CatalogObject **Package:** `com.salesforce.marketingcloud.sfmcsdk.components.events` A catalog object that represents various items that can be tracked, such as products or blog posts. #### Constructor ```kotlin @JvmOverloads constructor( type: String, id: String, attributes: Map = mapOf(), relatedCatalogObjects: Map> = mapOf() ) ``` ##### Parameters | Parameter | Type | Description | Default | | ----------------------- | --------------------------- | ------------------------------------------- | --------- | | `type` | `String` | A type name representing the catalog object | Required | | `id` | `String` | A unique id representing the catalog object | Required | | `attributes` | `Map` | A map of user-supplied values | `mapOf()` | | `relatedCatalogObjects` | `Map>` | A map of related catalog objects | `mapOf()` | #### Properties ##### attributes ```kotlin val attributes: Map ``` A map of user-supplied values. ##### id ```kotlin val id: String ``` A unique id representing the catalog object. ##### relatedCatalogObjects ```kotlin val relatedCatalogObjects: Map> ``` A map of related catalog objects. ##### type ```kotlin val type: String ``` A type name representing the catalog object. --- ## Usage Example ```kotlin // Create a catalog object val catalogObject = CatalogObject( type = "product", id = "12345", attributes = mapOf( "name" to "Example Product", "price" to 99.99, "category" to "Electronics" ), relatedCatalogObjects = mapOf( "similar" to listOf("12346", "12347") ) ) // Create a view catalog event val viewEvent = ViewCatalogEvent(catalogObject) ``` # CatalogObject **Package:** `com.salesforce.marketingcloud.sfmcsdk.components.events` **Salesforce Marketing Cloud Unified SDK** - Version 11.0.0 ## Description A catalog object representing various trackable items such as products or blog posts. ## Class Declaration ```kotlin class CatalogObject @JvmOverloads constructor( val type: String, val id: String, val attributes: Map = mapOf(), val relatedCatalogObjects: Map> = mapOf() ) ``` ## Constructor ### CatalogObject ```kotlin @JvmOverloads constructor( type: String, id: String, attributes: Map = mapOf(), relatedCatalogObjects: Map> = mapOf() ) ``` **Parameters:** - `type` - A type name representing the catalog object - `id` - A unique identifier for the catalog object - `attributes` - A map of user-supplied values (default: empty map) - `relatedCatalogObjects` - A map of related catalog objects (default: empty map) ## Properties ### type ```kotlin val type: String ``` A type name representing the catalog object. ### id ```kotlin val id: String ``` A unique id representing the catalog object. ### attributes ```kotlin val attributes: Map ``` A map of user-supplied values. ### relatedCatalogObjects ```kotlin val relatedCatalogObjects: Map> ``` A map of related catalog objects. ## Platform - **Target:** androidJvm # CDP `Class` ## Declaration ```swift @objc(SFMCSdkCDP) public final class CDP : NSObject, CdpInterface, SFMCModuleApi @objc public func getStatus() -> ModuleStatus public func getIdentity() -> ModuleIdentity? public func getConsent() -> Consent public func setConsent(consent: Consent) public func setLocation(coordinates: Coordinates?, expiresIn: Int) ``` ## Cases ### `getStatus()` ```swift @objc public func getStatus() -> ModuleStatus ``` --- ### `getIdentity()` ```swift public func getIdentity() -> ModuleIdentity? ``` --- ### `getConsent()` ```swift public func getConsent() -> Consent ``` --- ### `setConsent(consent:)` ```swift public func setConsent(consent: Consent) ``` --- ### `setLocation(coordinates:expiresIn:)` ```swift public func setLocation(coordinates: Coordinates?, expiresIn: Int) ``` --- # Change Log This changelog contains information about these Engagement SDK products: - [SDK for Android](#android) - [SDK for iOS](#ios) - [Cordova Plugin](#cordova) - [Flutter Plugin](#flutter) - [React Plugin](#react) Change history for previous major releases of each product is combined in a collapsible section. For example, to view the history for version 9 of the Android SDK, click **Version 9 Releases** in the SDK for Android section to expand the list of changes. ## Android This section contains information about releases of the MobilePush SDK for Android, including version numbers, release dates, compatibility details, and key changes. ### Latest Release - Version 11.0.1 _Released June 10, 2026_ Version 11.0.1 of the Android SDK has been tested with Firebase Cloud Messaging version 25.0.1, Google Play Location Services version 21.3.0, and AltBeacon Library version 2.20.7. The minimum compatible Android API version is 26. The SDK is compiled with Android API version 36 and depends on Java version 17 and Kotlin version 2.2.21. - Performance improvements and bug fixes. - Hardening against an ART verifier exception (VerifyError) that could crash apps running JaCoCo-instrumented builds. See [Google Issue Tracker](https://issuetracker.google.com/issues/247932119) and [Jacoco Issue](https://github.com/jacoco/jacoco/issues/1381). ### Version 11.0.0 _Released March 30, 2026_ Version 11.0.0 of the Android SDK has been tested with Firebase Cloud Messaging version 25.0.1, Google Play Location Services version 21.3.0, and AltBeacon Library version 2.20.7. The minimum compatible Android API version is 26. The SDK is compiled with Android API version 36 and depends on Java version 17 and Kotlin version 2.2.21. Version 11.0.0 of the SDK is a major release that introduces changes to the In-App Messaging configuration and how the `InAppMessageManager` is accessed, minor changes to Push configuration consolidating `UrlHandlers`. This release also includes performance improvements and bug fixes. For information about migrating Android apps to version 11 of the SDK, see [Migrate to Version 11](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade/mc_engagement_upgrade_android_v11.md).
Version 10 Releases ### Version 10.0.0 _Released November 6, 2025_ Version 10.0.0 of the Android SDK has been tested with Firebase Cloud Messaging version 24.0.2, Google Play Location Services version 21.3.0, and AltBeacon Library version 2.20.7. The minimum compatible Android API version is 26. The SDK is compiled with Android API version 36 and depends on Java version 17 and Kotlin version 1.9.22. Version 10.0.0 of the SDK is a major release that introduces a new unified SDK architecture. For information about migrating Android apps to version 10 of the SDK, see [Migrate to the SDK for Android Version 10](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade/mc_engagement_upgrade_android_v10.md).
Version 9 Releases ### Version 9.0.5 _Released April 22, 2026_ Version 9.0.5 of the Android SDK has been tested with Firebase Cloud Messaging version 24.0.2, Google Play Location Services version 21.3.0, and AltBeacon Library version 2.20.7. The minimum compatible Android API version is 23. Compiled with Android API version 36. The SDK depends on Java version 17. - Fix for bundle size issue with DeviceStatistics. ### Version 9.0.4 _Released December 18, 2025_ Version 9.0.4 of the Android SDK has been tested with Firebase Cloud Messaging version 24.0.2, Google Play Location Services version 21.3.0, and AltBeacon Library version 2.20.7. The minimum compatible Android API version is 23. Compiled with Android API version 36. The SDK depends on Java version 17. - Improved UI for the push notification carousel navigation buttons. - Fix for SDK crash issues due to uncaught exceptions from Broadcast receiver on devices running Android versions 11 and 12. ### Version 9.0.3 _Released August 5, 2025_ Version 9.0.3 of the Android SDK has been tested with Firebase Cloud Messaging version 24.0.2, Google Play Location Services version 21.3.0, and AltBeacon Library version 2.20.7. The minimum compatible Android API version is 23. Compiled with Android API version 36. The SDK depends on Java version 17. - Resolved the issue of not showing more than 2 lines of message text in standard push notifications with no media. - Bug fixes and performance improvements. ### Version 9.0.2 _Released June 26, 2025_ Version 9.0.2 of the Android SDK has been tested with Firebase Cloud Messaging version 24.0.2, Google Play Location Services version 21.3.0, and AltBeacon Library version 2.20.7. The minimum compatible Android API version is 23. Compiled with Android API version 36. The SDK depends on Java version 17. - Android 16 Support - Bug fixes and performance improvements. ### Version 9.0.1 _Released May 27, 2025_ Version 9.0.1 of the Android SDK has been tested with Firebase Cloud Messaging version 24.0.2, Google Play Location Services version 21.3.0, and AltBeacon Library version 2.20.7. The minimum compatible Android API version is 23. Compiled with Android API version 35. The SDK depends on Java version 17. - Resolved `ANR` issues on app start. - Resolved `NPE` during device statistics sending. - Resolved known keys issue in `NotificationMessage` customKeys. - Bug fixes and performance improvements. ### Version 9.0.0 _Released March 14, 2025, correlating with the Marketing Cloud Engagement March 2025 release._ Version 9.0.0 of the Android SDK has been tested with Firebase Cloud Messaging version 24.0.2, Google Play Location Services version 21.3.0, and AltBeacon Library version 2.20.7. The minimum compatible Android API version is 21. Compiled with Android API version 35. The SDK depends on Java version 17. - Push notifications – Send interactive carousel push notifications to your app users. Customize buttons, small icons, large icons, and sound. - Push Delivery event – Get a delivered ENS event when a push message successfully reaches a user’s device. - Inbox 2.0 Support – Send enhanced inbox messages with additional fields like subtitles and messages, plus new CTA options (App/Web URL, None) beyond only CloudPage. - Bug fixes and performance improvements.
Version 8 Releases ### Version 8.2.2 _Released February 27, 2025_ Version 8.2.2 of the Android SDK has been tested with Firebase Cloud Messaging version 23.2.1, Google Play Location Services version 21.0.1, and AltBeacon Library version 2.20.7. The minimum compatible Android API version is 21. Compiled with Android API version 35. The SDK depends on Java version 17. - Resolved an issue with HTTP header transmission to ensure reliable delivery of engagement events from the SDK - Addressed a `NullPointerException` that occurred when the Android Bundle system returned unexpected `null` values - Optimized the batch size for event and analytics API calls to enhance performance. ### Version 8.2.1 _Released November 11, 2024, correlating with the Marketing Cloud Engagement November 2024 release._ Version 8.2.1 of the Android SDK has been tested with Firebase Cloud Messaging version 23.2.1, Google Play Location Services version 21.0.1, and AltBeacon Library version 2.20.7. The minimum compatible Android API version is 21. Compiled with Android API version 35. The SDK depends on Java version 17. - Android 15 support - Fix for `null` attribute applied through SFMCSdk Identity causing ClassCastException - This release includes bug fixes and SDK improvements ### Version 8.2.0 _Released July 30, 2024, correlating with the Marketing Cloud Engagement July 2024 release._ Version 8.2.0 of the Android SDK has been tested with Firebase Cloud Messaging version 23.2.1, Google Play Location Services version 21.0.1, and AltBeacon Library version 2.20. The minimum compatible Android API version is 21. Compiled with Android API version 34. The SDK depends on Java version 17. - The SDK now automatically switches its encryption method to use the Android Keystore. - Moved MD5 hashing to a new, isolated library for optional use, with an added option to forcibly remove MD5 in `MarketingCloudConfig`. - Removed the deprecated Android `LocalBroadcastManager` dependency. - Bug fixes and performance improvements. ### Version 8.1.5 _Released February 27, 2024, correlating with the Marketing Cloud Engagement February 2024 release._ Version 8.1.5 of the Android SDK has been tested with Google Play Services version 21.0.1 and AltBeacon Library version 2.20. The minimum compatible Android API version is 21. Compiled with Android API version 34. - Fix for `NoClassDefFoundError` – Resolved an issue where the SDK crashes while reconfiguring a running SDK if the location dependency is not present. - Bug fixes and performance improvements. ### Version 8.1.4 _Released January 30, 2024, correlating with the Marketing Cloud Engagement January 2024 release._ Version 8.1.4 of the Android SDK has been tested with Google Play Services version 21.0.1 and AltBeacon Library version 2.20. The minimum compatible Android API version is 21. Compiled with Android API version 34. - Fix for Receiver Not Registered – Android 14’s notification trampolining fix resulted in a rare occurence of an issue unregistering a local receiver. ### Version 8.1.3 _Released November 9, 2023, correlating with the Marketing Cloud Engagement October 2023 release._ Version 8.1.3 of the MobilePush Android SDK has been tested with Google Play Services version 21.0.1 and AltBeacon Library version 2.20-beta1. The minimum compatible Android API version is 21. Compiled with Android API version 34. - Fix for Proguard obfuscating classes without package name ### Version 8.1.2 _Released October 19, 2023, correlating with the Marketing Cloud Engagement October 2023 release._ Version 8.1.2 of the MobilePush Android SDK has been tested with Google Play Services version 21.0.1 and AltBeacon Library version 2.20-beta1. The minimum compatible Android API version is 21. Compiled with Android API version 34. - Fix for NPE when parsing URI scheme ### Version 8.1.1 _Released October 10, 2023, correlating with the Marketing Cloud Engagement October 2023 release._ Version 8.1.1 of the MobilePush Android SDK has been tested with Google Play Services version 21.0.1 and AltBeacon Library version 2.20-beta1. The minimum compatible Android API version is 21. Compiled with Android API version 34. - Fix for missing `requestId` property in `NotificationMessage` ### Version 8.1.0 _Released October 9, 2023, correlating with the Marketing Cloud Engagement October 2023 release._ Version 8.1.0 of the Android SDK has been tested with Google Play Services version 21.0.1 and AltBeacon Library version 2.20-beta1. The minimum compatible Android API version is 21. Compiled with Android API version 34. - Android 14 support - Resolved NPE in `DevStats` - Resolved in-app message delay not being honored - Introduced Runtime Toggles for Analytics, Inbox, Geofence Messaging, and Proximity Messaging ### Version 8.0.9 _Released May 9, 2023, correlating with the Marketing Cloud Engagement May 2023 release._ Version 8.0.9 of the Android SDK has been tested with Google Play Services version 21.0.1 and AltBeacon Library version 2.19.3. The minimum compatible Android API version is 21. Compiled with Android API version 33. - Bug fixes and performance improvements - Play Services Location – Added support for Play Services Location versions 21 and newer - Firebase Messaging – Added support for Firebase Messaging versions 23 and newer - Better Foreground and Background Detection – Replaced Google’s annotation-based detection of application foreground and background - Resolved `JSONObject` Verifier Error – A fix for the `onInit` crash has been implemented. For more information, see the [Google Issue Tracker](https://issuetracker.google.com/issues/37012699#comment13). ### Version 8.0.8 _Released January 5, 2022, correlating with the Marketing Cloud Engagement October 2022 release._ Version 8.0.8 of the Android SDK has been tested with Google Play Services version 19.0.1 and AltBeacon Library version 2.19.3. The minimum compatible Android API version is 21. Compiled with Android API version 33. - `requestId` fix for analytics reporting issues - Bug fixes and performance improvements ### Version 8.0.7 _Released September 29, 2022, correlating with the Marketing Cloud Engagement October 2022 release._ Version 8.0.7 of the Android SDK has been tested with Google Play Services version 19.0.1 and AltBeacon Library version 2.19.3. The minimum compatible Android API version is 21. Compiled with Android API version 33. - Support for Android 13 - Support for ENS - Support for latest Firebase Messaging - Support for latest Beacon Messaging - Added `redirectForAnalytics` support for `RemoteNotification` - Bug fixes and performance improvements ### Version 8.0.6 _Released May 4, 2022, correlating with the Marketing Cloud Engagement May 2022 release._ Version 8.0.6 of the Android SDK has been tested with Google Play Services version 17.1.0 and AltBeacon Library version 2.19. The minimum compatible Android API version is 21. Compiled with Android API version 31. - Bug fixes and performance improvements ### Version 8.0.5 _Released March 22, 2022, correlating with the Marketing Cloud Engagement March 2022 release._ Version 8.0.5 of the Android SDK has been tested with Google Play Services version 17.1.0 and AltBeacon Library version 2.19. The minimum compatible Android API version is 21. Compiled with Android API version 31. - Bug fixes and performance improvements ### Version 8.0.4 _Released November 22, 2021, correlating with the Marketing Cloud Engagement October 2021 release._ Version 8.0.4 of the Android SDK has been tested with Google Play Services version 17.1.0 and AltBeacon Library version 2.19. The minimum compatible Android API version is 21. Compiled with Android API version 31. - Bug fixes and performance improvements ### Version 8.0.3 _Released November 12, 2021, correlating with the Marketing Cloud Engagement October 2021 release._ Version 8.0.3 of the Android SDK has been tested with Google Play Services version 17.1.0 and AltBeacon Library version 2.19. The minimum compatible Android API version is 21. Compiled with Android API version 31. - Bug fixes and performance improvements ### Version 8.0.2 _Released November 2, 2021, correlating with the Marketing Cloud Engagement October 2021 release._ Version 8.0.2 of the Android SDK has been tested with Google Play Services version 17.1.0 and AltBeacon Library version 2.19. The minimum compatible Android API version is 21. Compiled with Android API version 31. - Bug fixes and performance improvements ### Version 8.0.1 _Released October 11, 2021, correlating with the Marketing Cloud Engagement October 2021 release._ Version 8.0.1 of the Android SDK has been tested with Google Play Services version 17.1.0 and AltBeacon Library version 2.19. The minimum compatible Android API version is 21. Compiled with Android API version 31. - Bug fixes and performance improvements - Support for Android 12 - Support for latest Firebase Messaging - Support for latest Beacon Messaging ### Version 8.0.0 _Released October 4, 2021, correlating with the Marketing Cloud Engagement October 2021 release._ Version 8.0.0 of the Android SDK has been tested with Google Play Services version 17.1.0 and AltBeacon Library version 2.19. The minimum compatible Android API version is 21. Compiled with Android API version 31. **important:** This version is deprecated. Use version 8.0.1 or newer.
Version 7 Releases ### Version 7.4.4 _Released December 12, 2021, correlating with the Marketing Cloud Engagement June 2021 release._ Version 7.4.4 of the Android SDK has been tested with Google Play Services version 22.0.0 and AltBeacon Library version 2.19. The minimum compatible Android API version is 21. Compiled with Android API version 31. - Backport of version 8’s `RejectedExecutionException` Fix ### Version 7.4.3 _Released September 3, 2021, correlating with the Marketing Cloud Engagement June 2021 release._ Version 7.4.3 of the Android SDK has been tested with Google Play Services version 22.0.0 and AltBeacon Library version 2.19. The minimum compatible Android API version is 21. Compiled with Android API version 31. - Android 12 Support - Backported Android 12 support from the 8.x version of the SDK ### Version 7.4.2 _Released September 2, 2021, correlating with the Marketing Cloud Engagement June 2021 release._ Version 7.4.2 of the Android SDK has been tested with Google Play Services version 20.3.0 and AltBeacon Library version 2.17.1. The minimum compatible Android API version is 21. Compiled with Android API version 29. - Bug fixes and performance improvements ### Version 7.4.1 _Released June 11, 2021, correlating with the Marketing Cloud Engagement June 2021 release._ Version 7.4.1 of the Android SDK has been tested with Google Play Services version 17.1.0 and AltBeacon Library version 2.17.1. The minimum compatible Android API version is 21. Compiled with Android API version 29. - Bug fixes and performance improvements ### Version 7.4.0 _Released June 2, 2021, correlating with the Marketing Cloud Engagement June 2021 release._ Version 7.4.0 of the Android SDK has been tested with Google Play Services version 17.1.0 and AltBeacon Library version 2.17.1. The minimum compatible Android API version is 21. Compiled with Android API version 29. - Bug fixes and performance improvements ### Version 7.3.1 _Released November 25, 2020, correlating with the Marketing Cloud Engagement November 2020 release._ Version 7.3.1 of the Android SDK has been tested with Google Play Services version 21.0.0 and AltBeacon Library version 2.17.1. The minimum compatible Android API version is 21. Compiled with Android API version 29. - Bug fixes and performance improvements - Fixed a rare issue where the SDK crashed silently during initialization when upgrading from an old version of the SDK - Fixed an issue where clicking a Geofence or Beacon message didn’t open the provided OpenDirect URL - Fixed an issue where the SDK crashed when reobfuscated by the consuming mobile application - Corrected an SDK debug log incorrectly logging as error - Updated third-party dependencies for Google Play Services, Kotlin support, and the AltBeacon library ### Version 7.3.0 _Released October 12, 2020, correlating with the Marketing Cloud Engagement October 2020 release._ Version 7.3.0 of the Android SDK has been tested with Google Play Services version 17.0.0 and AltBeacon Library version 2.16.4. The minimum compatible Android API version is 21. Compiled with Android API version 29. - This release fixes the following issues. - Crashes on Android 21 (Lollipop) - Issues related to the FullImageFill In-App Message type on Android 23 (Marshmallow) - Fixes a rare `IllegalAccessError` on network failure. ### Version 7.2.0 _Released June 1, 2020, correlating with the Marketing Cloud Engagement June 2020 release._ Version 7.2.0 of the Android SDK has been tested with Google Play Services version 17.0.0 and AltBeacon Library version 2.16.4. The minimum compatible Android API version is 21. Compiled with Android API version 29. - Bug fixes and performance improvements ### Version 7.1.0 _Released March 23, 2020, correlating with the Marketing Cloud Engagement March 2020 release._ Version 7.1.0 of the Android SDK has been tested with Google Play Services version 17.0.0 and AltBeacon Library version 2.16.4. The minimum compatible Android API version is 21. Compiled with Android API version 29. - Image fills for full-page in-app messages: Currently, the full-page in-app message template crops images to a 16:9 aspect ratio. With this update, images can fill a larger portion of the screen and drive engagement with your app. To support image fill for full-page in-app messages, update to the March release of the MobilePush SDK. Image fill is available to customers with MobilePush and Journey Builder. - Bug fixes and performance improvements ### Version 7.0.0 _Released February 24, 2020, correlating with the Marketing Cloud Engagement February 2020 release._ Version 7.0.0 of the Android SDK has been tested with Google Play Services version 17.0.0 and AltBeacon Library version 2.16.4. The minimum compatible Android API version is 21. Compiled with Android API version 29. - Bug fixes and performance improvements
Version 6 Releases ### Version 6.4.0 _Released October 28, 2019, correlating with the Marketing Cloud Engagement October 2019 release._ Version 6.4.0 of the Android SDK has been tested with Google Play Services version 17.0.0 and AltBeacon Library version 2.16.3. The minimum compatible Android API version is 16. Compiled with Android API version 29. - Bug fixes and performance improvements ### Version 6.3.5 _Released September 25, 2019, correlating with the Marketing Cloud Engagement June 2019 release._ Version 6.3.5 of the Android SDK has been tested with Google Play Services version 16.0.0 and AltBeacon Library version 2.16.2. The minimum compatible Android API version is 16. Compiled with Android API version 29. - Bug fixes and performance improvements ### Version 6.3.4 _Released July 25, 2019 correlating with the Marketing Cloud Engagement June 2019 release._ Version 6.3.4 of the Android SDK has been tested with Google Play Services version 16.0.0 and AltBeacon Library version 2.16.2. The minimum compatible Android API version is 16. Compiled with Android API version 29. - Android Q Support: This release of the SDK adds support for the new `ACCESS_BACKGROUND_LOCATION` permission. The changes in Android Q require that you request this permission from your users when on an Android Q device for Geofence and Beacon messaging. For more information, see [Implement Location Messaging on Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_location_messages/mc_engagement_location_messages_android.md). - `JobIntentService` bug fix: Added code to prevent an unhandled exception thrown by Google’s `JobIntentService`. - Inbox message status: This release better reflects the read or deleted state of an inbox message in Engagement. - New LearningApp: This release includes an updated, simplified, and modern sample app using the MobilePush SDK. For more information, see [MobilePush SDK Android LearningApp](https://github.com/salesforce-marketingcloud/MarketingCloudSDK-Android/tree/master). ### Version 6.3.3 _Released June 25, 2019, correlating with the Marketing Cloud Engagement June 2019 release._ Version 6.3.3 of the Android SDK has been tested with Google Play Services version 16.0.0 and AltBeacon Library version 2.16.1. The minimum compatible Android API version is 16. Compiled with Android API version 28. - Deliver in-app messages: Deliver relevant, personalized messages to your app’s users. Send messages without relying on users having enabled push notifications. Engaging full-screen, modal, or banner messages are presented while your users are interacting with your app. For more information, see [Implement In-App Messaging on Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_in-app_messages/mc_engagement_in-app_messages_android.md). - Improved database recovery: In rare instances, the database used by the SDK becomes corrupt. To resolve any issues before initialization is complete, we added code to validate the database and its structure during initialization. - Fixed rare system bug: Certain Android devices and versions can cause issues when modifying the message data associated with a notification’s `PendingIntent`. To avoid these issues, we changed the structure of the data stored in the `PendingIntent`. ### Version 6.2.2 _Released May 21, 2019, correlating with the Marketing Cloud Engagement April 2019 release._ Version 6.2.2 of the Android SDK has been tested with Google Play Services version 16.0.0 and AltBeacon Library version 2.16.1. The minimum compatible Android API version is 16. Compiled with Android API version 28. - Prevent crash on Android O or newer: Some devices running Android O or newer can exhibit a bug where the SDK attempts to create a job using Android’s `JobScheduler` when there are already 100 scheduled jobs, resulting in Android throwing an `IllegalStateException`. We added code to prevent this crash and improve logging when the issue occurs. ### Version 6.2.1 _Released April 23, 2019, correlating with the Marketing Cloud Engagement April 2019 release._ Version 6.2.1 of the Android SDK has been tested with Google Play Services version 16.0.0 and AltBeacon Library version 2.16.1. The minimum compatible Android API version is 16. Compiled with Android API version 28. - Required app endpoint (tenant-specific endpoint): To pass the SDK’s configuration, an app endpoint is now required. Find the app endpoint for your app under Administration in MobilePush. Review Configuration Requirements for details. - Enforced critical update to Firebase Cloud Messaging for Android SDK: For your app to continue receiving messages, update your SDK to version 6.0.1 or later and configure your app with Firebase initialized. - Added ability to delay registration until the contact key is set: Use a new SDK configuration value to delay registrations to Engagement until a contact key is set via setDelayRegistrationUntilContactKeyIsSet(). Review Delay Registration for details. - Inbox messages support sendDateUtc for sorting: Inbox messages delivered to your app now include the date that the message was sent. App users can sort their inbox based on this value. For more information, see [Implement Inbox Messaging on Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_inbox_messages/mc_engagement_inbox_messages_android.md). - Added ability to set read or deleted by inbox message ID only: Added convenience methods to set the status of an inbox message to read or deleted with only the message’s ID as an argument. ### Version 6.1.0 _Released February 11, 2019, correlating with the Marketing Cloud Engagement January 2019 release._ Version 6.1.0 of the Android SDK has been tested with Google Play Services version 16.0.0 and AltBeacon Library version 2.15.2. The minimum compatible Android API version is 16. Compiled with Android API version 28. - Implemented message segmentation: The Android SDK now supports app control over which push notifications, geofence messages, and beacon messages are displayed. Use the region information provided for geofence and beacon messages in your notification presentation logic. Review Notification Segmentation. - Implemented predictive intelligence identifier (PIID) configuration options and APIs: Configure the identifier for Predictive Intelligence analytics according to how you use Personalization Builder. Configure your applications to use either existing contact key data or a PI-specific identifier. For more information, see [Enable and Use Analytics on Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_analytics/mc_engagement_analytics_android_implement.md). - Added ability to unregister a `WhenReadyListener` passed to `requestSdk`: For more information, see the reference documentation for [`unregisterWhenReadyListener()`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/MarketingCloudSdk/8.0/-marketing%20-cloud%20-s-d-k/com.salesforce.marketingcloud/-marketing-cloud-sdk/unregister-when-ready-listener.html). ### Version 6.0.2 (Revised) _Released December 5, 2018._ Version 6.0.2 of the Android SDK has been tested with Google Play Services version 15.0.1 and AltBeacon Library version 2.14. The minimum compatible Android API version is 16. Compiled with Android API version 27. - Corrected a registration frequency issue in the SDK that allows for multiple registration requests to be sent to Engagement within a small amount of time. Now, registration edits are properly batched and sent one time per minute. - Improved `SdkState` logging output to support you during debugging sessions. ### Version 6.0.2 _Released October 22, 2018, correlating with the Marketing Cloud Engagement 215 release._ Version 6.0.2 of the Android SDK has been tested with Google Play Services version 15.0.1 and AltBeacon Library version 2.14. The minimum compatible Android API version is 16. Compiled with Android API version 27. - Replaced GCM with FCM: We removed the deprecated Google Cloud Messaging library and replaced it with Firebase Cloud Messaging. Configure your application so that Firebase is initialized. For more information, see [Integrate the MobilePush Android SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_integrate_android/engagement_sdk_guide_integrate_android.md). - Simplified notification customization and handling: We've simplified the `MarketingCloudConfig.Builder` by consolidating all of the notification customization options into a single `NotificationCustomizationOptions` class. For more information, see [Customize Push Notification Functionality for Android Apps](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications/mc_engagement_push_notifications_android_customize.md). - Fewer required dependencies: The Google Play Services Location and AltBeacon dependencies are no longer declared in the SDK’s `pom.xml` file as required dependencies. If your application requires these features, follow the instructions provided in [Implement Location Messaging on Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_location_messages/mc_engagement_location_messages_android.md). - Improved initialization verification: To make sure that the necessary information is provided before the SDK is initialized, we've added additional checks to `MarketingCloudConfig.Builder`. These checks make sure that an icon resource for notifications is provided and that notification channels are handled. To allow for this change, update your call to `MarketingCloudConfig.Builder#build(Context)` to pass in an `Android` context. - Default notification channel: The SDK now creates a default notification channel named “Marketing”. For information on how to modify this channel, see [Implement Default and Custom Notification Channels](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications/mc_engagement_push_notifications_android_custom_notification.md). - Removed `Attribute` class: We removed the previously deprecated `Attribute` class, along with any associated methods. Registration attributes are now provided in a key-value `Map`. - Removed `DefaultUrlPresenter`: To address potential security concerns, we removed the SDK’s default URL presenter. Consequently, if your message involves redirection to a web URL, resource, file, or other custom application schema driven by business logic, override notification handling. For more information, see [Handling URLs and Custom Keys](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_handle_urls.md). - Tenant-Specific Endpoint: Two new methods were added to `MarketingCloudConfig.Builder` to facilitate Tenant-Specific Endpoints: `setMarketingCloudServerUrl()` and `setMid()`. These methods configure the SDK to communicate with the specific server for your application. For guidance on where to find your Tenant-Specific Endpoint and MID, see [Updating Engagement Endpoints to Tenant-Specific Endpoints: FAQ](https://help.salesforce.com/s/articleView?id=000392227&type=1). - Improved Kotlin interoperability: Addressed issues reported by the Kotlin interoperability Android lint check. - Added nullability annotations to all public APIs. - Reversed parameter order of MarketingCloudSdk’s `whenReady` method to make the interface eligible for SAM conversion. - Fixed region message URL locale bug: For locales that don’t use `.` as the decimal separator, the SDK requests region messages in a format that Engagement doesn’t support. We corrected this issue to enforce that `.` is used, regardless of device locale.
## iOS This section contains information about releases of the MobilePush SDK for iOS, including version numbers, release dates, compatibility details, and key changes. ### Latest Release: Version 11.0.2 _Released July 23, 2026_ Resolved a race condition that crashed the SDK when accessing event configuration data. ### Version 11.0.1 _Released June 26, 2026_ Fixed the In-App DisplayCompleted event analytics to accurately capture buttonId for button dismissals. ### Version 11.0.0 _Released March 31, 2026_ Version 11.0.0 of the SDK is a major release that introduces a new improved In-App Messaging feature module. For information about migrating iOS apps to version 11 of the SDK, see [Migrate to Version 11](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade/mc_engagement_upgrade_ios_v11.md). The minimum compatible iOS API version is 12. - Performance improvements and bug fixes. - SFMC module version 4.0.0 (compatible with this module version 11.0.0 and above) - Extension SDK version 3.0.0 (compatible with this module version 11.0.0 and above) - Push Feature module version 2.0.0 (compatible with this module version 11.0.0 and above) - InAppMessaging Feature module version 1.0.0 (compatible with this module version 11.0.0 and above)
Version 10 Releases ### Version 10.0.0 _Released November 6, 2025_ Version 10.0.0 of the SDK is a major release that introduces a new unified SDK architecture. For information about migrating iOS apps to version 10 of the SDK, see [Migrate to the SDK for iOS Version 10](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade/mc_engagement_upgrade_ios_v10.md). The minimum compatible iOS API version is 12. - Bug fixes and performance improvements. - SFMCSDK version 3.0.0 (compatible with Marketing Cloud SDK versions 10.0.0 and above). - Extension SDK version 2.0.0 (compatible with Marketing Cloud SDK versions 10.0.0 and above). - Push Feature SDK version 1.0.0 (compatible with Marketing Cloud SDK versions 10.0.0 and above).
Version 9 Releases ### Version 9.0.3 _Released July 2, 2025_ - Performance improvements and bug fixes for the In-App Messaging functionality. - Extension SDK version 1.0.3 released on December 16, 2025 (compatible with MobilePush versions 9.0.3 and later). Update to this version to get improved UI for the push notification carousel navigation buttons. ### Version 9.0.2 _Released June 11, 2025_ - Resolved Apple digital certificate signing issue found in versions 9.0.0 and 9.0.1. - SFMCSDK version 2.0.1 (compatible with Push Module versions 9.0.2 and later). - Extension SDK version 1.0.2 (compatible with Push Module versions 9.0.2 and later). ### Version 9.0.1 _Released May 26, 2025_ - Thumbnail support: Enable or disable the first image of the Carousel template as a thumbnail. For implementation details, see [Configure Thumbnail](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_integrate_ios_extension/mc_engagement_integrate_ios_extension_configure_service.md#configure-thumbnail). - Extension SDK version 1.0.1 (compatible with Push Module versions 9.0.1 and later). - Bug fixes and performance improvements. - Update to version 9.0.2 to resolve the Apple digital certificate signing issue found in this version. ### Version 9.0.0 _Released March 14, 2025, correlating with the Marketing Cloud Engagement March 2025 release._ - Carousel push notifications – Send interactive carousel push notifications to your app users. For implementation details, see [Integrate the MobilePush Extension SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_integrate_ios_extension/mc_engagement_integrate_ios_extension.md). - Push Delivery event – Get a delivered ENS event when a push message successfully reaches a user’s device. For more details, see [Integrate the MobilePush Extension SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_integrate_ios_extension/mc_engagement_integrate_ios_extension.md). - Inbox 2.0 Support – Send enhanced inbox messages with additional fields like subtitles and messages, plus new CTA options (App/Web URL, None) beyond only CloudPage. For implementation details, see [Implement Inbox Messaging on iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_inbox_messages/mc_engagement_inbox_messages_ios.md). - Bug fixes and performance improvements. - Extension SDK version 1.0.0 (compatible with Push Module versions 9.0.0 and later). - SFMCSDK version 2.0.0 (compatible with Push Module versions 9.0.0 and later). - Update to version 9.0.2 to resolve the Apple digital certificate signing issue found in this version.
Version 8 Releases ### Version 8.1.4 _Released June 11, 2025_ - Resolved Apple digital certificate signing issue that occurs with versions 8.1.1, 8.1.2, and 8.1.3. - SFMCSDK version 1.1.4 (compatible with Push Module versions 8.1.4 and later). ### Version 8.1.3 _Released July 23, 2024, correlating with the Marketing Cloud Engagement July 2024 release._ - Resolved hang issues occurring during the first launch and app upgrades, resulting in improved SDK performance. - Fixed an issue affecting Inbox Open Analytics when the Inbox Replace feature is enabled. - Bug fixes and performance improvements. - SFMCSDK version 1.1.3 (compatible with Push Module versions 8.1.2 and later). - Update to version 8.1.4 to resolve the Apple digital certificate signing issue found in this version. ### Version 8.1.2 _Released February 27, 2024, correlating with the Marketing Cloud Engagement February 2024 release._ - Privacy Manifest – Adds a privacy manifest that declares the default data collected by the SDK as per [Apple’s privacy requirements for third-party SDKs](https://developer.apple.com/documentation/bundleresources/privacy_manifest_files). For more information, see [Apple Privacy Manifest Guide](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement/mc_engagement_integrate_ios/engagement_sdk_guide_integrate_ios_privacy_manifest.md). - SFMCSDK version 1.1.2 (compatible with Push Module versions 8.1.2 and later). - Update to version 8.1.4 to resolve the Apple digital certificate signing issue found in this version. ### Version 8.1.1 _Released January 18, 2024, correlating with the Marketing Cloud Engagement January 2024 release._ Version 8.1.1 of the iOS SDK requires SFMC SDK v1.0.8. The minimum compatible iOS API version is 12. - Bug fixes and performance improvements - Framework code signatures: Code signatures have been added to all frameworks. - Alert + Inbox “Tap To Read”: Configure the SDK to mark an inbox message as “read” when a user taps the push notification for an Alert + Inbox message. For more information, see [Implement Inbox Messaging on iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement/mc_engagement_inbox_messages/mc_engagement_inbox_messages_ios.md). - Discontinued support for iOS 11. - Update to version 8.1.4 to resolve the Apple digital certificate signing issue found in this version. ### Version 8.1.0 _Released October 30, 2023, correlating with the Marketing Cloud Engagement October 2023 release._ Version 8.1.0 of the iOS SDK requires SFMC SDK v1.0.8. The minimum compatible iOS API version is 11. - Bug fixes and performance improvements - Runtime Toggles: Enable or disable Analytics, Inbox, Geofence Messaging, and Proximity Messaging at runtime. For more information, see [Runtime Toggles](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_runtime_toggles.md). - `MarketingCloudSDK.bundle` Integration: We've eliminated the need for manual addition of `MarketingCloudSDK.bundle` as an application resource, streamlining the integration process. - New API – Added an API, `requestPushSdk`, which guarantees access to the Push module when it becomes available. - MarketingCloudSDK integration via Swift Package Manager (SPM): Integration via SPM now automatically includes SFMCSDK, simplifying integration efforts. - Improved logging for multiple push providers: Introduced enhanced log messages to warn users about multiple push providers, aiding in proactive implementation decisions. - Initialization issues on locked devices: Fixed an issue where the SDK failed to initialize when the device was locked and no keychain or data protection was available. - Compatibility fix for iOS 11: Addressed initialization issues specific to iOS 11, ensuring seamless integration and functionality on this platform. - Enhanced diagnostic tooling: The MobilePush iOS SDK now detects and logs SDK implementation issues, providing guidance in the log output for smoother implementations. ### Version 8.0.13 _Released May 3, 2023, correlating with the Marketing Cloud Engagement May 2023 release._ Version 8.0.13 of the iOS SDK requires SFMC SDK v1.0.8. The minimum compatible iOS API version is 11. - Bug fixes and performance improvements. ### Version 8.0.12 _Released March 27, 2023, correlating with the Marketing Cloud Engagement March 2023 release._ Version 8.0.12 of the iOS SDK requires SFMC SDK v1.0.8. The minimum compatible iOS API version is 11. - Bug fixes and performance improvements. - Adds registration callbacks: Added the ability to pass a single callback to listen to registration events. - Adds configurable filesystem protection types: Added the ability to configure the SDK’s [protection values](https://developer.apple.com/documentation/foundation/fileprotectiontype). For an example implementation, see the [MobilePush iOS LearningApp](https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS/tree/master/LearningApp). - Fixes crashes due to Xcode archive overriding the default `CFBundleShortVersionString` within the framework. - Addresses crashes caused by back-to-back initializations of the SDK. - Deprecates `tearDown` methods: The SDK now handles tear-downs internally. - Improved data merge tool performance. ### Version 8.0.10 _Released January 24, 2023, correlating with the Marketing Cloud Engagement January 2023 release._ Version 8.0.10 of the iOS SDK requires SFMC SDK v1.0.8. The minimum compatible iOS API version is 11. - This release includes bug fixes and SDK improvements. **important:** This version deprecates support for iOS versions 10.0 and older, and Xcode versions 13.x and older. ### Version 8.0.9 _Released December 7, 2022, correlating with the Marketing Cloud Engagement December 2022 release._ Version 8.0.9 of the iOS SDK requires SFMC SDK v1.0.6. The minimum compatible iOS API version is 10. - Bug fix for push open reporting and Inbox message retrieval. ### Version 8.0.8 _Released September 29, 2022, correlating with the Marketing Cloud Engagement October 2022 release._ Version 8.0.8 of the iOS SDK requires SFMC SDK v1.0.6. The minimum compatible iOS API version is 10. - Support for ENS. - This release includes bug fixes, SDK, and performance improvements. ### Version 8.0.7 _Released August 18, 2022, correlating with the Marketing Cloud Engagement August 2022 release._ Version 8.0.7 of the iOS SDK requires SFMC SDK v1.0.6. The minimum compatible iOS API version is 10. - This release includes fixes for Objective-C compatibility - SDK data merge: This release includes a tool that facilitates the reconciliation of the dataset associated with the v7.x SDK and the current dataset for v8.x SDK users. For information, see [Troubleshoot Data Merge](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting/mc_engagement_troubleshooting_ios_data_merge.md). ### Version 8.0.6 _Released April 14, 2022, correlating with the Marketing Cloud Engagement March 2022 release._ Version 8.0.6 of the iOS SDK requires SFMC SDK v1.0.6. The minimum compatible iOS API version is 10. - Bug fixes and performance improvements. ### Version 8.0.5 _Released March 31, 2022, correlating with the Marketing Cloud Engagement January 2022 release._ Version 8.0.5 of the iOS SDK requires SFMC SDK v1.0.6. The minimum compatible iOS API version is 10. - This release fixes the following issues. - Swizzling ViewDidAppear - Keychain crashes in iOS 15 - Adds namespacing to encryption files in SFMCSDK. - Library evolution with Xcode 12.5 as minimum Xcode compatibility. ### Version 8.0.4 _Released February 4, 2022, correlating with the Marketing Cloud Engagement January 2022 release._ Version 8.0.4 of the iOS SDK requires SFMC SDK v1.0.6. The minimum compatible iOS API version is 10. - This release fixes the following issues. - Open Direct URL - Swizzling `ViewDidAppear` - Version conflict when uploaded to TestF light and similar apps - Support for CocoaPods along with Swift Package Manager. ### Version 8.0.3 _Released January 3, 2022, correlating with the Marketing Cloud Engagement January 2022 release._ Version 8.0.3 of the iOS SDK requires SFMC SDK v1.0.6. The minimum compatible iOS API version is 10. - This release includes fixes for the validation process (bundle collision and structure). ### Version 8.0.2 _Released December 14, 2021, correlating with the Marketing Cloud Engagement December 2021 release._ Version 8.0.2 of the iOS SDK requires SFMC SDK v1.0.6. The minimum compatible iOS API version is 10. - This release includes a fix for the profile attributes API. ### Version 8.0.1 _Released October 28, 2021, correlating with the Marketing Cloud Engagement October 2021 release._ Version 8.0.1 of the iOS SDK requires SFMC SDK v1.0.6. The minimum compatible iOS API version is 10. - This release includes open attributes API and `InboxMessage` UI support fixes. ### Version 8.0.0 _Released October 14, 2021, correlating with the Marketing Cloud Engagement October 2021 release._ Version 8.0.0 of the iOS SDK requires SFMC SDK v1.0.6. The minimum compatible iOS API version is 10. - Bug fixes and performance improvements. - Introducing Swift Packages. - Discontinuation of CocoaPods support in favor of Swift Package Manager. For guidance on migrating to SDK version 8.x, see [Migrate to the MobilePush SDK for iOS Version 8](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade/mc_engagement_upgrade_ios_v8.md).
Version 7 Releases ### Version 7.6.0 _Released June 2, 2021, correlating with the Marketing Cloud Engagement June 2021 release._ The minimum compatible iOS API version is 10. - Bug fixes and performance improvements. ### Version 7.5.1 _Released May 25, 2021, correlating with the Marketing Cloud Engagement May 2021 release._ The minimum compatible iOS API version is 10. - In App banner message bug fix: Fixes an issue where banner In-App messages crash on iOS 14. ### Version 7.5.0 _Released March 17, 2021, correlating with the Marketing Cloud Engagement March 2021 release._ The minimum compatible iOS API version is 10. - Packaged SDK as an XCFramework: The SDK is now packaged as an XCFramework, supporting arm64 simulators on Macs with M1 Chipsets. ### Version 7.4.0 _Released February 11, 2021, correlating with the Marketing Cloud Engagement February 2021 release._ The minimum compatible iOS API version is 10. - Improve Inbox Messages sync when force closing app: Improved chances of syncing inbox message status with the server for end users who force close the app. - Bug fixes and performance improvements. ### Version 7.3.1 _Released December 22, 2020, correlating with the Marketing Cloud Engagement November 2020 release._ The minimum compatible iOS API version is 10. - Added Support for arm64e: Explicitly added arm64e architecture to enable reading debug symbols on arm64e devices. ### Version 7.3.0 _Released November 11, 2020, correlating with the Marketing Cloud Engagement November 2020 release._ The minimum compatible iOS API version is 10. - Fixes for rare race conditions linked to customer reported crash reports showing crash during SDK tear down following the successful deletion of data prompted by a GDPR request. - Fix possible naming collisions with Objective-C Classes: Renamed `Event` class to minimize potential naming collisions for customers using Objective-C. ### Version 7.2.2 _Released August 31, 2020, correlating with the Marketing Cloud Engagement June 2020 release._ The minimum compatible iOS API version is 10. - Bug fixes and performance improvements. ### Version 7.2.1 _Released July 6, 2020, correlating with the Marketing Cloud Engagement June 2020 release._ The minimum compatible iOS API version is 10. - Bug fixes and performance improvements. - Fixes an issue where the custom data field wasn’t present in inbox messages. ### Version 7.2.0 _Released June 1, 2020, correlating with the Marketing Cloud Engagement June 2020 release._ The minimum compatible iOS API version is 10. - Bug fixes and performance improvements. ### Version 7.1.1 _Released May 18, 2020, correlating with the Marketing Cloud Engagement March 2020 release._ The minimum compatible iOS API version is 10. - Added armv7 support: We had previously removed armv7 support, restricting support to armv7s and arm64 architectures. This release provides armv7, armv7s, and arm64 support. ### Version 7.1.0 _Released March 23, 2020, correlating with the Marketing Cloud Engagement March 2020 release._ The minimum compatible iOS API version is 10. - Image Fill for full-page in-app messages: Currently, the full-page in-app message template crops images to a 16:9 aspect ratio. With this update, images can fill a larger portion of the screen and drive engagement with your app. To support image fill for full-page in-app messages, update to the March release of the MobilePush SDK. Image fill is available to customers with MobilePush and Journey Builder. ### Version 7.0.1 _Released January 25, 2020, correlating with the Marketing Cloud Engagement January 2020 release._ The minimum compatible iOS API version is 10. - JSON configuration method removal: The `sfmc_configure` and `sfmc_configureWithURL` SDK configuration methods, using the `MarketingCloudSDKConfiguration.json` file, have been removed. If you’re upgrading to this version of the SDK, see [Integrate the MobilePush iOS SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_integrate_ios/mc_engagement_integrate_ios.md) for an example of using our `ConfigBuilder` for simple, code-based SDK configuration. - Required minimum deployment target of iOS 10.0: Existing mobile applications continue to function, without change. Mobile applications can continue to reference older SDK versions, without change. Applications that adopt the January 2020 MobilePush SDK release require a project change, if your application build still supports iOS 9.
Version 6 Releases ### Version 6.4.2 _Released December 27, 2019, correlating with the Marketing Cloud Engagement October 2019 release._ - Bug fixes and performance improvements for devices running iOS 13. ### Version 6.4.1 _Released November 22, 2019, correlating with the Marketing Cloud Engagement October 2019 release._ - Bug fixes and performance improvements. - Updated LearningApp for iOS data protection: This release includes an updated, simplified, and modern sample app using the MobilePush SDK. For more information, see the [MobilePush iOS LearningApp](https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS/tree/master/LearningApp). ### Version 6.4.0 _Released October 28, 2019, correlating with the Marketing Cloud Engagement October 2019 release._ - JSON configuration method deprecation: The `sfmc_configure` and `sfmc_configureWithURL` SDK configuration methods, using the `MarketingCloudSDKConfiguration.json` file, have been deprecated. These methods will be removed in the next SDK release. If you’re upgrading to this version of the SDK, see [Configure the MobilePush iOS SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_integrate_ios/mc_engagement_integrate_ios_configure.md) for an example of using our `ConfigBuilder`. - Immediate registration after install: To more effectively establish an Engagement contact, a MobilePush registration is sent immediately following the first SDK configuration after a new app install. Subsequent registrations are deferred for up to 60 seconds, as described in [Contact and Device Registration](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_register_contacts_devices/mc_engagement_register_contacts_devices.md). ### Version 6.3.6 _Released September 26, 2019, correlating with the Marketing Cloud Engagement June 2019 release._ - Bug fixes and performance improvements. - In-App message layout improvements: On iOS 13 devices, when in-app messages are displayed on an iPad in Split View modes, messages are sized appropriately. ### Version 6.3.4 _Released July 25, 2019, correlating with the Marketing Cloud Engagement June 2019 release._ - New LearningApp for iOS: This release includes an updated, simplified, and modern sample app using the MobilePush SDK. For more information, see the [MobilePush iOS LearningApp](https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS/tree/master/LearningApp). - Inbox message status: This release better reflects the `read` or `deleted` state of an inbox message in Engagement. ### Version 6.3.3 _Released June 17, 2019 correlating with the Marketing Cloud Engagement June 2019 release._ - Deliver in-app messages: Deliver relevant, personalized messages to your app’s users. Send messages without relying on users having enabled push notifications. Engaging full-screen, modal, or banner messages are presented while your users are interacting with your app. For more information and implementation guidance, see [Implement In-App Messaging on iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_in-app_messages/mc_engagement_in-app_messages_ios.md). ### Version 6.2.3 _Released May 21, 2019, correlating with the Marketing Cloud Engagement April 2019 release._ - Fixed issue with inbox start date: Inbox messages now respect `startDateUtc` payload values in all cases. ### Version 6.2.2 _Released May 2, 2019, correlating with the Marketing Cloud Engagement April 2019 release._ - Removed SDK test code from the library: Test code associated with SDK development was removed from the public release. - Fixed location messaging date calculation: Fixed an issue in calculating the "next show date" for location messages, where previously there was a discrepancy of one day. ### Version 6.2.0 _Released April 23, 2019, correlating with the Marketing Cloud Engagement April 2019 release._ - Required app endpoint (Tenant-Specific Endpoint): Passing the SDK’s configuration now mandates an app endpoint. Locate your app’s endpoint under **Administration** in the MobilePush UI. For guidance on where to find your Tenant-Specific Endpoint, see [Updating Engagement Endpoints to Tenant-Specific Endpoints: FAQ](https://help.salesforce.com/s/articleView?id=000392227&type=1). - Added application badging override: A new SDK configuration value gives you full control of your app’s badge value. - Added ability to delay registration until the contact key is set: Use a new SDK configuration value to delay registrations to Engagement until a contact key is set via `sfmc_setContactKey:`. For more information, see [Delay Registrations Until Contact Key is Set](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_register_contacts_devices/mc_engagement_register_contacts_devices_contact_dissociation.md#delay-registrations-until-contact-key-is-set). - Inbox messages support `sendDateUtc` for sorting: Inbox messages delivered to your app now include the date that the message was sent. App users can sort their inbox based on this value. For more information, see [Implement Inbox Messaging on iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_inbox_messages/mc_engagement_inbox_messages_ios.md). - Better tracking of "open from push" analytics: The SDK now captures "open from push" analytics more effectively when the application isn’t running, especially when configured asynchronously. - Fixed an issue with the `ConfigurationBuilder`: Fixed an issue with using the `ConfigurationBuilder` method to configure the SDK that caused an authorization error when contacting Engagement. ### Version 6.1.4 _Released February 28, 2019, correlating with the Marketing Cloud Engagement January 2019 release._ Corrected an issue that prevented a location or proximity `CloudPage+Alert` message from displaying. ### Version 6.1.3 _Released February 11, 2019, correlating with the Marketing Cloud Engagement January 2019 release._ - Implemented location message segmentation: The SDK now supports app control over which geofence and beacon messages are displayed. Use the region information provided for geofence and beacon messages in your notification presentation logic. For details, see [Location Message Segmentation](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_location_messages/mc_engagement_location_messages_ios_segment.md). - Implemented Predictive Intelligence Identifier (PIID) configuration options and APIs: Configure the identifier for Predictive Intelligence analytics according to how you use Personalization Builder. Configure your applications to use either existing contact key data or a PI-specific identifier. For details, see [Enable and Use Analytics on iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_analytics/mc_engagement_analytics_ios_implement.md). - Added time for iOS file protection transitions: Added a guarding mechanism that makes sure iOS file protection transitions are complete before the SDK completes configuration. To accommodate these transitions, the SDK waits up to 5 seconds, without blocking other functions. If the UIApplication’s `isProtectedDataAvailable` returns `NO`, then configuration fails. - Fixed Predictive Intelligence analytics issues: Fixed issues related to sending Predictive Intelligence analytics when using the MID configuration value. - Fixed location messaging issue: Resolved an issue where reloading location messages from the server displayed a message limited by the display settings again, contrary to the intended message setting. ### Version 6.0.1 _Released December 5, 2018._ - Analytics: Addressed an issue sending analytics to Predictive Intelligence when using the MID configuration value. - Networking: Reduced the number of network calls made to Engagement servers during the lifecycle of the SDK. ### Version 6.0.0 _Released October 22, 2018, correlating with the Marketing Cloud Engagement October 2018 release._ - Implemented Tenant Specific Endpoint support for Engagement Accounts: Configure new MobilePush applications to use account-specific settings. For information on configuring the SDK, see [Integrate the MobilePush iOS SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_integrate_ios/mc_engagement_integrate_ios.md). - Removed SDK-provided web view for URLs: To address potential security concerns, we removed the SDK’s default URL presenter. Consequently, if your message involves redirection to a web URL, resource, file, or other custom application schema driven by business logic, provide the SDK with a delegate and implementation of the `MarketingCloudSDKURLHandlingDelegate` protocol. For more information, see [Handling URLs and Custom Keys](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_handle_urls.md). - Removed the following SDK protocols and protocol methods: - `MarketingCloudSDKCloudPageMessagesNotificationHandlerDelegate` - `MarketingCloudSDKOpenDirectMessagesNotificationHandlerDelegate` - `MarketingCloudSDKInboxMessagesNotificationHandlerDelegate` **important:** Update your code to implement the `MarketingCloudSDKURLHandlingDelegate` protocol. - Inbox functionality improvements: - When an Alert+Inbox push notification arrives with the app in the foreground, inbox messages are reloaded from the server automatically. - Inbox message handling better tracks active messages in the inbox based on their start and end date values. - SDK Configuration: Added the `sfmc_configureWithDictionary:` method to configure the SDK via runtime values passed to SDK.
Version 5 Releases ### Version 5.2.1 _Released August 27, 2018, correlating with the Marketing Cloud Engagement July 2018 release._ Addressed issues related to multithreading and core data concurrency. ### Version 5.1.1 _Released July 31, 2018._ - Addressed issues related to multi-threading in the SDK - Updated the build process to include the i386 architecture, which allows you to run 32-bit simulators - Corrected an issue related to loading resources on armv7s devices ### Version 5.1.0 _Released July 23rd, 2018, correlating with the Marketing Cloud Engagement April 2018 release._ - Added iOS 9 support: The iOS MarketingCloudSDK framework now supports iOS 9. Use conditional coding via Apple’s available attributes. For notes on using conditional coding for push registration and handling push notifications, see the iOS 9 documentation. - Added synchronous configuration calls: To prevent developers from trying to set a contact key, tag, or attribute before configuration is complete, we added synchronous configuration calls to the API as the default. - Added data privacy compliance: This version of the iOS MarketingCloudSDK supports three privacy modes that can affect your application’s use of MobilePush: Right to be Forgotten, Restriction of Processing, and Don’t Track. These changes assist you in preparing for data compliance regulations, such as the European Union’s General Data Protection Regulation (GDPR). For more information, see [Data Protection and Privacy](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_data_protection_privacy.md). - Throttled inbox message calls: To match the Android SDK, we now prevent the iOS MarketingCloudSDK from calling `sfmc_refreshMessages` too often. Reference the headers for more information. - Allowed Predictive Intelligence to be set separately: When you configure the iOS MarketingCloudSDK, enable or disable Predictive Intelligence separately from Analytics. If your app uses the iOS MarketingCloudSDK version 5.0.0 framework with analytics enabled, then Predictive Intelligence is also enabled. To control Predictive Intelligence separately, add the `config` flag. - Improved registration: We improved registration to prevent duplicate tags and attributes. - Fixed `isPushEnabled` override issue: Previously, disabling push notifications in the Notification Center overrode the `setPushEnable` property. We fixed this issue so that the SDK uses `setPushEnable`. ### Version 5.2.0 _Released July 11, 2018, correlating with the Marketing Cloud Engagement July 2018 release._ - Added checks to prevent exceptions: Added `nil` checks to prevent potential exceptions that occur when users swipe to close an app. - Improved log string initializers: To help prevent Xcode Address Sanitizer warnings, we improved the SDK’s use of log string initializers. - Device ID migration: The SDK attempts to migrate the `deviceId` from versions of JB4ASDK 4.x.x, if possible. ### Version 5.0.0 _Released January 22, 2018, correlating with the Marketing Cloud Engagement January 2018 release._ - We redesigned the SDK to make it easier to integrate than ever before. This release includes a slimmer API that makes it easier to add Engagement features to your app. Existing users can upgrade their version to take advantage of the improved SDK. New users can follow the existing Getting Started directions to get the SDK up and running. - We updated the SDK for full support of iOS 11.
## Cordova This section contains information about releases of the Salesforce Marketing Cloud Cordova Plugin, including version numbers, compatibility details, and key changes. ### Latest Release - Version 8.1.1 - Fix for Open Direct link not working when app is in killed state for iOS.
View changelog for earlier releases ### Version 8.1.0 - Runtime Toggles – Enable and disable Analytics and Predictive Intelligence (PI) analytics at runtime. For more information, see the [Cordova Plugin API Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_development_frameworks/mc_engagement_development_frameworks_cordova_ref.md). - Android 14 support - Bug fixes and performance improvements ### Version 8.0.0 - Android 13 support - Integrated with the Engagement SDK, which includes support for mobile app events - Bug fixes and performance improvements ### Version 7.5.0 - Uses 7.4+ versions of the Android and iOS MobilePush SDK - Adds Behavioral Triggers for InApp messaging functionality. For more information, see `track()`. ### Version 7.4.3 - Uses 7.x versions of the Android and iOS MobilePush SDK - Fix Insecure Maven URL for downloading MobilePush SDK in Android ### Version 7.4.2 - Uses 7.x versions of the Android and iOS MobilePush SDK. - This plugin version requires Cordova Android 9.0.0 as the minimum version to build, which makes the minimum supported Android version as 5.1. - Added support to enable or disable Google Play Services Plugin and change its version change in the `config.xml` file. - Added `AndroidXEnabled` preference as `true`, since the MobilePush SDK for Android depends on these support libraries. ### Version 7.4.1 - Updated to the 7.4.x versions of the Android and iOS MobilePush SDK. - Fix for removing unnecessary Logcat statements on `newIntent()` flow in Android ### Version 7.4.0 - Updated to the 7.4.x version of the iOS MobilePush SDK. ### Version 7.3.0 - Updated to the 7.3.x versions of the Android and iOS MobilePush SDK. ### Version 7.2.0 - Updated to the 7.2.x versions of the Android and iOS MobilePush SDK. ### Version 7.1.0 - Updated to the 7.1.x versions of the Android and iOS MobilePush SDK. ### Version 7.0.0 - Updated to the 7.0.x versions of the Android and iOS MobilePush SDK. ### Version 6.4.0 - Updated to the 6.4.x versions of the Android and iOS MobilePush SDK. ### Version 6.3.1 - Added support for logging the SDK state to the native platform logging system. Uses Logcat in Android, and Console in iOS. - Added documentation for setting up push for iOS. ### Version 6.3.0 - Updated to the 6.3.x versions of the Android and iOS MobilePush SDK. - The plugin now uses CocoaPods for the iOS SDK integration. - Support In-App Messaging functionality of the MobilePush SDK. ### Version 6.2.1 - Updated to the 6.2.x versions of the Android and iOS MobilePush SDK. - Added support to delay registration until the contact key has been set. For more information, see the [Installation documentation](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_development_frameworks/mc_engagement_development_frameworks_cordova.md). - Require Tenant Specific Endpoint in the `config.xml` file. If a Tenant-Specific Endpoint isn’t specified, an exception is thrown. ### Version 6.1.0 - Updated to the 6.1.x versions of the Android and iOS MobilePush SDK. - Added support for listening to notification opened events, enabling you to act when a user clicks a notification, such as loading the url from an OpenDirect or CloudPages message. ### Version 6.0.0 In this release, we have greatly simplified the Cordova plugin for our MobilePush SDK. For successful implementations, if you’re upgrading from a prior release, we suggest following the integration instructions as if you were integrating a new plugin. All functionality of this plugin remains the same as the preceding versions. - The plugin version number now matches with the `major`.`minor` version of the SDK release. - The plugin is now published to npm for easier installation - The JavaScript API has been updated to allow for optional parameters where applicable. For more information, see [API Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_development_frameworks/mc_engagement_development_frameworks_cordova_ref.md). - Moved SDK configuration values from command-line arguments passed in while installing the SDK into the `config.xml` file. ### Version 1.1.0 _Released July 11, 2018_ For Android: Depends on Android Cordova platform 6.4.0. - Updated Android SDK to 5.6.x - Updated iOS SDK to 5.2.x ### Version 1.0.3 _Released April 23, 2018_ - For iOS: Depends on the MobilePush iOS SDK v5.1.x - For Android: Depends on the MobilePush Android SDK v5.5.x, the latest version of Cordova, and Android Cordova platform 6.4.0. - Added support for Cordova iOS cross-platform (CLI) workflow ### Version 1.0.2 _Released January 22, 2018_ - For iOS: Depends on the MobilePush iOS SDK v4.9.x - For Android: Depends on the MobilePush Android SDK v5.3.x, the latest version of Cordova, and Android Cordova platform 6.4.0. - Updated Android SDK to v5.3.+ ### Version 1.0.1 _Released November 29, 2017_ - Depends on the MobilePush iOS SDK v4.9.x - Depends on the MobilePush Android SDK v5.2.x - Updated Android SDK to v5.2.+ ### Version 1.0.0 _Released October 27, 2017_ - Depends on the MobilePush iOS SDK v4.9.x - Depends on the MobilePush Android SDK v5.0.x
## Flutter This section contains information about releases of the Salesforce Marketing Cloud Flutter plugin, including version numbers, compatibility details, and key changes. ### Latest Release - Version 9.0.1 - Fixed issue with the parsing of Inbox CustomKeys: Custom key values sent from Marketing Cloud are now correctly parsed and available in the Inbox message object. - Bug fixes and improvements.
View changelog for earlier releases ### Version 9.0.0 - Support for the 9.0.x versions of the Android and iOS MobilePush SDK. ### Version 8.2.0 - Added APIs that support persistent Inbox and combined Alert + Inbox messaging functionality - Bug fixes and improvements ### Version 8.1.0 - Depends on the 8.1.x versions of the Android and iOS MobilePush SDKs - Initial release
## React This section contains information about releases of the Salesforce Marketing Cloud React Native module, including version numbers, compatibility details, and key changes. ### Latest Release - Version 9.0.0 - Support for the 9.0.x versions of the Android and iOS MobilePush SDK.
View changelog for earlier releases ### Version 8.1.0 - Runtime Toggles – Enable and disable Analytics and PI analytics at runtime. For more information, refer to the [React Plugin API Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_development_frameworks/mc_engagement_development_frameworks_react_native_ref.md). - Android 14 support - Bug fixes and performance improvements ### Version 8.0.0 - Android 13 support - Integrated with the Engagement SDK, which includes support for mobile app events - Bug fixes and performance improvements ### Version 7.5.2 - Removed unit tests from released artifact. ### Version 7.5.1 - Android 12 support. Requires v7.4.3 of the Android SDK or higher. ### Version 7.5.0 - Using the 7.4.x versions of the Android MobilePush SDK. ### Version 7.4.3 - Using the 7.4.x versions of the Android MobilePush SDK. ### Version 7.4.2 - Using the 7.4.x versions of the Android MobilePush SDK. ### Version 7.4.0 - Using the 7.4.x versions of the iOS MobilePush SDK. ### Version 7.3.0 - Using the 7.3.x versions of the Android and iOS MobilePush SDK. ### Version 7.2.0 - Using the 7.2.x versions of the Android and iOS MobilePush SDK. ### Version 7.1.0 - Using the 7.1.x versions of the Android and iOS MobilePush SDK. ### Version 7.0.0 - Using the 7.0.x versions of the Android and iOS MobilePush SDK. ### Version 6.4.0 - Using the 6.4.x versions of the Android and iOS MobilePush SDK. ### Version 6.3.x - Initial release - Using the 6.3.x versions of the Android and iOS MobilePush SDK.
# Change Log This page lists the changes to the Mobile App Messaging SDK. ## Android This section contains information about releases of the Mobile App Messaging SDK for Android, including version numbers, release dates, compatibility details, and key changes. ### Version 1.1.1 _Released June 10, 2026_ Version 1.1.0 of the Android SDK has been tested with Firebase Cloud Messaging version 25.0.1. The minimum compatible Android API version is 26. The SDK is compiled with Android API version 36 and depends on Java version 17, Koltin version 2.2.21. - Performance improvements and bug fixes. - Hardening against an ART verifier exception (VerifyError) that could crash apps running JaCoCo-instrumented builds. See [Google Issue Tracker](https://issuetracker.google.com/issues/247932119) and [Jacoco Issue](https://github.com/jacoco/jacoco/issues/1381). ### Version 1.1.0 _Released March 30, 2026_ Version 1.1.0 of the Android SDK has been tested with Firebase Cloud Messaging version 25.0.1. The minimum compatible Android API version is 26. The SDK is compiled with Android API version 36 and depends on Java version 17, Koltin version 2.2.21. Version 1.1.0 of the SDK is a major release that includes: - In-App Messaging feature module. - Support for tracking Custom events defined in the Mobile App Messaging UI. - Faster event sending from the SDK to the Mobile App Messaging Platform and support for real-time sending of high-priority events. - Performance improvements and bug fixes. ### Version 1.0.0 _Released November 6, 2025_ Version 1.0.0 of the Android SDK has been tested with Firebase Cloud Messaging version 24.0.2. The minimum compatible Android API version is 26. The SDK is compiled with Android API version 36 and depends on Java version 17, Koltin version 1.9.22. Version 1.0.0 is an initial release and includes support for: - Mobile App Messaging in Marketing Cloud Next - Basic and Advanced Push Notifications ## iOS ### Version 2.0.0 _Released March 31, 2026_ Version 2.0.0 of the SDK is a major release that introduces the In-App Messaging feature module. The minimum compatible iOS API version is 12. - In-App Messaging feature support. - Support for tracking Custom events defined in the Mobile App Messaging UI. - Faster event sending from the SDK to the Mobile App Messaging Platform and support for real-time sending of high-priority events. - Performance improvements and bug fixes. - SFMC module version 4.0.0 (compatible with this module version 2.0.0 and above). - Extension SDK version 3.0.0 (compatible with this module version 2.0.0 and above). - Push Feature module version 2.0.0 (compatible with this module version 2.0.0 and above) - InAppMessaging Feature module version 1.0.0 (compatible with this module version 2.0.0 and above) ### Version 1.0.2 _Released February 25, 2026_ - Bug fixes and performance improvements. ### Version 1.0.1 _Released December 18, 2025_ - Fixed SPM dependency error for v1.0.0. - Changed arrow buttons for carousel. ### Version 1.0.0 _Released November 6, 2025_ Version 1.0.0 of the SDK is a major release that introduces a new unified SDK architecture. The minimum compatible iOS API version is 12. - Initial release, which provides support for Mobile App Messaging in Marketing Cloud Next. - Basic and Advanced Push Notifications. - SFMCSDK version 3.0.0 (compatible with Mobile App Messaging SDK version 1.0.0 and above). - Extension SDK version 2.0.0 (compatible with Mobile App Messaging SDK version 1.0.0 and above). - Push Feature SDK version 1.0.0 (compatible with Mobile App Messaging SDK version 1.0.0 and above). # Check Required Registration Fields If a registration is missing a required field, or if a required field contains an error, the registration is considered invalid. When a registration is invalid, the SDK sets the device that’s associated with the registration to an inactive or opted-out state. 1. To verify that the registration information is properly recorded, review how to test and validate registrations. **note:** Registrations are asynchronous. While the SDK can receive a successful `201` response from the server indicating that it received the registration, it can’t determine whether it successfully processed it. The SDK also can’t know whether the server marked the registration as invalid. This code sample shows an example of a registration request for a contact registered with v10.0.0 of the SDK. ```json { "push_Enabled": "true", "sdk_Version": "10.0.0", "tags": ["ALL", "DEBUG", "DISCOUNT", "IOS", "iPhone"], "etAppId": "995b5b1a-162c-4e5d-a4cf-ac5ddeb14e47", "device_Token": "80ef8671f34bd9acabb375031e3036f1cb906bd30c8bba2e24bd9e078ba2e14j", "hwid": "iPhone13", "location_Enabled": true, "uuid": "A7ADDDD7-63CF-4C3F-9442-7C34C299C88A", "app_Version": "10.0.0", "registrationDateUtc": "2025-11-20T12:46:48.335Z", "subscriberKey": "contactkey@example.com", "quietPushEnabled": false, "dST": false, "locale": "en_US", "deviceID": "DE0AEA79-955D-4941-96A5-C51853A4168B", "platform": "iOS", "timeZone": "19800", "registrationId": "DE0AEA79-955D-4941-96A5-C51853A4168B", "platform_Version": "18.5", "proximity_Enabled": true, "attributes": [ { "key": "CODE", "value": "FREE99" } ] } ``` For earlier versions of the SDK, use this code. ``` { "deviceID" : "1EB8C21D-CA72-41AC-930D-CEC9A311D699", "device_Token" : "t22wrs6vr221rr29r671412s5vwuruwwsu8s48rs274t7tr3s771w7t9v32vus41", "sdk_Version" : "8.0.8", "app_Version" : "32.1.4", "dST" : true, "location_Enabled" : true, "proximity_Enabled" : true, "push_Enabled" : true, "platform_Version" : "15.6", "timeZone" : "-14400", "quietPushEnabled" : false, "subscriberKey" : "contactkey@example.com", "platform" : "iOS", "hwid" : "iPhone13", "etAppId" : " 995k5k1j-162l-4n5m-j4lo-jl5mmnk14n47", "locale" : "en_US", "tags" : [ "ALL", "DEBUG", "DISCOUNT", "IOS" ], "attributes" : [ { "key" : "CODE", "value" : "FREE99" } "registrationId" : "1eb8c21d-ca72-41ac-930d-cec9a311d699", ], "language" : "en_US", } ``` This table lists the fields that Marketing Cloud Engagement uses when it registers contacts. | Field | Type | Description | | ------------------- | ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `access_token` | String | Required. The value that was provided when the app was created in Marketing Cloud Setup. The SDK was configured or initialized with this value. | | `deviceID` | String | Required. A random GUID that identifies a device, representing a unique installation of the app. | | `etAppId` | String | Required. A unique ID for the app that was created when the app was set up in Marketing Cloud. The SDK was configured or initialized with this value. | | `platform` | String | Required. The device’s operating system. Possible values are `iOS` and `Android`. | | `device_token` | String | The unique token that Apple or Google FCM returns to the SDK. To prevent implementation issues, don’t customize or interrupt the process by which the notification service returns the device token to the SDK. Tampering with the device token can invalidate it. The app must send a valid device token to Marketing Cloud for the device to receive push notifications. | | `push_enabled` | Boolean | Indicates whether the device or contact is eligible to receive push messages. If the value is `true`, the device or contact is opted in. Only opted-in contacts or devices receive push notifications. The default value is `true`. | | `subscriberKey` | String | The subscriber key for a user, which is captured or provided by the app. The key can contain up to 100 characters. If this value isn’t provided, a random GUID is generated. | | `attributes` | Array of key-value pairs | A set of attributes that apply to a contact. Before your app submits attributes, define the attribute keys in the MobilePush Demographics table in Contact Builder. If the attribute name that the SDK submits doesn't match the attribute name defined in Contact Builder, the entire registration is rejected. | | `dst` | Boolean | Indicates whether the device time zone honors daylight saving time. | | `timezone` | String | The time zone offset in seconds, as set by the app. | | `tags` | Array of strings | A set of labels used to group or segment which devices to send to. | | `platform_version` | String | The version of the device’s operating system | | `badge` | Integer | The current number displayed in a badge on the app icon (iOS only). Represents the number of unread messages. | | `sdk_version` | String | The version of the SDK integrated with the app. | | `app_version` | String | The version of the app that’s on the device. | | `location_enabled` | Boolean | Indicates whether the subscriber allows the app to track their location. If the value is `true`, the app can track the user’s location. | | `hwid` | String | A hardware identifier used to identify device model and type. | | `locale` | String | The locale code used by the device. | | `proximity_enabled` | Boolean | Indicates whether the subscriber allowed the app to range for beacons. If the value is `true`, the subscriber allowed ranging for beacons. | # Check Required Registration Fields A registration is considered invalid if it doesn’t contain all the required fields, or if there are errors in the required fields. If a registration is invalid, the device is set to an inactive or opted-out state. 1. To verify that the registration information is properly recorded, review how to test and validate registrations. **note:** Registrations are asynchronous. The SDK can receive a successful `201` response from the server, which indicates that it received the registration request. However, it can’t determine whether the server successfully processed the request or if it marked the registration as invalid. This code sample shows an example of a registration request. ```json { "mobileAppVersion": "10.0.0", "dateTimeInDevice": "2025-11-20T12:40:58.623Z", "deviceVersion": "18.5", "partyIdentificationName": "Testing-Name", "devicePlatform": "iPhone OS", "deviceId": "5784dd5a-053e-4d23-a05e-6abfbeb4dfb0", "locale": "en_US", "partyIdentificationNumber": "123456", "deviceModel": "iPhone13", "registrationId": "6241b7d1-8d42-4aa4-bbe9-7607cf7092b0", "deviceTimeZone": "Asia/Kolkata", "mobileAppName": "SDKExplorer", "eventId": "0fb1e9d5-9e92-4e95-82ec-5f5e4544d35c", "mobileAppId": "com.exacttarget.sdkx", "pushEnabled": true, "deviceSystemToken": "f3658491895d40c79377120332bb9b3dexample", "sdkVersion": "1.0.0", "partyIdentificationType": "Testing-iOS", "attributes": [ { "key": "CODE", "value": "FREE99" } ] } ``` # Check the Log Output The SDK uses extensive internal logging to record actions it performs for informational and diagnostic purposes. General logging is always enabled. The SDK also writes error and fault-level logs when certain conditions occur. Add this code to your app to enable logging. ::::::tabset{tabs='["SDK v8+", "SDK v7"]'} :::::tab ```swift // Turn on logging by selecting the logLevel (debug, warn or error). Debugging is not recommended for production apps. SFMCSdk.setLogger(logLevel: .debug) ``` ::::: :::::tab ```swift // turn on logging for debugging. Not recommended for production apps. // Set to true to enable logging while debugging MarketingCloudSDK.sharedInstance().sfmc_setDebugLoggingEnabled(true) ``` ::::: :::::: You can also enable logging with `CustomLogOutputter`, as shown in this example. ```swift class CustomLogOutputter: LogOutputter { override func out(level: LogLevel, subsystem: String, category: LoggerCategory, message: String) { // custom log outputting code } } // Then set the log level and custom log outputter SFMCSdk.setLogger(logLevel: .debug, logOutputter: CustomLogOutputter()) ``` ## Standard Log Output Alternatively, you can enable logging with a standard log output and a log filter, as shown in this example. ```swift SFMCSdk.setLogger(logLevel: .debug, logOutputter: LogOutputter(), filters: [.module, .identity]) ``` To clear previously set filtering options, use this code. ```swift SFMCSdk.clearLoggerFilters() ``` To query the state of debug-level logging, use this code. ```swift let enabled = MarketingCloudSDK.sharedInstance().sfmc_getDebugLoggingEnabled() ``` The SDK sends all logging output to Apple’s unified logging system. Review this information on the **Devices and Simulators** window in Xcode, or in the macOS Console app. If SDK debug logging is enabled, the SDK uses the `OS_LOG_TYPE_DEBUG` value. Disable logging before you submit a release build to the App Store. ## See Also - _Apple Developers_: [Logging](https://developer.apple.com/documentation/os/logging?language=objc) # Classes - [SFContentExtensionConfig](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfcontentextensionconfig.md) - [SFNotificationServiceConfig](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfnotificationserviceconfig.md) # Classes - [InAppMessagingFeature](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagingfeature.md) - [InAppMessagingFeatureConfigBuilder](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagingfeatureconfigbuilder.md) # Classes - [MobileAppMessaging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/mobileappmessaging.md) - [MobileAppMessagingConfigBuilder](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/mobileappmessagingconfigbuilder.md) # Classes - [MarketingCloudSdk](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/marketingcloudsdk.md) - [MarketingCloudSdkConfigBuilder](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/marketingcloudsdkconfigbuilder.md) # Classes - [PushFeature](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushfeature.md) - [PushFeatureConfigBuilder](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushfeatureconfigbuilder.md) # Classes - [CDP](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/cdp.md) - [ConfigBuilder](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/configbuilder.md) - [CustomEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/customevent.md) - [Identity](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/identity.md) - [InAppMessageCloseAction](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagecloseaction.md) - [LogOutputter](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/logoutputter.md) - [ModuleInitStatus](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/moduleinitstatus.md) - [PERSONALIZATION](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/personalization.md) - [SFMCSdk](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk.md) # clearAttribute Clears the value of an attribute in the registration. ## Syntax `MCCordovaPlugin.clearAttribute(key, [successCallback], [errorCallback])` ## Kind Static method of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | ----------------------- | ---------- | ---------------------------------------------------------------------------- | | `key` | `string` | The name of the attribute whose value must be cleared from the registration. | | `successCallback` | `function` | | | `successCallback.saved` | `boolean` | Whether the value of the `key` attribute was cleared from the registration. | | `errorCallback` | `function` | | ## See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/MarketingCloudSdk/8.0/-marketing%20-cloud%20-s-d-k/com.salesforce.marketingcloud.registration/-registration-manager/-editor/clear-attribute.html) - _SDK Reference for iOS_: [Identity Class](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/ios-sdk-v11/sfmc-sdk/classes/identity.md) # clearAttribute Removes a custom attribute from the device. ## Syntax ```dart Future clearAttribute(String key) ``` ## Parameters - `key` (String) - The attribute key to remove ## Returns - `Future` - Completes when the attribute has been cleared. ## Example ```dart try { await SfmcSdk.clearAttribute('userType'); print('Attribute cleared successfully'); } catch (e) { print('Failed to clear attribute: $e'); } ``` ## Related Methods - [getAttributes()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getAttributes.md) - [setAttribute()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_setAttribute.md) # clearAttribute Clears the value of an attribute in the registration. ## Syntax ```javascript MCReactModule.clearAttribute(key); ``` ## Parameters | Parameter | Type | Description | | --------- | -------- | ---------------------------------------------------------------------------- | | `key` | `string` | The name of the attribute whose value must be cleared from the registration. | ## Returns - `void` - No return value. ## Example ```javascript import { MCReactModule } from "react-native-marketingcloudsdk"; const clearUserAttribute = () => { try { MCReactModule.clearAttribute("userType"); console.log("Attribute cleared successfully"); } catch (error) { console.error("Error clearing attribute:", error); } }; ``` ## See Also - [getAttributes() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_getAttributes.md) - [setAttribute() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_setAttribute.md) # com.salesforce.marketingcloud ## Interfaces - [UrlHandler](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/interfaces/_UrlHandler.md) # com.salesforce.marketingcloud ## Classes - [InitializationStatus](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/_InitializationStatus.md) - [MarketingCloudConfig](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/_MarketingCloudConfig.md) - [MarketingCloudSdk](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/_MarketingCloudSdk.md) ## Interfaces - [MCLogListener](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/interfaces/_MCLogListener.md) # com.salesforce.marketingcloud - Classes This package contains 3 classes. ## Classes - [InitializationStatus](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/_InitializationStatus.md) - [MarketingCloudConfig](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/_MarketingCloudConfig.md) - [MarketingCloudSdk](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/_MarketingCloudSdk.md) # com.salesforce.marketingcloud - Interfaces This package contains 1 interface. ## Interfaces - [UrlHandler](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/_UrlHandler.md) # com.salesforce.marketingcloud - Interfaces This package contains 1 interface. ## Interfaces - [MCLogListener](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/_MCLogListener.md) # com.salesforce.marketingcloud.analytics ## Classes - [PiCart](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/analytics_PiCart.md) - [PiCartItem](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/analytics_PiCartItem.md) - [PiOrder](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/analytics_PiOrder.md) ## Interfaces - [AnalyticsManager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/interfaces/analytics_AnalyticsManager.md) # com.salesforce.marketingcloud.analytics - Classes This package contains 3 classes. ## Classes - [PiCart](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/analytics_PiCart.md) - [PiCartItem](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/analytics_PiCartItem.md) - [PiOrder](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/analytics_PiOrder.md) # com.salesforce.marketingcloud.analytics - Interfaces This package contains 1 interface. ## Interfaces - [AnalyticsManager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/analytics_AnalyticsManager.md) # com.salesforce.marketingcloud.inappmessaging.models ## Classes - [InAppMessage](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/inappmessaging-models_InAppMessage.md) # com.salesforce.marketingcloud.inappmessaging.models - Classes This package contains 1 class. ## Classes - [InAppMessage](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessaging-models_InAppMessage.md) # com.salesforce.marketingcloud.inappmessagingfeature ## Classes - [InAppMessageCloseAction](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/inappmessagingfeature_InAppMessageCloseAction.md) - [InAppMessagingFeature](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/inappmessagingfeature_InAppMessagingFeature.md) - [InAppMessagingFeatureInitializationStatus](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/inappmessagingfeature_InAppMessagingFeatureInitializationStatus.md) ## Interfaces - [InAppMessageManager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/interfaces/inappmessagingfeature_InAppMessageManager.md) - [WhenReadyListener](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/interfaces/inappmessagingfeature_WhenReadyListener.md) ## Enums - [InAppMessageCloseAction.InAppMessageDismissReason](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/enums/inappmessagingfeature_InAppMessageCloseAction.InAppMessageDismissReason.md) # com.salesforce.marketingcloud.inappmessagingfeature - Classes This package contains 3 classes. ## Classes - [InAppMessageCloseAction](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagingfeature_InAppMessageCloseAction.md) - [InAppMessagingFeature](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagingfeature_InAppMessagingFeature.md) - [InAppMessagingFeatureInitializationStatus](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagingfeature_InAppMessagingFeatureInitializationStatus.md) # com.salesforce.marketingcloud.inappmessagingfeature - Enums This package contains 1 enum. ## Enums - [InAppMessageCloseAction.InAppMessageDismissReason](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagingfeature_InAppMessageCloseAction.InAppMessageDismissReason.md) # com.salesforce.marketingcloud.inappmessagingfeature - Interfaces This package contains 2 interfaces. ## Interfaces - [InAppMessageManager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagingfeature_InAppMessageManager.md) - [WhenReadyListener](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagingfeature_WhenReadyListener.md) # com.salesforce.marketingcloud.inappmessagingfeature.config ## Classes - [InAppMessagingFeatureConfig](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/inappmessagingfeature-config_InAppMessagingFeatureConfig.md) # com.salesforce.marketingcloud.inappmessagingfeature.config - Classes This package contains 1 class. ## Classes - [InAppMessagingFeatureConfig](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagingfeature-config_InAppMessagingFeatureConfig.md) # com.salesforce.marketingcloud.location ## Classes - [LatLon](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/location_LatLon.md) # com.salesforce.marketingcloud.location - Classes This package contains 1 class. ## Classes - [LatLon](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/location_LatLon.md) # com.salesforce.marketingcloud.messages ## Classes - [Message](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/messages_Message.md) - [Region](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/messages_Region.md) ## Interfaces - [RegionMessageManager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/interfaces/messages_RegionMessageManager.md) # com.salesforce.marketingcloud.messages - Classes This package contains 2 classes. ## Classes - [Message](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/messages_Message.md) - [Region](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/messages_Region.md) # com.salesforce.marketingcloud.messages - Interfaces This package contains 1 interface. ## Interfaces - [RegionMessageManager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/messages_RegionMessageManager.md) # com.salesforce.marketingcloud.messages.geofence ## Classes - [GeofenceMessageResponse](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/messages-geofence_GeofenceMessageResponse.md) # com.salesforce.marketingcloud.messages.geofence - Classes This package contains 1 class. ## Classes - [GeofenceMessageResponse](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/messages-geofence_GeofenceMessageResponse.md) # com.salesforce.marketingcloud.messages.inbox ## Classes - [InboxMessage](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/messages-inbox_InboxMessage.md) - [InboxMessage.Media](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/messages-inbox_InboxMessage.Media.md) ## Interfaces - [InboxMessageManager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/interfaces/messages-inbox_InboxMessageManager.md) # com.salesforce.marketingcloud.messages.inbox - Classes This package contains 2 classes. ## Classes - [InboxMessage](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/messages-inbox_InboxMessage.md) - [InboxMessage.Media](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/messages-inbox_InboxMessage.Media.md) # com.salesforce.marketingcloud.messages.inbox - Interfaces This package contains 1 interface. ## Interfaces - [InboxMessageManager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/messages-inbox_InboxMessageManager.md) # com.salesforce.marketingcloud.messages.inbox.InboxMessage.Media **Package:** `com.salesforce.marketingcloud.messages.inbox` **Type:** Data Class **Platform:** androidJvm ## Description A data class representing media content associated with an inbox message in the Salesforce Marketing Cloud SDK. ## Declaration ```kotlin data class Media ``` ## Properties ### altText ```kotlin val altText: String? ``` Alternative text description for the media content. This property is nullable. --- ### url ```kotlin val url: String? ``` The URL location of the media resource. This property is nullable. # com.salesforce.marketingcloud.messages.proximity ## Classes - [ProximityMessageResponse](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/messages-proximity_ProximityMessageResponse.md) # com.salesforce.marketingcloud.messages.proximity - Classes This package contains 1 class. ## Classes - [ProximityMessageResponse](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/messages-proximity_ProximityMessageResponse.md) # com.salesforce.marketingcloud.mobileappmessaging ## Classes - [MobileAppMessaging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/mobileappmessaging_MobileAppMessaging.md) - [MobileAppMessagingConfig](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/mobileappmessaging_MobileAppMessagingConfig.md) - [MobileAppMessagingInitializationStatus](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/mobileappmessaging_MobileAppMessagingInitializationStatus.md) # com.salesforce.marketingcloud.mobileappmessaging - Classes This package contains 3 classes. ## Classes - [MobileAppMessaging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/mobileappmessaging_MobileAppMessaging.md) - [MobileAppMessagingConfig](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/mobileappmessaging_MobileAppMessagingConfig.md) - [MobileAppMessagingInitializationStatus](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/mobileappmessaging_MobileAppMessagingInitializationStatus.md) # com.salesforce.marketingcloud.mobileappmessaging.analytics ## Interfaces - [AnalyticsManager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/interfaces/mobileappmessaging-analytics_AnalyticsManager.md) # com.salesforce.marketingcloud.mobileappmessaging.analytics - Interfaces This package contains 1 interface. ## Interfaces - [AnalyticsManager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/mobileappmessaging-analytics_AnalyticsManager.md) # com.salesforce.marketingcloud.mobileappmessaging.registration ## Classes - [Registration](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/mobileappmessaging-registration_Registration.md) ## Interfaces - [RegistrationManager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/interfaces/mobileappmessaging-registration_RegistrationManager.md) # com.salesforce.marketingcloud.mobileappmessaging.registration - Classes This package contains 1 class. ## Classes - [Registration](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/mobileappmessaging-registration_Registration.md) # com.salesforce.marketingcloud.mobileappmessaging.registration - Interfaces This package contains 1 interface. ## Interfaces - [RegistrationManager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/mobileappmessaging-registration_RegistrationManager.md) # com.salesforce.marketingcloud.notifications ## Classes - [NotificationCustomizationOptions](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/notifications_NotificationCustomizationOptions.md) - [NotificationManager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/notifications_NotificationManager.md) - [NotificationMessage](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/notifications_NotificationMessage.md) - [ProximityNotificationCustomizer](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/notifications_ProximityNotificationCustomizer.md) - [PushNotificationActionHandler](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/notifications_PushNotificationActionHandler.md) # com.salesforce.marketingcloud.notifications - Classes This package contains 5 classes. ## Classes - [NotificationCustomizationOptions](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/notifications_NotificationCustomizationOptions.md) - [NotificationManager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/notifications_NotificationManager.md) - [NotificationMessage](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/notifications_NotificationMessage.md) - [ProximityNotificationCustomizer](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/notifications_ProximityNotificationCustomizer.md) - [PushNotificationActionHandler](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/notifications_PushNotificationActionHandler.md) # com.salesforce.marketingcloud.proximity ## Classes - [BeaconLogger](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/proximity_BeaconLogger.md) - [BeaconRegion](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/proximity_BeaconRegion.md) - [ProximityNotificationCustomizationOptions](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/proximity_ProximityNotificationCustomizationOptions.md) # com.salesforce.marketingcloud.proximity - Classes This package contains 3 classes. ## Classes - [BeaconLogger](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/proximity_BeaconLogger.md) - [BeaconRegion](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/proximity_BeaconRegion.md) - [ProximityNotificationCustomizationOptions](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/proximity_ProximityNotificationCustomizationOptions.md) # com.salesforce.marketingcloud.pushfeature ## Classes - [PushFeature](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushfeature_PushFeature.md) - [PushFeatureInitializationStatus](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushfeature_PushFeatureInitializationStatus.md) - [WhenReadyHandler](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushfeature_WhenReadyHandler.md) ## Interfaces - [InitializationListener](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/interfaces/pushfeature_InitializationListener.md) - [WhenReadyListener](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/interfaces/pushfeature_WhenReadyListener.md) # com.salesforce.marketingcloud.pushfeature - Classes This package contains 3 classes. ## Classes - [PushFeature](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushfeature_PushFeature.md) - [PushFeatureInitializationStatus](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushfeature_PushFeatureInitializationStatus.md) - [WhenReadyHandler](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushfeature_WhenReadyHandler.md) # com.salesforce.marketingcloud.pushfeature - Interfaces This package contains 2 interfaces. ## Interfaces - [InitializationListener](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushfeature_InitializationListener.md) - [WhenReadyListener](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushfeature_WhenReadyListener.md) # com.salesforce.marketingcloud.pushfeature.config ## Classes - [PushFeatureConfig](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushfeature-config_PushFeatureConfig.md) # com.salesforce.marketingcloud.pushfeature.config - Classes This package contains 1 class. ## Classes - [PushFeatureConfig](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushfeature-config_PushFeatureConfig.md) # com.salesforce.marketingcloud.pushfeature.notifications ## Classes - [NotificationCustomizationOptions](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushfeature-notifications_NotificationCustomizationOptions.md) - [NotificationManager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushfeature-notifications_NotificationManager.md) # com.salesforce.marketingcloud.pushfeature.notifications - Classes This package contains 2 classes. ## Classes - [NotificationCustomizationOptions](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushfeature-notifications_NotificationCustomizationOptions.md) - [NotificationManager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushfeature-notifications_NotificationManager.md) # com.salesforce.marketingcloud.pushfeature.push ## Classes - [IntentProvider](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushfeature-push_IntentProvider.md) - [PushMessageManager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushfeature-push_PushMessageManager.md) - [PushMessagingService](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushfeature-push_PushMessagingService.md) # com.salesforce.marketingcloud.pushfeature.push - Classes This package contains 3 classes. ## Classes - [IntentProvider](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushfeature-push_IntentProvider.md) - [PushMessageManager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushfeature-push_PushMessageManager.md) - [PushMessagingService](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushfeature-push_PushMessagingService.md) # com.salesforce.marketingcloud.pushmodels ## Classes - [Message](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushmodels_Message.md) - [NotificationMessage](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushmodels_NotificationMessage.md) - [Region](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushmodels_Region.md) - [PushKeys](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushmodels_PushKeys.md) # com.salesforce.marketingcloud.pushmodels - Classes This package contains 4 classes. ## Classes - [Message](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushmodels_Message.md) - [NotificationMessage](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushmodels_NotificationMessage.md) - [Region](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushmodels_Region.md) - [PushKeys](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushmodels_PushKeys.md) # com.salesforce.marketingcloud.pushmodels.data ## Classes - [Action](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushmodels-data_Action.md) - [Media](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushmodels-data_Media.md) - [Text](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushmodels-data_Text.md) ## Interfaces - [Style](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/interfaces/pushmodels-data_Style.md) - [Template](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/interfaces/pushmodels-data_Template.md) # com.salesforce.marketingcloud.pushmodels.data - Classes This package contains 3 classes. ## Classes - [Action](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushmodels-data_Action.md) - [Media](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushmodels-data_Media.md) - [Text](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushmodels-data_Text.md) # com.salesforce.marketingcloud.pushmodels.data - Interfaces This package contains 2 interfaces. ## Interfaces - [Style](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushmodels-data_Style.md) - [Template](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushmodels-data_Template.md) # com.salesforce.marketingcloud.pushmodels.exceptions ## Classes - [BadMediaException](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushmodels-exceptions_BadMediaException.md) - [InvalidCompressionException](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushmodels-exceptions_InvalidCompressionException.md) - [InvalidJsonException](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushmodels-exceptions_InvalidJsonException.md) - [MissingFieldException](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushmodels-exceptions_MissingFieldException.md) - [PushException](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushmodels-exceptions_PushException.md) - [UnknownErrorException](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushmodels-exceptions_UnknownErrorException.md) - [UnsupportedWidgetException](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushmodels-exceptions_UnsupportedWidgetException.md) ## Enums - [PushException.ErrorCode](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/enums/pushmodels-exceptions_PushException.ErrorCode.md) # com.salesforce.marketingcloud.pushmodels.exceptions - Classes This package contains 7 classes. ## Classes - [BadMediaException](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushmodels-exceptions_BadMediaException.md) - [InvalidCompressionException](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushmodels-exceptions_InvalidCompressionException.md) - [InvalidJsonException](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushmodels-exceptions_InvalidJsonException.md) - [MissingFieldException](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushmodels-exceptions_MissingFieldException.md) - [PushException](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushmodels-exceptions_PushException.md) - [UnknownErrorException](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushmodels-exceptions_UnknownErrorException.md) - [UnsupportedWidgetException](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushmodels-exceptions_UnsupportedWidgetException.md) # com.salesforce.marketingcloud.pushmodels.exceptions - Enums This package contains 1 enum. ## Enums - [PushException.ErrorCode](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushmodels-exceptions_PushException.ErrorCode.md) # com.salesforce.marketingcloud.pushmodels.location ## Classes - [LatLon](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushmodels-location_LatLon.md) # com.salesforce.marketingcloud.pushmodels.location - Classes This package contains 1 class. ## Classes - [LatLon](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushmodels-location_LatLon.md) # com.salesforce.marketingcloud.pushmodels.rich ## Classes - [RichFeatures](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushmodels-rich_RichFeatures.md) # com.salesforce.marketingcloud.pushmodels.rich - Classes This package contains 1 class. ## Classes - [RichFeatures](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushmodels-rich_RichFeatures.md) # com.salesforce.marketingcloud.pushmodels.rich.buttons ## Classes - [RichButtonTemplate](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushmodels-rich-buttons_RichButtonTemplate.md) - [RichButton](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushmodels-rich-buttons_RichButton.md) # com.salesforce.marketingcloud.pushmodels.rich.buttons - Classes This package contains 2 classes. ## Classes - [RichButtonTemplate](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushmodels-rich-buttons_RichButtonTemplate.md) - [RichButton](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushmodels-rich-buttons_RichButton.md) # com.salesforce.marketingcloud.pushmodels.rich.carousel ## Classes - [CarouselFullTemplate](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushmodels-rich-carousel_CarouselFullTemplate.md) - [CarouselFullTemplate.CarouselItem](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/pushmodels-rich-carousel_CarouselFullTemplate.CarouselItem.md) # com.salesforce.marketingcloud.pushmodels.rich.carousel - Classes This package contains 2 classes. ## Classes - [CarouselFullTemplate](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushmodels-rich-carousel_CarouselFullTemplate.md) - [CarouselFullTemplate.CarouselItem](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/pushmodels-rich-carousel_CarouselFullTemplate.CarouselItem.md) # com.salesforce.marketingcloud.registration ## Classes - [Registration](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/registration_Registration.md) ## Interfaces - [RegistrationManager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/interfaces/registration_RegistrationManager.md) # com.salesforce.marketingcloud.registration - Classes This package contains 1 class. ## Classes - [Registration](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/registration_Registration.md) # com.salesforce.marketingcloud.registration - Interfaces This package contains 1 interface. ## Interfaces - [RegistrationManager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/registration_RegistrationManager.md) # com.salesforce.marketingcloud.sfmcsdk ## Classes - [SFMCSdk](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk_SFMCSdk.md) - [SFMCSdkInitializationStatus](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk_SFMCSdkInitializationStatus.md) - [SFMCSdkModuleConfig](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk_SFMCSdkModuleConfig.md) ## Interfaces - [InitializationStatus](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/interfaces/sfmcsdk_InitializationStatus.md) - [SFMCSdkReadyListener](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/interfaces/sfmcsdk_SFMCSdkReadyListener.md) ## Enums - [InitializationState](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/enums/sfmcsdk_InitializationState.md) # com.salesforce.marketingcloud.sfmcsdk - Classes This package contains 3 classes. ## Classes - [SFMCSdk](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk_SFMCSdk.md) - [SFMCSdkInitializationStatus](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk_SFMCSdkInitializationStatus.md) - [SFMCSdkModuleConfig](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk_SFMCSdkModuleConfig.md) # com.salesforce.marketingcloud.sfmcsdk - Enums This package contains 1 enum. ## Enums - [InitializationState](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk_InitializationState.md) # com.salesforce.marketingcloud.sfmcsdk - Interfaces This package contains 2 interfaces. ## Interfaces - [InitializationStatus](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk_InitializationStatus.md) - [SFMCSdkReadyListener](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk_SFMCSdkReadyListener.md) # com.salesforce.marketingcloud.sfmcsdk.components.events ## Classes - [AddToCartEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_AddToCartEvent.md) - [CancelOrderEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_CancelOrderEvent.md) - [CartEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_CartEvent.md) - [CatalogEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_CatalogEvent.md) - [CatalogObject](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_CatalogObject.md) - [CommentCatalogEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_CommentCatalogEvent.md) - [DeliverOrderEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_DeliverOrderEvent.md) - [EngagementEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_EngagementEvent.md) - [Event](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_Event.md) - [EventManager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_EventManager.md) - [ExchangeOrderEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_ExchangeOrderEvent.md) - [FavoriteCatalogEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_FavoriteCatalogEvent.md) - [LineItem](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_LineItem.md) - [Order](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_Order.md) - [OrderEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_OrderEvent.md) - [PreorderEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_PreorderEvent.md) - [PurchaseOrderEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_PurchaseOrderEvent.md) - [QuickViewCatalogEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_QuickViewCatalogEvent.md) - [RemoveFromCartEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_RemoveFromCartEvent.md) - [ReplaceCartEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_ReplaceCartEvent.md) - [ReturnOrderEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_ReturnOrderEvent.md) - [ReviewCatalogEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_ReviewCatalogEvent.md) - [ShareCatalogEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_ShareCatalogEvent.md) - [ShipOrderEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_ShipOrderEvent.md) - [ViewCatalogDetailEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_ViewCatalogDetailEvent.md) - [ViewCatalogEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-events_ViewCatalogEvent.md) # com.salesforce.marketingcloud.sfmcsdk.components.events - Classes This package contains 26 classes. ## Classes - [AddToCartEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_AddToCartEvent.md) - [CancelOrderEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_CancelOrderEvent.md) - [CartEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_CartEvent.md) - [CatalogEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_CatalogEvent.md) - [CatalogObject](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_CatalogObject.md) - [CommentCatalogEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_CommentCatalogEvent.md) - [DeliverOrderEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_DeliverOrderEvent.md) - [EngagementEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_EngagementEvent.md) - [Event](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_Event.md) - [EventManager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_EventManager.md) - [ExchangeOrderEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_ExchangeOrderEvent.md) - [FavoriteCatalogEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_FavoriteCatalogEvent.md) - [LineItem](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_LineItem.md) - [Order](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_Order.md) - [OrderEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_OrderEvent.md) - [PreorderEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_PreorderEvent.md) - [PurchaseOrderEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_PurchaseOrderEvent.md) - [QuickViewCatalogEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_QuickViewCatalogEvent.md) - [RemoveFromCartEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_RemoveFromCartEvent.md) - [ReplaceCartEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_ReplaceCartEvent.md) - [ReturnOrderEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_ReturnOrderEvent.md) - [ReviewCatalogEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_ReviewCatalogEvent.md) - [ShareCatalogEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_ShareCatalogEvent.md) - [ShipOrderEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_ShipOrderEvent.md) - [ViewCatalogDetailEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_ViewCatalogDetailEvent.md) - [ViewCatalogEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-events_ViewCatalogEvent.md) # com.salesforce.marketingcloud.sfmcsdk.components.identity ## Classes - [AttributesEditor](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-identity_AttributesEditor.md) - [Identity](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-identity_Identity.md) - [IdentityEditor](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmcsdk-components-identity_IdentityEditor.md) # com.salesforce.marketingcloud.sfmcsdk.components.identity - Classes This package contains 3 classes. ## Classes - [AttributesEditor](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-identity_AttributesEditor.md) - [Identity](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-identity_Identity.md) - [IdentityEditor](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-identity_IdentityEditor.md) # com.salesforce.marketingcloud.sfmcsdk.components.logging ## Interfaces - [LogListener](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/interfaces/sfmcsdk-components-logging_LogListener.md) ## Enums - [LogLevel](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/enums/sfmcsdk-components-logging_LogLevel.md) # com.salesforce.marketingcloud.sfmcsdk.components.logging - Enums This package contains 1 enum. ## Enums - [LogLevel](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-logging_LogLevel.md) # com.salesforce.marketingcloud.sfmcsdk.components.logging - Interfaces This package contains 1 interface. ## Interfaces - [LogListener](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmcsdk-components-logging_LogListener.md) # CommentCatalogEvent ## Overview `CommentCatalogEvent` is a class in the Salesforce Marketing Cloud Unified SDK for Android that captures user comments on catalog objects. **Package:** `com.salesforce.marketingcloud.sfmcsdk.components.events` **Platform:** androidJvm **SDK Version:** 11.0.0 (SFMC SDK v3.1.0) --- ## Class Declaration ```kotlin class CommentCatalogEvent : CatalogEvent ``` --- ## Description An event to capture when a user comments on a catalog object. This event extends `CatalogEvent` and is used for tracking user engagement when they add comments to catalog items such as products, blog posts, or other trackable objects. --- ## Inheritance Hierarchy ``` Event └── EngagementEvent └── CatalogEvent └── CommentCatalogEvent ``` --- ## Inherited Properties ### From CatalogEvent #### catalogObject ```kotlin val catalogObject: CatalogObject ``` A property that holds the catalog object associated with this event. ### From EngagementEvent #### category ```kotlin open override var category: Event.Category ``` The Event category Name. Category contains list of allowed values. #### priority ```kotlin open override val priority: Priority ``` Defines the priority level for the event. --- ## Inherited Methods ### From EngagementEvent #### attributes() ```kotlin open override fun attributes(): Map ``` Returns a map of event attributes for this event. **Returns:** `Map` - The Event attributes for this event. #### name() ```kotlin open override fun name(): String ``` Returns the name for the event. This value must match the Event Name used when creating the event in the Marketing Cloud UI to trigger associated actions. **Returns:** `String` - The event name. --- ## Related Types ### CatalogObject The `catalogObject` property uses the `CatalogObject` class, which represents various items that can be tracked. **Constructor:** ```kotlin @JvmOverloads constructor( type: String, id: String, attributes: Map = mapOf(), relatedCatalogObjects: Map> = mapOf() ) ``` **Parameters:** - **type**: `String` - A type name representing the catalog object - **id**: `String` - A unique id representing the catalog object - **attributes**: `Map` - A map of user-supplied values (optional, defaults to empty map) - **relatedCatalogObjects**: `Map>` - A map of related catalog objects (optional, defaults to empty map) **Properties:** - `val type: String` - `val id: String` - `val attributes: Map` - `val relatedCatalogObjects: Map>` --- ## Sibling Classes Other classes that extend `CatalogEvent`: - `ViewCatalogEvent` - Captures when a user views a catalog object - `ViewCatalogDetailEvent` - Captures when a user views detailed catalog information - `QuickViewCatalogEvent` - Captures quick views of catalog items - `ShareCatalogEvent` - Captures catalog item sharing events - `ReviewCatalogEvent` - Captures catalog item review events - `FavoriteCatalogEvent` - Captures when users mark catalog objects as favorites ## Usage Notes As a sealed class hierarchy member, `CommentCatalogEvent` is part of a controlled type system for engagement events. The class inherits its core functionality from `CatalogEvent` and `EngagementEvent`, providing a standardized way to track user comment interactions with catalog objects in the Salesforce Marketing Cloud ecosystem. The event name returned by `name()` must match the Event Name configured in the Marketing Cloud UI to properly trigger associated actions and workflows. # Common ## Packages - [com.salesforce.marketingcloud](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud/_com-salesforce-marketingcloud_index.md) # Common Terminology The Mobile App Messaging SDK uses terminology that aligns with industry standards. - Anonymous Contact - : A contact that doesn’t have an explicitly set contact key. When an app user’s identity is unknown and the SDK doesn’t set a contact key, Marketing Cloud automatically assigns a randomly generated GUID (Globally Unique Identifier) as the contact key. Anonymous contacts are common when users first install an app, before they sign in or provide identifying information. When the app later identifies the user and sets a contact key, Marketing Cloud migrates the device registration to the new contact key. The original anonymous contact becomes an orphaned contact with no associated devices. - Asynchronous - : A type of request where the SDK waits only to see if the server received the API call, but doesn’t validate the request or return its status. To check the status of an asynchronous request later, issue a subsequent request. Because the Engagement SDK is installed in apps on billions of devices, we minimize contact between the SDK and Salesforce servers. As a result, the SDK primarily uses asynchronous, REST API calls for registration and analytics processes. The asynchronous nature of the SDK can lead to confusion around registration. If you use the SDK to register a contact attribute that isn’t formatted correctly, you can still receive a success response from the server. However, this response confirms only that the server successfully received the API call, not that it successfully processed it. In this scenario, the server attempts to process the registration and then rejects it. This rejection can result in the loss of critical information, such as contact key, device token, and other attributes contained in the registration. - Contact Attributes - : Key-value pairs that you can use to segment your audience and personalize your messages. Contact attributes serve as the common standard for segmentation and personalization across all channels. Examples of contact attributes include first name, last name, loyalty level, channel preference, signup date, birthday, postal code, or a unique identifier. Marketing Cloud Engagement stores these values in the MobilePush Demographics table within Contact Builder. Define these contact attributes in Contact Builder before the SDK assigns a value and registers the data with the Engagement server. Marketing Cloud Next stores contact attributes in the Individual data model object (DMO). - Device Token - : A unique token that identifies a user’s device. When a user opts into receiving push notifications from an app, their phone’s operating system generates the token and registers it with the SDK. The device token is similar to both an address and an access code. Apple and Google use the device token to route push notifications to the correct device and to track its validity, including the recipient’s opt status. - Initialization - : The process where the SDK begins to load its settings as the app starts up. For the Engagement SDK to function properly, it must complete the initialization process. The SDK’s initialization can start from the main thread, because its underlying implementation does its own processing on a separate initialization thread. - Local Contact Model - : A copy of the contact model stored by the SDK. The SDK uses this model to update the attributes in Marketing Cloud. The SDK sends registration requests asynchronously, so there isn’t a synchronization mechanism between the SDK and Marketing Cloud. - Registration - : The process where the SDK issues a REST API call to send critical information to Marketing Cloud Next or Marketing Cloud Engagement. The registration process facilitates the transfer of devices, contacts, device tokens, attributes, and similar information. This information determines whether Marketing Cloud can send a message to a contact. # ConfigBuilder `Class` ## Declaration ```swift @objc(SFMCSdkConfigBuilder) public class ConfigBuilder : NSObject override public init() @objc public func setCdp(config: ModuleConfig) -> ConfigBuilder @objc public func setEngagement(config: ModuleConfig) -> ConfigBuilder @objc public func setPersonalization(config: ModuleConfig) -> ConfigBuilder @objc public func setPushFeature(config: ModuleConfig) -> ConfigBuilder @objc public func setMAM(config: ModuleConfig) -> ConfigBuilder @objc public func setInAppMessagingFeature(config: ModuleConfig) -> ConfigBuilder @objc public func build() -> Config ``` ## Cases ### `init()` ```swift override public init() ``` --- ### `setCdp(config:)` Set Cdp Module ```swift @objc public func setCdp(config: ModuleConfig) -> ConfigBuilder ``` **Returns:** ConfigBuilder --- ### `setEngagement(config:)` Set Engagement Module ```swift @objc public func setEngagement(config: ModuleConfig) -> ConfigBuilder ``` **Returns:** ConfigBuilder --- ### `setPersonalization(config:)` Set Personalization Module Paramter config: Personalization Configuration ```swift @objc public func setPersonalization(config: ModuleConfig) -> ConfigBuilder ``` **Returns:** ConfigBuilder --- ### `setPushFeature(config:)` Set Push Feature Module ```swift @objc public func setPushFeature(config: ModuleConfig) -> ConfigBuilder ``` **Returns:** ConfigBuilder --- ### `setMAM(config:)` Set MobileAppMessaging Module ```swift @objc public func setMAM(config: ModuleConfig) -> ConfigBuilder ``` **Returns:** ConfigBuilder --- ### `setInAppMessagingFeature(config:)` Set InAppMessaging Feature Module ```swift @objc public func setInAppMessagingFeature(config: ModuleConfig) -> ConfigBuilder ``` **Returns:** ConfigBuilder --- ### `build()` Build SDK configuiration ```swift @objc public func build() -> Config ``` **Returns:** Config for the SDK --- # Configure Button and Carousel Actions Marketers can configure the action when an end user taps a button or a carousel image in a push notification. The actions for Web URL and App URL require that you implement `UrlHandler` as a new SDK initialization method. This example shows how to configure the SDK to handle button and carousel clicks in push messages. ```java SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { pushFeatureModuleConfig = PushFeatureConfig.builder().apply { // Other configuration values setUrlHandler(UrlHandler { context, url, _ -> PendingIntent.getActivity( context, Random().nextInt(), Intent(Intent.ACTION_VIEW, url.toUri()), PendingIntent.FLAG_UPDATE_CURRENT ) }) }.build() }) { // Handle initialization status } ``` # Configure Button and Carousel Actions for Android Push Notifications Marketers can configure the action when an end user taps a button or a carousel image in a push notification. The actions for Web URL and App URL require that you implement `UrlHandler` as a new SDK initialization method. This example shows how to configure the SDK to handle button and carousel clicks in push messages. ```java SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { pushModuleConfig = MarketingCloudConfig.builder().apply { setApplicationId("{mc_application_id}") setAccessToken("{mc_access_token}") setSenderId("{fcm_sender_id}") setMarketingCloudServerUrl("{marketing_cloud_url}") setMid("{mid}") setNotificationCustomizationOptions("{your instance of NotificationCustomizationOptions}") // Tell the SDK how to handle button & Carousel clicks in a Push Notification setUrlHandler(UrlHandler { context, url, _ -> PendingIntent.getActivity( context, Random().nextInt(), Intent(Intent.ACTION_VIEW, Uri.parse(url)), PendingIntent.FLAG_UPDATE_CURRENT ) }) // Other configuration options }.build(applicationContext) }) { // TODO handle initialization status } ``` # Configure Carousel Click Actions with the iOS Extension SDK Configure your app to specify what happens when a user taps a carousel image in a push notification. ## Prerequisites Before you configure carousel click actions, complete these steps to integrate the extension SDK into your app: 1. [Configure the Service Extension](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_integrate_ios_extension_configure_service.md) 2. [Configure the Content Extension](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_integrate_ios_extension_configure_content.md) 3. [Enable App Groups](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_integrate_ios_extension_enable_app_groups.md) ## Handle URL Actions When a carousel image has an associated URL action, tapping the image triggers the URL handling delegate in your app. Configure URL handling to respond to these tap events. For instructions on configuring URL handling, see [Customize Push Notification Functionality for iOS Apps](https://developer.salesforce.com/docs/marketing/mobilepush/guide/customize-push-notifications-ios.html#handle-urls). ## See Also - [Integrate the iOS Extension SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_integrate_ios_extension.md) # Configure Flutter for Android After you install the unified Flutter packages, finish setting up your Android development environment. ## Add the Marketing Cloud SDK Repository Add the Marketing Cloud Android SDK Maven repository to your project-level `android/build.gradle`. ``` allprojects { repositories { maven { url "https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/repository" } } } ``` ## Configure Firebase To provide Firebase Cloud Messaging credentials: 1. Add your `google-services.json` to `android/app/`. 2. Apply the Google Services plugin. 3. If your app initializes Firebase manually, make sure that Firebase is initialized before the SDK initialization. ## Initialize SDK in Application Startup Configure the SDK in your main application (`MainApplication.kt`) using the multi-module ConfigBuilder pattern. For detailed Android setup instructions, see [Integrate the Android SDK](https://developer.salesforce.com/docs/mc_next/mc_next_integrate_android/mc_next_integrate_android.md). ## Android SDK Versions | Android Artifact | Version | | ----------------------------- | ------- | | `sfmcsdk` | 3.1.+ | | `marketingcloudsdk` | 11.0.+ | | `pushfeaturemodule` | 2.0.+ | | `inappmessagingfeaturemodule` | 1.0.+ | | `mobileappmessagingsdk` | 1.1.+ | ## Next Step If your app provides cross-platform support, verify the iOS setup. - [Configure Flutter for iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/configure-flutter-ios.md) # Configure Flutter for iOS After you install the unified Flutter plugin packages, finish setting up your iOS development environment. ## Resolve Plugins Run `flutter pub get` from the project root first. This command generates `.flutter-plugins` and `.flutter-plugins-dependencies`, which CocoaPods needs to resolve plugin symlinks. ``` flutter pub get ``` ## Install Pods From your app's `ios` directory, install CocoaPods dependencies. ``` cd ios && pod install ``` ## Configure APNs Set up APNs in your Apple Developer account and upload credentials in Marketing Cloud Engagement setup. You can use either: - APNs authentication key (`.p8`) - APNs certificate (`.p12`) ## Configure SDK in App Startup Configure the SDK in your `AppDelegate.swift` using the multi-module ConfigBuilder pattern. For detailed SDK configurations, see [Configure iOS SDK](https://developer.salesforce.com/docs/mc_engagement/mc_engagement_integrate_ios/mc_engagement_integrate_ios_configure.md). ## Enable Push Capabilities In Xcode, enable: - Push Notifications - Background Modes with Remote Notifications For more information, see [Enable Push Notifications](https://developer.salesforce.com/docs/mc_next/mc_next_push_notifications/mc_next_push_notifications_ios_enable.md). ## iOS SDK Versions | iOS Pod | Version | | ---------------------------- | --------------- | | `MarketingCloud-SFMCSdk` | 4.0.0 or later | | `MarketingCloudSDK` | 11.0.0 or later | | `SFPushFeatureSDK` | 2.0.0 or later | | `SFInAppMessagingFeatureSDK` | 1.0.0 or later | | `SFMobileAppMessagingSDK` | 2.0.0 or later | # Configure Marketing Cloud Engagement Before you integrate the Salesforce Engagement SDK with your app, complete these steps to set up and configure Marketing Cloud Engagement. ## Prerequisites Before you begin, provision your app with Apple and Firebase. This step ensures that users of your apps receive push messages. For more information, see [Prerequisites](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/before-you-begin/engagement_sdk_guides_before_you_begin_prereqs.md). ## Provision User Access To set up your app, test messages, and review analytics in MobilePush, make sure that your user account has the necessary permissions. 1. In Marketing Cloud Engagement setup, go to **Administration** > **Users**. 2. Select a user. 3. Click **Manage Roles** > **Edit Permissions**. 4. In the MobilePush section of the permissions tree, select all checkboxes under **General**, **Message**, and **Reporting**. These permissions are required to set up your app, send messages, and review analytics. 5. In the Contact Builder section of the permissions tree, add the **access and view all contacts** permission. These permissions are required to test and verify registration information that is sent from the SDK and to review the MobilePush data model before sending attributes from the SDK. 6. In the Journey Builder section of the permissions tree, select all checkboxes under **General** and **Automation**. These permissions are required to test and verify messages in Journey Builder. 7. In the CloudPages section of the permissions tree, select all checkboxes under **General**. These permissions are required to create, test, and verify inbox messages. ## Create an App Ask your marketing admin to create an app in MobilePush, or create it yourself. 1. In Mobile Studio, on the MobilePush tab, select **Administration**. **note:** If you don’t see this option, you don’t have permission to administer MobilePush. Contact a Marketing Admin for assistance. 2. Click **Create New App** and complete the workflow. ![Create an app on MobilePush](https://developer.salesforce.com/media/quickstart/create-new-app-mobilepush.png '{"class": "image-xl"}') ## Retrieve Required SDK Configuration Data Ask your marketing admin to locate the following required SDK configuration data on your app’s administration page in MobilePush, or locate the information yourself. To connect your app to Marketing Cloud Engagement, add the configuration data from MobilePush to the SDK config file for your app. - App ID - Access token - App endpoint ![Retrieve Access Token, App ID, and App endpoint](https://developer.salesforce.com/media/quickstart/retrieve-sdk-configuration-data.png) - MID ![Retrieve MID](https://developer.salesforce.com/media/quickstart/retrieve-mid-mobilepush.png '{"class": "image-md"}') ## See Also - _Salesforce Help_: [MobilePush App Administration](https://help.salesforce.com/s/articleView?id=mktg.mc_overview_mobilepush_administration.htm) # Configure Push Delivery Analytics for Android The Salesforce Engagement SDK for Android tracks successful delivery of push notifications. To enable this feature, work with your Marketing Cloud admin. For more information, see [MobilePush Install, Inactive Devices, Push Delivery events](https://help.salesforce.com/s/articleView?id=mktg.mc_mobilepush_events.htm) # Configure Push Permission Authorization for In-App Messages on iOS Push Primers are a type of in-app message that educates users about the benefits of push notifications before requesting system-level permission. When a user taps the permission button in a Push Primer, the SDK triggers the standard iOS notification authorization request. Use this configuration to control which specific push notification permissions are requested when the user interacts with a Push Primer. For example, you can request only alerts and sounds while excluding badges, or customize the combination based on your app’s needs. To customize which permissions are requested, such as alerts, sounds, or badges, use the `setNotificationAuthorizationOptions` method during SDK initialization. If you don’t explicitly configure these options, the SDK requests permissions for alerts, sounds, and badges by default. This code example shows how to configure push permission authorization to request only alerts and sounds. ```swift func configureSdk() -> Bool { ... // Configure In-App Messaging Feature with custom authorization options let iamFeatureConfiguration = InAppMessagingFeatureConfigBuilder() .setEventDelegate(self) .setURLHandlingDelegate(self) .setInAppMessageFont(name: "HelveticaNeue") .setNotificationAuthorizationOptions([.alert, .sound]) .build() configBuilder = configBuilder .setInAppMessagingFeature(config: iamFeatureConfiguration) ... } ``` # Configure React Native for Android After installing React Native unified packages, complete Android setup. ## Add Repository and Dependencies Add the Marketing Cloud Android SDK Maven repository to your project `android/build.gradle`. ## Configure Firebase To provide Firebase Cloud Messaging credentials: 1. Add `google-services.json` to `android/app`. 2. Apply the Google Services plugin. 3. If your app initializes Firebase manually, make sure that Firebase is initialized before the SDK initialization. ## Initialize SDK in Application Startup Configure the SDK in your main application (`MainApplication.kt`) using the multi-module ConfigBuilder pattern. For detailed Android setup instructions, see [Integrate the Android SDK](https://developer.salesforce.com/docs/mc_next/mc_next_integrate_android/mc_next_integrate_android.md). ## Next Step If your app provides cross-platform support, verify the iOS setup. - [Configure React Native for iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/configure-react-native-ios.md) # Configure React Native for iOS After installing React Native unified plugin packages, complete iOS setup. ## Install Pods From your app's `ios` directory, install CocoaPods dependencies. ``` cd ios && pod install ``` ## Configure APNs Set up APNs in your Apple Developer account and upload credentials to your MobilePush (Marketing Cloud Engagement) administration configuration. You can use either: - APNs authentication key (`.p8`) - APNs certificate (`.p12`) ## Configure SDK in App Startup Configure the SDK in your AppDelegate.swift using the multi-module ConfigBuilder pattern. For detailed SDK configurations, see [Configure iOS SDK](https://developer.salesforce.com/docs/mc_engagement/mc_engagement_integrate_ios/mc_engagement_integrate_ios_configure.md). ## Enable Push Capabilities In Xcode, enable: - Push Notifications - Background Modes with Remote Notifications For more information, see [Enable Push Notifications](https://developer.salesforce.com/docs/mc_next/mc_next_push_notifications/mc_next_push_notifications_ios_enable.md). # Configure the Content Extension for the iOS Extension SDK Set up and configure the Notification Content Extension for use with the iOS Extension for the Salesforce Engagement SDK. ## Add a Content Extension Target The notification content extension is a bundle within your main app. To add a content extension target, complete these steps. 1. In Xcode, go to **File** > **New** > **Target**. 2. In the iOS > Application Extension section, select **Notification Content Extension**. 3. Click **Next**. 4. Configure the app extension and click **Finish**. 5. In the General Settings section for your project target, verify that the new extension is listed under **Frameworks, Libraries, and Embedded Content**. If it isn’t listed there, add it. **important:** Use the same Xcode-managed profile for the extension targets as the main project. Match the content extension version to the main app version whenever possible, and prefix the content extension bundle ID with the main app’s bundle ID. For example, if the main app’s bundle ID is `com.salesforce.MyAwesomeApp`, the content extension bundle ID can be `com.salesforce.MyAwesomeApp.MyContentExtension`. ## Integrate the Extension SDK with the Content Extension To integrate the iOS Extension with the Content Extension, add the dependencies to CocoaPods or Swift Package Manager (SPM). You can also add the dependencies manually. - [Integrate the SDK with CocoaPods](#integrate-the-extension-sdk-with-cocoapods) - [Integrate the SDK with Swift Package Manager (SPM)](#integrate-the-extension-sdk-with-swift-package-manager) - [Integrate the SDK Manually](#integrate-the-extension-sdk-manually) ### Integrate the Extension SDK with CocoaPods If you use CocoaPods to manage dependencies for your app, add the extension SDK to your Podfile. 1. Update your Podfile to include the extension SDK. ```swift target ‘’ do use_frameworks! pod ‘MarketingCloudSDK’ end target ‘’ do use_frameworks! pod ‘MarketingCloud-ExtensionSDK’ end ``` 2. In your project directory, run `pod install`. 3. Open the `.xcworkspace` file that CocoaPods generates. **important:** Don’t open the `.xcodeproj` file directly. Opening a project file instead of a workspace can lead to errors. For more information about updating Podfiles, see _Using CocoaPods_: [Adding pods to an Xcode project](https://guides.cocoapods.org/using/using-cocoapods.html) on the CocoaPods documentation site. ### Integrate the Extension SDK with Swift Package Manager If you use Swift Package Manager (SPM) to manage dependencies for your app, add the extension SDK to your project. 1. On the **Package Dependencies** tab of your project’s settings, click the plus sign (**+**) to add a package. 2. Search for the package `MCExtensionSDK` using the URL `https://github.com/salesforce-marketingcloud/extension-sdk-ios.git` 3. Select the package to include it in your app. ### Integrate the Extension SDK Manually If you don’t use CocoaPods or Swift Package Manager, add the extension packages manually. 1. Download the [MCExtensionSDK](https://github.com/salesforce-marketingcloud/extension-sdk-ios/releases/tag/v1.0.0). 2. Copy the `MCExtensionSDK` directory from your downloads folder to your project directory. **note:** To keep the binary in a different location, adjust the Framework Search Path (`FRAMEWORK_SEARCH_PATHS`) in your build settings. 3. In your project, select the Content Extension target. 4. In the General Settings for your project, in the **Frameworks, Libraries, and Embedded Content** section, add the `MCExtensionSDK` framework. ![](https://developer.salesforce.com/media/quickstart/configure-ext-ios-sdk-8.png) ## Inherit from SFMCNotificationViewController After you add the dependencies to your project, inherit the main class of the Content Extension from the `SFMCNotificationViewController` class. If your project is written in Swift, use this code to inherit the service. ```swift import UIKit import UserNotifications import UserNotificationsUI import MCExtensionSDK class NotificationViewController: SFMCNotificationViewController { } ``` If your project uses ObjectiveC, use this header. ```objc #import #import @interface NotificationViewController : SFMCNotificationViewController @end ``` In your ObjectiveC implementation file, use this code. ```objc #import "NotificationViewController.h" @implementation NotificationViewController @end ``` **warning:** `SFMCNotificationViewController` fully manages UI rendering. Don’t implement or override any `UIViewController` methods in the principal class of the content extension, as doing so can interfere with UI rendering. ## Configure Info.plist Settings Configure your content extension’s `Info.plist` file to register the correct notification category, build the rich push notification UI in code using the Extension SDK, and enable user interaction. These steps make sure that the content extension is correctly triggered and displays the intended rich UI as defined in Marketing Cloud Engagement. ### Set Up the Extension Category To set up and synchronize the notification category between your content extension’s `Info.plist` file and the Marketing Cloud Engagement UI: 1. Contact your Marketing Cloud Engagement admin to obtain the correct category name for the Rich UI template. 2. In your content extension’s `Info.plist` file, replace the value for `UNNotificationExtensionCategory` under `NSExtension > NSExtensionAttributes`. **warning:** iOS activates the content extension only if the category value in the push notification payload matches the one defined in `Info.plist > NSExtension > NSExtensionAttributes > UNNotificationExtensionCategory`. Make sure that the category value in Marketing Cloud Engagement matches the value in your content extension’s `Info.plist` file. Otherwise, the Carousel template won’t show. ### Build the UI Programmatically Unlike Apple’s auto-generated content extension template, `MCExtensionSDK` builds the notification UI programmatically instead of using an Interface Builder file. To modify the project to build the rich push notification UI entirely in code using the `MCExtensionSDK`: 1. Remove the storyboard reference by deleting the `NSExtensionMainStoryboard` item from `Info.plist > NSExtension`. 2. Add the `NSExtensionPrincipalClass` key to `Info.plist > NSExtension` - Value type: `String` - Value: `$(PRODUCT_MODULE_NAME).` **note:** For Objective-C projects, specify the class name directly. 3. Remove `MainInterface.storyboard` from your project. ### Enable User Interaction Add this key to your content extension’s `Info.plist` file: - Key: `UNNotificationExtensionUserInteractionEnabled` - Value type: Boolean - Value: `YES` ## Additional Configuration Options The `MCExtensionSDK` manages the content extension lifecycle. You can customize some of the ways the extension behaves: - Enabling or disabling logging and configuring log levels - Adjusting the HTTP request timeout ### Configure Logging and Timeout If your project is written in Swift, implement the `sfmcProvideConfig()` method to define custom log levels and HTTP timeout settings for the extension. ```swift import UIKit import UserNotifications import UserNotificationsUI import MCExtensionSDK class NotificationViewController: SFMCNotificationViewController { override func sfmcProvideConfig() -> SFContentExtensionConfig { var logLevel: LogLevel = .none #if DEBUG logLevel = .debug #endif return SFContentExtensionConfig(logLevel: logLevel, timeoutIntervalForRequest: 30.0) } } ``` If your project uses ObjectiveC, use the `sfmcProvideConfig` method to configure logging behavior and HTTP request timeout values for the extension. ```objc #import "NotificationViewController.h" @implementation NotificationViewController - (SFMCContentExtensionConfig *)sfmcProvideConfig { SFMCExtensionSdkLogLevel logLevel = SFMCExtensionSdkLogLevelNone; #if DEBUG logLevel = SFMCExtensionSdkLogLevelDebug; #endif return [[SFMCContentExtensionConfig alloc] initWithLogLevel:logLevel timeoutIntervalForRequest:30.0]; } @end ``` **note:** The default timeout for network requests is 15 seconds. Additionally, iOS blocks insecure (non-HTTPS) URLs by default. To allow loading Carousel images from HTTP URLs, configure an [exception](https://developer.apple.com/documentation/security/preventing-insecure-network-connections#Configure-Exceptions-Only-When-Needed-Prefer-Server-Fixes). # Configure the Content Extension for the iOS Extension SDK To show rich media notifications in your app, add and configure a content extension in your project. **note:** The configuration steps vary depending on your programming language. If you use Swift, click **View Swift code example** to expand the Swift example. If you use Objective-C, click **View Objective-C code example** to expand the Objective-C example. ## Add a Content Extension Target Notification Content Extensions run as separate processes within your app, providing isolation and enhancing security. 1. In Xcode, go to **File** > **New** > **Target**. 2. From the **iOS** > **Application Extension** section, select **Notification Content Extension**. 3. Click **Next**. 4. Provide a name and configure your extension settings. 5. Click **Finish**. 6. In the general settings for your target, verify that the **Frameworks, Libraries, and Embedded Content** section lists the new extension. If it isn't present, add it. ## Integrate the Extension SDK with Your Content Extension Integrate the `MCExtensionSDK` into your Content Extension by using the same process as the Service Extension. For detailed instructions, see [Integrate the Extension SDK with the Service Extension](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_integrate_ios_extension_configure_service.md#integrate-the-extension-sdk-with-the-service-extension). After you complete the integration, verify that your Content Extension’s target settings list the library in the **Frameworks, Libraries, and Embedded Content** section. ![The Frameworks, Libraries, and Embedded Content section for a project, showing the new extension highlighted.](https://developer.salesforce.com/media/quickstart/configure-ext-ios-sdk-8.png) ## Inherit from SFMCNotificationViewController Remove the provided sample code and inherit the main class of the Content Extension from `SFMCNotificationViewController`.
View Swift code example ```swift import UIKit import UserNotifications import UserNotificationsUI import MCExtensionSDK class NotificationViewController: SFMCNotificationViewController { } ```
View Objective-C code example **Header file** ```objc #import #import @interface NotificationViewController : SFMCNotificationViewController @end ``` **Implementation file** ```objc #import "NotificationViewController.h" @implementation NotificationViewController @end ```
**note:** `SFMCNotificationViewController` fully manages UI rendering. Don’t implement or override any `UIViewController` methods in the principal class of the content extension. ## Project and Info.plist Configuration Configure your project and content extension’s `Info.plist` file to register the notification category, build the UI programmatically, and turn on user interaction. ### Set Up the Extension Category Set up the notification category in your content extension’s `Info.plist` file to match the category in Marketing Cloud Next. 1. Work with your Marketing Admin to obtain the category name for your Rich UI template. 2. In your content extension’s `Info.plist` file, set the value for `UNNotificationExtensionCategory` under `NSExtension > NSExtensionAttributes`. ### Build the UI Programmatically The `MCExtensionSDK` builds the notification UI programmatically. Configure your project to build the UI in code. 1. Remove the storyboard reference by deleting the `NSExtensionMainStoryboard` item from `Info.plist > NSExtension`. 2. Add the `NSExtensionPrincipalClass` key to `Info.plist > NSExtension` - Value type: `String` - Value: `$(PRODUCT_MODULE_NAME).` **note:** For Objective-C projects, specify the class name directly. 3. Remove `MainInterface.storyboard` from your project. ### Turn On User Interaction Add this key to your content extension’s `Info.plist` file. - Key: `UNNotificationExtensionUserInteractionEnabled` - Value type: Boolean - Value: `YES` This screenshot illustrates an `Info.plist` file in a Swift-based implementation with configured `NSExtensionAttributes` and `NSExtensionPrincipalClass`. ![The details of the Info.plist file for a Swift-based implementation with configured NSExtensionAttributes and NSExtensionPrincipalClass](https://developer.salesforce.com/media/quickstart/configure-ext-ios-sdk-9.png) This screenshot illustrates an `Info.plist` file in an Objective-C-based implementation with configured `NSExtensionAttributes` and `NSExtensionPrincipalClass`. ![The details of the Info.plist file for an Objective-C-based implementation with configured NSExtensionAttributes and NSExtensionPrincipalClass](https://developer.salesforce.com/media/quickstart/configure-ext-ios-sdk-10.png) ## Other Configuration Steps Implement the `sfmcProvideConfig()` method to define custom log levels and HTTP timeout settings.
View Swift code example ```swift import UIKit import UserNotifications import UserNotificationsUI import MCExtensionSDK class NotificationViewController: SFMCNotificationViewController { override func sfmcProvideConfig() -> SFContentExtensionConfig { var logLevel: LogLevel = .none #if DEBUG logLevel = .debug #endif return SFContentExtensionConfig(logLevel: logLevel, timeoutIntervalForRequest: 30.0) } } ```
View Objective-C code example ```objc #import "NotificationViewController.h" @implementation NotificationViewController - (SFMCContentExtensionConfig *)sfmcProvideConfig { SFMCExtensionSdkLogLevel logLevel = SFMCExtensionSdkLogLevelNone; #if DEBUG logLevel = SFMCExtensionSdkLogLevelDebug; #endif return [[SFMCContentExtensionConfig alloc] initWithLogLevel:logLevel timeoutIntervalForRequest:30.0]; } ```
**note:** iOS blocks insecure (non-HTTPS) URLs by default. To load carousel images from HTTP URLs, configure an [exception](https://developer.apple.com/documentation/security/preventing-insecure-network-connections#Configure-Exceptions-Only-When-Needed-Prefer-Server-Fixes). # Configure the Cordova Plugin for Android Apps After you install and configure the Cordova plugin, configure it to enable push support for the Android platform. ## Prerequisites Before you configure the Cordova plugin for Android apps, make sure that the plugin is installed and configured for your app. See [Marketing Cloud Cordova Plugin](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_development_frameworks_cordova.md). ## Configure the Plugin To enable push support for the Android platform, provide your Firebase Cloud Messaging (FCM) credentials by including the `google-services.json` file in your `config.xml` file. 1. Download the `google-services.json` file for your app from the [Firebase console](https://console.firebase.google.com/). 2. Place the `google-services.json` file in your project’s root folder. 3. In the `config.xml` file for your app, add this code to the `Android` element. ```xml ``` ## See Also - [Configure the Cordova Plugin for iOS Apps](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_development_frameworks_cordova_ios.md) # Configure the Cordova Plugin for Android Apps After you install and configure the Cordova plugin, configure the plugin to enable push support for the Android platform. ## Prerequisites Before you configure the Cordova plugin for Android apps, make sure that the plugin is installed and configured for your app. See [Marketing Cloud Cordova Plugin](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_development_frameworks_cordova.md). At the command line, run these commands to install Cocoapods and update the repository. ```bash sudo gem install cocoapods pod repo update ``` ## Set the Deployment Target Apple requires all third-party frameworks to include a privacy manifest. Versions 8.1.2 and later of the Engagement SDK feature a signed framework and a privacy manifest that meet this requirement. To ensure compatibility with the privacy manifest in versions 8.1.2 and later, your app must support a deployment target of iOS 12 or later. To update the deployment target, complete these steps. **note:** Completing these steps removes support for iOS 11.0 and earlier. 1. Open the `config.xml` file for your app in an editor. 2. Update the `deployment-target` to include this code. ```xml ``` 3. At the command line, run this command to remove and then add the iOS platform. ```shell cordova platform remove ios cordova platform add ios ``` ## Enable Rich Notifications for iOS Rich notifications include images, videos, titles and subtitles from Marketing Cloud. Rich notifications can include personalization in the title, subtitle, or body of your message. To enable rich notifications, follow these steps. 1. In Xcode, click **File** > **New** > **Target**. 2. Select **Notification Service Extension**. 3. Name and save the new extension. **note:** Perform these steps every time you add the platform to your Cordova app. This service extension checks for a `"_mediaUrl"` element in `request.content.userInfo`. If it’s present, the extension attempts to download media from the URL, creates a thumbnail-size version, and then adds the attachment. Additionally, the service extension also checks for a `"_mediaAlt"` element in `request.content.userInfo`. If this key is found, the service extension uses the element for the body text, in case there are any problems downloading or creating the media attachment. A service extension can timeout if it can’t download media. In this example, the service extension delivers the original content but replaces the body text with the value from `"_mediaAlt"`. ``` #import #import "NotificationService.h" @interface NotificationService () @property(nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver); @property(nonatomic, strong) UNMutableNotificationContent *modifiedNotificationContent; @end @implementation NotificationService - (UNNotificationAttachment *)createMediaAttachment:(NSURL *)localMediaUrl { // options: specify what cropping rectangle of the media to use for a thumbnail // whether the thumbnail is hidden or not UNNotificationAttachment *mediaAttachment = [UNNotificationAttachment attachmentWithIdentifier:@"attachmentIdentifier" URL:localMediaUrl options:@{ UNNotificationAttachmentOptionsThumbnailClippingRectKey : (NSDictionary *)CFBridgingRelease( CGRectCreateDictionaryRepresentation(CGRectZero)), UNNotificationAttachmentOptionsThumbnailHiddenKey : @NO } error:nil]; return mediaAttachment; } - (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent *_Nonnull))contentHandler { // save the completion handler we will call back later self.contentHandler = contentHandler; // make a copy of the notification so we can change it self.modifiedNotificationContent = [request.content mutableCopy]; // alternative text to display if there are any issues loading the media URL NSString *mediaAltText = request.content.userInfo[@"_mediaAlt"]; // does the payload contains a remote URL to download or a local URL? NSString *mediaUrlString = request.content.userInfo[@"_mediaUrl"]; NSURL *mediaUrl = [NSURL URLWithString:mediaUrlString]; // if we have a URL, try to download media (i.e., // https://media.giphy.com/media/3oz8xJBbCpzG9byZmU/giphy.gif) if (mediaUrl != nil) { // create a session to handle downloading of the URL NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; // start a download task to handle the download of the media __weak __typeof__(self) weakSelf = self; [[session downloadTaskWithURL:mediaUrl completionHandler:^(NSURL *_Nullable location, NSURLResponse *_Nullable response, NSError *_Nullable error) { BOOL useAlternateText = YES; // if the download succeeded, save it locally and then make an attachment if (error == nil) { if (200 <= ((NSHTTPURLResponse *)response).statusCode && ((NSHTTPURLResponse *)response).statusCode <= 299) { // download was successful, attempt save the media file NSURL *localMediaUrl = [NSURL fileURLWithPath:[location.path stringByAppendingString:mediaUrl .lastPathComponent]]; // remove any existing file with the same name [[NSFileManager defaultManager] removeItemAtURL:localMediaUrl error:nil]; // move the downloaded file from the temporary location to a new file if ([[NSFileManager defaultManager] moveItemAtURL:location toURL:localMediaUrl error:nil] == YES) { // create an attachment with the new file UNNotificationAttachment *mediaAttachment = [weakSelf createMediaAttachment:localMediaUrl]; // if no problems creating the attachment, we can use it if (mediaAttachment != nil) { // set the media to display in the notification weakSelf.modifiedNotificationContent.attachments = @[ mediaAttachment ]; // everything is ok useAlternateText = NO; } } } } // if any problems creating the attachment, use the alternate text if provided if ((useAlternateText == YES) && (mediaAltText != nil)) { weakSelf.modifiedNotificationContent.body = mediaAltText; } // tell the OS we are done and here is the new content weakSelf.contentHandler(weakSelf.modifiedNotificationContent); }] resume]; } else { // see if the media URL is for a local file (i.e., file://movie.mp4) BOOL useAlternateText = YES; if (mediaUrlString != nil) { // attempt to create a URL to a file in local storage NSURL *localMediaUrl = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:mediaUrlString.lastPathComponent .stringByDeletingLastPathComponent ofType:mediaUrlString.pathExtension]]; // is the URL a local file URL? if (localMediaUrl != nil && localMediaUrl.isFileURL == YES) { // create an attachment with the local media UNNotificationAttachment *mediaAttachment = [self createMediaAttachment:localMediaUrl]; // if no problems creating the attachment, we can use it if (mediaAttachment != nil) { // set the media to display in the notification self.modifiedNotificationContent.attachments = @[ mediaAttachment ]; // everything is ok useAlternateText = NO; } } } // if any problems creating the attachment, use the alternate text if provided if ((useAlternateText == YES) && (mediaAltText != nil)) { self.modifiedNotificationContent.body = mediaAltText; } // tell the OS we are done and here is the new content contentHandler(self.modifiedNotificationContent); } } - (void)serviceExtensionTimeWillExpire { // Called just before the extension will be terminated by the system. // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the // original push payload will be used. // we took too long to download the media URL, use the alternate text if provided NSString *mediaAltText = self.modifiedNotificationContent.userInfo[@"_mediaAlt"]; if (mediaAltText != nil) { self.modifiedNotificationContent.body = mediaAltText; } // tell the OS we are done and here is the new content self.contentHandler(self.modifiedNotificationContent); } @end ``` # Configure the Flutter Plugin for Android Apps After you install and configure the Flutter plugin, configure it to enable push support for the Android platform. **important:** For new Flutter integrations, use the [Unified Flutter Setup](https://developer.salesforce.com/docs/marketing/unified_modules/hybrid-frameworks/flutter/flutter-setup.md), which works with both Marketing Cloud Engagement and Marketing Cloud Next. This topic is intended for customers who use the existing Flutter plugin for Marketing Cloud Engagement. The implementation steps vary depending on your app and the Flutter version it uses. ## Prerequisites Install and configure the Flutter plugin. See [Marketing Cloud Flutter Plugin](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_development_frameworks_flutter.md). ## Add the SDK Repository To add the SDK repository to your project, add this code to your `android/build.gradle` file. ```groovy allprojects { repositories { maven { url "https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/repository" } } } ``` ## Add the MarketingCloud SDK Dependency To add the `marketingcloudsdk` dependency to your project, add this code to your `android/app/build.gradle` file. ```groovy dependencies { implementation "com.salesforce.marketingcloud:marketingcloudsdk:9.0.+" } ``` ## Update Compile and Minimum Android SDK Versions In your app’s `build.gradle` file, set the SDK version parameters to the versions listed in this table. | Parameter | Version | | ----------------------------------- | ------- | | `compileSdk` or `compileSdkVersion` | `35` | | `minSdkVersion` | `23` | ## Update Kotlin Version Ensure the `org.jetbrains.kotlin.android` or `org.jetbrains.kotlin:kotlin-gradle-plugin` plugin is version `1.9.10` or later. **important:** Depending on your Flutter implementation, the location for specifying the Kotlin version can differ. You can specify the Kotlin version in either `android/build.gradle` or `android/settings.gradle`. ### Provide Firebase Cloud Messaging Credentials To enable push support for the Android platform, provide your Firebase Cloud Messaging (FCM) credentials by including the `google-services.json` file in your `config.xml` file. 1. Download the `google-services.json` file from your application’s [Firebase console](https://console.firebase.google.com/) and place it in your project’s `android/app` directory 2. To include the Google Services plugin, add this code to your `android/settings.gradle` file. ``` pluginManagement { buildscript { repositories { mavenCentral() } dependencies { classpath 'com.google.gms:google-services:4.3.2' } } } ``` **note:** If `pluginManagement` isn’t present in your `settings.gradle`, add this dependency in `android/build.gradle` under the `buildscript` section. If the Gradle file doesn't have a `buildscript` section, add it. 3. To apply the plugin, add this code to your `android/app/build.gradle` file. **note:** This step can vary depending on your implementation. ``` plugins { id "com.google.gms.google-services" } ``` If the `plugins` section doesn’t exist in your `android/app/build.gradle` file, add this code to the end of the file. ``` // Add the google services plugin to your build.gradle file apply plugin: 'com.google.gms.google-services' ``` ## Update `MainApplication.kt` **note:** If `MainApplication.kt` isn’t present in your app, create it by extending the `FlutterApplication` class. Additionally, update `AndroidManifest.xml`. ``` // add ".MainApplication" entry in main/AndroidManifest.xml ``` Update `MainApplication.kt` in your app. ``` //MainApplication.kt //YOUR_package //rest of imports... import android.util.Log import com.salesforce.marketingcloud.MarketingCloudConfig import com.salesforce.marketingcloud.notifications.NotificationCustomizationOptions import com.salesforce.marketingcloud.sfmcsdk.InitializationStatus import com.salesforce.marketingcloud.sfmcsdk.SFMCSdk import com.salesforce.marketingcloud.sfmcsdk.SFMCSdkModuleConfig import io.flutter.app.FlutterApplication class MainApplication : FlutterApplication() { //Update onCreate override fun onCreate() { super.onCreate() SFMCSdk.configure( applicationContext, SFMCSdkModuleConfig.build { pushModuleConfig = MarketingCloudConfig.builder() .apply { //Update these details based on your MC config setApplicationId("{MC_APP_ID}") setAccessToken("{MC_ACCESS_TOKEN}") setMarketingCloudServerUrl("{MC_APP_SERVER_URL}") setSenderId("{FCM_SENDER_ID_FOR_MC_APP}") setNotificationCustomizationOptions( NotificationCustomizationOptions.create( R.mipmap.ic_launcher ) ) } .build(applicationContext) } ) { initStatus -> when (initStatus.status) { InitializationStatus.SUCCESS -> Log.d("SFMC", "SFMC SDK Initialization Successful") InitializationStatus.FAILURE -> Log.d("SFMC", "SFMC SDK Initialization Failed") else -> Log.d("SFMC", "SFMC SDK Initialization Status: Unknown") } } //rest of onCreate... } //rest of MainApplication... } ``` To customize push functionality, see [Customize Push Notification Functionality for Android Apps](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_push_notifications/mc_engagement_push_notifications_android_customize.md). To implement the Carousel and Button actions features introduced in Android SDK version 9.0.0, see [Configure Button and Carousel Actions](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_push_notifications/mc_engagement_push_notifications_android_button_carousel.md). ### Declare Notification Permission Update `AndroidManifest.xml` to declare the notification permission. ``` //AndroidManifest.xml //Add this line to declare the notification permission. ... ``` ## Handle URLs The SDK doesn’t automatically present URLs from these sources. - CloudPages URLs from push notifications - OpenDirect URLs from push notifications - Action URLs from in-app messages To handle URLs from push notifications, follow these steps. Navigate to `MainApplication.kt` and update `setNotificationCustomizationOptions` to include the code in this example. 1. Open `MainApplication.kt` in an editor. 2. In the `setNotificationCustomizationOptions` section, add these `import` statements. ``` import android.app.PendingIntent import android.content.Context import android.content.Intent import android.net.Uri import android.os.Build import com.salesforce.marketingcloud.notifications.NotificationManager import com.salesforce.marketingcloud.notifications.NotificationMessage import java.util.Random ``` 3. Update `setNotificationCustomizationOptions` in `MarketingCloudConfig`. ``` //MainApplication.kt setNotificationCustomizationOptions(NotificationCustomizationOptions.create { context: Context, notificationMessage: NotificationMessage -> NotificationManager.createDefaultNotificationChannel(context).let { channelId -> NotificationManager.getDefaultNotificationBuilder( context, notificationMessage, channelId, R.mipmap.ic_launcher ).apply { setContentIntent( NotificationManager.redirectIntentForAnalytics( context, getPendingIntent(context, notificationMessage), notificationMessage, true ) ) } } }) ``` 4. Implement these methods in `MainApplication.kt`. ``` //MainApplication.kt private fun provideIntentFlags(): Int { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE } else { PendingIntent.FLAG_UPDATE_CURRENT } } private fun getPendingIntent( context: Context, notificationMessage: NotificationMessage ): PendingIntent { val intent = if (notificationMessage.url.isNullOrEmpty()) { context.packageManager.getLaunchIntentForPackage(context.packageName) } else { Intent(Intent.ACTION_VIEW, Uri.parse(notificationMessage.url)) } return PendingIntent.getActivity(context, Random().nextInt(), intent, provideIntentFlags()) } ``` ### Handle URLs from In-App messages To handle URLs from in-app messages, set the `setUrlHandler` in `MarketingCloudConfig` as shown in this example. ``` //MainApplication.kt // Add import statement for UrlHandler import com.salesforce.marketingcloud.UrlHandler // Tell the SDK how to handle button clicks in an IAM setUrlHandler(UrlHandler { context, url, _ -> PendingIntent.getActivity( context, Random().nextInt(), Intent(Intent.ACTION_VIEW, Uri.parse(url)), PendingIntent.FLAG_UPDATE_CURRENT ) }) ``` Additionally, review the additional documentation on [URL Handling for Android](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/sdk-implementation/url-handling.html). ## Troubleshoot Your Android Setup If you encounter errors related to Java sealed classes or dexing, add the `r8` dependency to your app. For more information about this error, see [Google’s IssueTracker](https://issuetracker.google.com/issues/290412574). To add the `r8` dependency, update your app’s `settings.gradle` file. **note:** If you don’t have `pluginManagement` in your `settings.gradle` file, update the `buildscript.dependencies` section of the `android/build.gradle` file. ``` pluginManagement { buildscript { repositories { mavenCentral() } dependencies { //Add the r8 dependency classpath 'com.android.tools:r8:8.2.42' //other dependencies } } // rest of settings.gradle } ``` # Configure the Flutter Plugin for iOS Apps After you install and configure the Flutter plugin for the Salesforce Engagement SDK, configure the plugin to enable push support for the iOS platform. **important:** For new Flutter integrations, use the [Flutter Unified Plugin Setup](https://developer.salesforce.com/docs/marketing/unified_modules/hybrid-frameworks/flutter/flutter-setup.md), which works with both Marketing Cloud Engagement and Marketing Cloud Next. This topic is intended for customers who use the Flutter plugin for Marketing Cloud Engagement. ## Prerequisites Install the dependencies for the SDK. See [Integrate the SDK for iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_integrate_ios/mc_engagement_integrate_ios.md). Install the Flutter plugin. See [Marketing Cloud Flutter Plugin](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_development_frameworks_flutter.md). ## Enable Push Notifications Enable push notifications in the **Capabilities** settings for your target in Xcode. ![Enable Push](https://developer.salesforce.com/media/overview/enable-push-ios-apps.png) ## Update the `AppDelegate` 1. Navigate to the `YOUR_APP/ios` directory and open `Runner.xcworkspace`. 2. To configure the SDK and enable push, update `AppDelegate`.
View Swift code example ```swift //AppDelegate.swift import UIKit import Flutter // The SFMCSDK module is included in the dependency packages for the SDK. Don't install it // separately or list it in your podfile. import SFMCSDK import MarketingCloudSDK func setupMobilePush() { // Make sure to dispatch this to the main thread, as UNUserNotificationCenter will // present UI. DispatchQueue.main.async { // Set the UNUserNotificationCenterDelegate to a class adhering to thie protocol. // In this exmple, the AppDelegate class adheres to the protocol (see below) // and handles Notification Center delegate methods from iOS. UNUserNotificationCenter.current().delegate = self // Request authorization from the user for push notification alerts. UNUserNotificationCenter.current().requestAuthorization( options: [.alert, .sound, .badge], completionHandler: {(_ granted: Bool, _ error: Error?) -> Void in if error == nil { if granted == true { // Your application may want to do something specific if the user has granted // authorization for the notification types specified; it would be done here. } } }) // Your application should register for remote notifications each time your application // launches to make sure that the push token for silent push is updated, if necessary. // Registering in this manner doesn't mean that a user sees a notification. It only // means that the application receives a unique push token from iOS. UIApplication.shared.registerForRemoteNotifications() } } @UIApplicationMain @objc class AppDelegate: FlutterAppDelegate { // The appID, accessToken, and appEndpoint are required values for configuring the SDK. Obtain // these values from your app. let appID = YOUR_APP_ID let accessToken = YOUR_ACCESS_TOKEN let appEndpointURL = YOUR_APP_ENDPOINT let mid = YOUR_ACCOUNT_MID // Define the features your app uses. let analytics = true override func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { GeneratedPluginRegistrant.register(with: self) // Required: tell the MarketingCloudSDK about the notification. The SDK collects // analytics and processes the notification on behalf of your application. SFMCSdk.requestPushSdk { mp in mp.setNotificationResponse(response) } // rest of the didFinishLaunchingWithOptions method... return super.application(application, didFinishLaunchingWithOptions: launchOptions) } completionHandler(.alert) } ```
View Objective-C code example ```objc //AppDelegate.h #import #import #import // The SFMCSDK module is included in the dependency packages for the SDK. Don't install it // separately or list it in your podfile. #import //Other imports... @interface AppDelegate : FlutterAppDelegate @end //AppDelegate.m #import "AppDelegate.h" #import "GeneratedPluginRegistrant.h" #import //Other imports... @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //Flutter setup [GeneratedPluginRegistrant registerWithRegistry:self]; // Override point for customization after application launch. // Use the Push Config Builder to configure the Mobile Push Module. This gives you the // maximum flexibility in SDK configuration. The builder lets you configure the module // parameters at runtime. PushConfigBuilder *pushConfigBuilder = [[PushConfigBuilder alloc] initWithAppId:@"{MC_APP_ID}"]; [pushConfigBuilder setAccessToken:@"{MC_ACCESS_TOKEN}"]; [pushConfigBuilder setMarketingCloudServerUrl: [NSURL URLWithString:@"{MC_APP_SERVER_URL}"]]; [pushConfigBuilder setMid:@"MC_MID"]; [pushConfigBuilder setAnalyticsEnabled:YES]; // Once you’ve created the mobile push configuration, intialize the SDK. [SFMCSdk initializeSdk:[[[SFMCSdkConfigBuilder new] setPushWithConfig:[pushConfigBuilder build] onCompletion:^(SFMCSdkOperationResult result) { if (result == SFMCSdkOperationResultSuccess) { // module is fully configured and ready for use [self pushSetup]; } else { NSLog(@"SFMC sdk configuration failed."); } }] build]]; // rest of the didFinishLaunchingWithOptions method... return [super application:application didFinishLaunchingWithOptions:launchOptions]; } - (void)pushSetup { // Make sure to dispatch this to the main thread, as UNUserNotificationCenter will // present UI. dispatch_async(dispatch_get_main_queue(), ^{ // Set the UNUserNotificationCenterDelegate to a class adhering to thie protocol. // In this exmple, the AppDelegate class adheres to the protocol (see below) // and handles Notification Center delegate methods from iOS. [UNUserNotificationCenter currentNotificationCenter].delegate = self; // Your application should register for remote notifications each time your // application launches to make sure that the push token for silent push is updated, // if necessary. // Registering in this manner doesn’t mean that a user sees a notification. It only // means that the application will receive a unique push token from iOS. [[UIApplication sharedApplication] registerForRemoteNotifications]; // Request authorization from the user for push notification alerts. [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge completionHandler:^(BOOL granted, NSError *_Nullable error) { if (error == nil) { if (granted == YES) { // Your application may want to do something specific if the user has // granted authorization for the notification types specified; it would be // done here. NSLog(@"User granted permission"); } } }]; }); } - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { [SFMCSdk requestPushSdk:^(id _Nonnull mp) { [mp setDeviceToken:deviceToken]; }]; } - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { os_log_debug(OS_LOG_DEFAULT, "didFailToRegisterForRemoteNotificationsWithError = %@", error); } // The method will be called on the delegate when the user responded to the notification by // opening the application, dismissing the notification or choosing a UNNotificationAction. // The delegate must be set before the application returns from // applicationDidFinishLaunching:. - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler { // tell the MarketingCloudSDK about the notification [SFMCSdk requestPushSdk:^(id _Nonnull mp) { [mp setNotificationResponse:response]; }]; if (completionHandler != nil) { completionHandler(); } } // The method will be called on the delegate only if the application is in the foreground. // If the method is not implemented or the handler is not called in a timely manner then the // notification will not be presented. The application can choose to have the notification // presented as a sound, badge, alert and/or in the notification list. This decision should // be based on whether the information in the notification is otherwise visible to the user. - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler: (void (^)(UNNotificationPresentationOptions options))completionHandler { completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge); } /** This delegate method offers an opportunity for applications with the "remote-notification" background mode to fetch appropriate new data in response to an incoming remote notification. You should call the fetchCompletionHandler as soon as you’re finished performing that operation, so the system can accurately estimate its power and data cost. This method will be invoked even if the application was launched or resumed because of the remote notification. The respective delegate methods will be invoked first. Note that this behavior is in contrast to application:didReceiveRemoteNotification:, which is not called in those cases, and which will not be invoked if this method is implemented. **/ - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { [SFMCSdk requestPushSdk:^(id _Nonnull mp) { [mp setNotificationUserInfo:userInfo]; }]; completionHandler(UIBackgroundFetchResultNewData); } @end ``` ## URL Handling The SDK doesn’t automatically present URLs from these sources. - CloudPages URLs from push notifications - OpenDirect URLs from push notifications - Action URLs from in-app messages To handle URLs from push notifications, follow these steps. 1. [Set the `setURLHandlingDelegate`](#set-the-seturlhandlingdelegate). 2. [Implement the `URLHandlingDelegate`](#implement-the-urlhandlingdelegate). ### Set the `setURLHandlingDelegate` To set the `URLHandlingDelegate`, update the `AppDelegate` as shown in this example.
View Swift code example ```swift func setupMobilePush() { // Set the URLHandlingDelegate to a class adhering to the protocol. // In this example, the AppDelegate class adheres to the protocol (see below) // and handles URLs passed back from the SDK. SFMCSdk.requestPushSdk { mp in mp.setURLHandlingDelegate(self) } ... } ```
View Objective-C code example ```objc // AppDelegate.h #import #import #import // The SFMCSDK module is included in the dependency packages for the SDK. Don't install it // separately or list it in your podfile. #import //... // Implement the SFMCSdkURLHandlingDelegate delegate @interface AppDelegate : FlutterAppDelegate @end // AppDelegate.m - (void)pushSetup { // AppDelegate adheres to the SFMCSdkURLHandlingDelegate protocol // and handles URLs passed back from the SDK in `sfmc_handleURL`. [SFMCSdk requestPushSdk:^(id _Nonnull mp) { [mp setURLHandlingDelegate:self]; }]; //rest of pushSetup... } ```
### Implement the `URLHandlingDelegate` Implement the `URLHandlingDelegate` in `AppDelegate`, as shown in this example.
View Swift code example ```swift // AppDelegate.swift //rest of AppDelegate.swift... // REQUIRED IMPLEMENTATION extension AppDelegate: URLHandlingDelegate { /** This method, if implemented, can be called when a Alert+CloudPage, Alert+OpenDirect, Alert+Inbox or Inbox message is processed by the SDK. Implementing this method allows the application to handle the URL from Marketing Cloud Engagement data. In versions of the SDK before version 6.0.0, the SDK automatically handled URLs and presented them using a SFSafariViewController. Because there are security risks inherent in URLs and web pages (such as Open Redirect vulnerabilities), the app that implements the Engagement SDK is now responsible for processing URLs. This reduces risk to the application by affording full control over processing, presentation and security to the application code itself. @param url value NSURL sent with the Location, CloudPage, OpenDirect or Inbox message @param type value NSInteger enumeration of the source type of this URL */ func sfmc_handleURL(_ url: URL, type: String) { // Send the URL returned from the SDK to UIApplication to handle correctly. UIApplication.shared.open(url, options: [:], completionHandler: { (success) in print("Open \(url): \(success)") }) } } ```
View Objective-C code example ```objc // AppDelegate.m //rest of AppDelegate.m... /** This method, if implemented, can be called when a Alert+CloudPage, Alert+OpenDirect, Alert+Inbox or Inbox message is processed by the SDK. Implementing this method allows the application to handle the URL from Marketing Cloud Engagement data. Versions of the SDK before version 6.0.0 handled URLs automatically and presented them using a SFSafariViewController. Because there are security risks inherent in URLs and web pages (such as Open Redirect vulnerabilities), the app that implements the SDK is now responsible for processing URLs. This change reduces risk to the application by affording full control over processing, presentation and security to the application code itself. @param url value NSURL sent with the Location, CloudPage, OpenDirect or Inbox message @param type value NSInteger enumeration of the source type of this URL */ - (void)sfmc_handleURL:(NSURL * _Nonnull)url type:(NSString * _Nonnull)type { if ([[UIApplication sharedApplication] canOpenURL:url]) { [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) { if (success) { NSLog(@"url %@ opened successfully", url); } else { NSLog(@"url %@ could not be opened", url); } }]; } } //rest of AppDelegate.m... ```
## Enable Rich Notifications (Optional) Rich notifications include images, videos, titles, subtitles, and mutable content. Mutable content can include personalization in the title, subtitle, or body of your message. For implementation details, see [Send Rich Notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_push_notifications/mc_engagement_push_notifications_ios_rich_notifications.md). ## Troubleshoot iOS Setup If you encounter a cycle error in your Flutter Xcode project after adding a Notification Service Extension, follow these steps to fix it. 1. Navigate to `YOUR_APP_TARGET` in Xcode. 2. With your app target selected, go to the **Build Phases** tab. 3. Find **Embed Foundation Extension**. 4. Drag and position it above both **Thin Binary** and Embed Pods **Frameworks**. Reordering the build phases resolves the cycle error. ## See Also - [URL Handling](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_handle_urls.md) - _Github_: [Flutter Plugin](https://github.com/salesforce-marketingcloud/sdk-flutter-plugin) # Configure the React Native Plugin for Android Apps After you install and configure the React Native plugin, configure the plugin to enable push support for the Android platform. **important:** For new React Native integrations, use the [React Native Unified Plugin Setup](https://developer.salesforce.com/docs/marketing/unified_modules/hybrid-frameworks/react-native/unified-react-native-setup.md). This topic is intended for customers who use the existing React Native plugin for Marketing Cloud Engagement. ## Prerequisites Before you configure the React Native plugin for Android apps, make sure that the plugin is installed and configured for your app. See [Marketing Cloud React Native Plugin](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_development_frameworks_react_native.md). ## Add the Repository Add the repository to your `build.gradle` file. ``` allprojects { repositories { maven { url "https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/repository" } //... Other repos } } ``` ## Provide FCM Credentials To enable push support for Android, provide your FCM credentials by placing the `google-services.json` file in the `android/app` directory. 1. Download the `google-services.json` file from your app’s [Firebase console](https://console.firebase.google.com/) and place it in your project’s `android/app` directory. 2. Include the Google Services plugin in your `android/build.gradle` file. ``` buildscript { repositories { google() // Google’s Maven repository } dependencies { // ... // Add this line: classpath 'com.google.gms:google-services:4.3.15' } } ``` 3. Add the plugin to your `build.gradle` file. ``` // Add the google services plugin to your build.gradle file apply plugin: 'com.google.gms.google-services' ``` ## Configure the SDK Configure the SDK in your main application class. **note:** React Native templates default to Kotlin (`MainApplication.kt`). However, older templates still support Java (`MainApplication.java`). When you configure the SDK, select the file type that matches your project. ```java import android.content.Context import android.util.Log import com.salesforce.marketingcloud.MarketingCloudConfig import com.salesforce.marketingcloud.notifications.NotificationCustomizationOptions import com.salesforce.marketingcloud.sfmcsdk.SFMCSdk import com.salesforce.marketingcloud.sfmcsdk.SFMCSdkModuleConfig override fun onCreate() { super.onCreate() SFMCSdk.configure(this as Context, SFMCSdkModuleConfig.build { pushModuleConfig = MarketingCloudConfig.builder() .setApplicationId("{MC_APP_ID}") .setAccessToken("{MC_ACCESS_TOKEN}") .setSenderId("{FCM_SENDER_ID_FOR_MC_APP}") .setMarketingCloudServerUrl("{MC_APP_SERVER_URL}") .setNotificationCustomizationOptions( NotificationCustomizationOptions.create(R.drawable.ic_notification) ) .setAnalyticsEnabled(true) .build(this@MainApplication) }) { initializationStatus -> Log.e("TAG", "STATUS $initializationStatus") if (initializationStatus.status == 1) { Log.e("TAG", "STATUS SUCCESS") } } // ... The rest of the onCreate method } ```
View Java code example ```java import android.content.Context; import android.util.Log; import com.salesforce.marketingcloud.MarketingCloudConfig; import com.salesforce.marketingcloud.notifications.NotificationCustomizationOptions; import com.salesforce.marketingcloud.sfmcsdk.SFMCSdk; import com.salesforce.marketingcloud.sfmcsdk.SFMCSdkModuleConfig; @Override public void onCreate() { super.onCreate(); SFMCSdk.configure((Context) this, SFMCSdkModuleConfig.build(builder -> { builder.setPushModuleConfig(MarketingCloudConfig.builder() .setApplicationId("{MC_APP_ID}") .setAccessToken("{MC_ACCESS_TOKEN}") .setSenderId("{FCM_SENDER_ID_FOR_MC_APP}") .setMarketingCloudServerUrl("{MC_APP_SERVER_URL}") .setNotificationCustomizationOptions(NotificationCustomizationOptions.create(R.drawable.ic_notification)) .setAnalyticsEnabled(true) .build(this)); return null; }), initializationStatus -> { Log.e("TAG", "STATUS "+initializationStatus); if (initializationStatus.getStatus() == 1) { Log.e("TAG", "STATUS SUCCESS"); } return null; }); // ... The rest of the onCreate method } ```
To customize push notification functionality for Android apps, see the [notification customization guide](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_push_notifications/mc_engagement_push_notifications_android_customize.md). To implement the Carousel and Button actions features introduced in version 9 of the SDK, see [Configure Button and Carousel Actions](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_push_notifications/mc_engagement_push_notifications_android_button_carousel.md). # Configure the React Native Plugin for iOS Apps After you install and configure the React Native plugin, configure it to enable push notification support for the iOS platform. **important:** For new react-native integrations, use the [React Native Unified Plugin Setup](https://developer.salesforce.com/docs/marketing/unified_modules/hybrid-frameworks/react-native/unified-react-native-setup.md). This topic is intended for customers who use the React Native plugin for Marketing Cloud Engagement. ## Prerequisites Before you configure the React Native plugin for iOS apps, make sure that the plugin is installed and configured for your app. See [Marketing Cloud React Native Plugin](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_development_frameworks_react_native.md). ## Enable Push Notifications In Your iOS App To enable push notifications in your iOS app, follow these steps. 1. [Install the SDK pod](#install-the-sdk-pod) 2. [Enable and configure push notifications](#enable-and-configure-push-notifications) 3. [Enable rich notifications](#enable-rich-notifications) ### Install the SDK Pod After you've installed the React Native plugin using [npm](https://www.npmjs.com/package/react-native-marketingcloudsdk) or [Yarn](https://yarnpkg.com/package/react-native-marketingcloudsdk), navigate to the `ios` directory and install the SDK pod. ```bash // In your App, go to ios directory after installing plugin via npm or yarn. cd ios pod install ``` ### Enable and Configure Push Notifications 1. Enable push notifications in your target’s **Capabilities** settings in Xcode by clicking **+ Capability** and then selecting **Push Notifications**. ![Enabling push notifications](https://developer.salesforce.com/media/overview/enable-push-ios-apps.png) 2. Set your `AppDelegate` class to adhere to the `UNUserNotificationCenterDelegate` and `SFMCSdkURLHandlingDelegate` protocols. ```c // Other imports... #import #import #import @interface AppDelegate : RCTAppDelegate ``` 3. Set up push notifications by updating `AppDelegate`. ```c @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { //RN setup self.moduleName = @"example"; // You can add your custom initial props in the dictionary below. // They will be passed down to the ViewController used by React Native. self.initialProps = @{}; // Configure the SFMC sdk ... PushConfigBuilder *pushConfigBuilder = [[PushConfigBuilder alloc] initWithAppId:@"{MC_APP_ID}"]; [pushConfigBuilder setAccessToken:@"{MC_ACCESS_TOKEN}"]; [pushConfigBuilder setMarketingCloudServerUrl:[NSURL URLWithString:@"{MC_APP_SERVER_URL}"]]; [pushConfigBuilder setMid:@"MC_MID"]; [pushConfigBuilder setAnalyticsEnabled:YES]; [SFMCSdk initializeSdk:[[[SFMCSdkConfigBuilder new] setPushWithConfig:[pushConfigBuilder build] onCompletion:^(SFMCSdkOperationResult result) { if (result == SFMCSdkOperationResultSuccess) { [self pushSetup]; } else { // SFMC sdk configuration failed. NSLog(@"SFMC sdk configuration failed."); } }] build]]; // ... The rest of the didFinishLaunchingWithOptions method return [super application:application didFinishLaunchingWithOptions:launchOptions]; } - (void)pushSetup { // AppDelegate adheres to the SFMCSdkURLHandlingDelegate protocol // and handles URLs passed back from the SDK in `sfmc_handleURL`. [SFMCSdk requestPushSdk:^(id _Nonnull mp) { [mp setURLHandlingDelegate:self]; }]; dispatch_async(dispatch_get_main_queue(), ^{ // set the UNUserNotificationCenter delegate - the delegate must be set here in // didFinishLaunchingWithOptions [UNUserNotificationCenter currentNotificationCenter].delegate = self; [[UIApplication sharedApplication] registerForRemoteNotifications]; [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge completionHandler:^(BOOL granted, NSError *_Nullable error) { if (error == nil) { if (granted == YES) { NSLog(@"User granted permission"); } } }]; }); } - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { [SFMCSdk requestPushSdk:^(id _Nonnull mp) { [mp setDeviceToken:deviceToken]; }]; } - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { os_log_debug(OS_LOG_DEFAULT, "didFailToRegisterForRemoteNotificationsWithError = %@", error); } // The method will be called on the delegate when the user responded to the notification by opening // the application, dismissing the notification or choosing a UNNotificationAction. The delegate // must be set before the application returns from applicationDidFinishLaunching:. - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler { // tell the MarketingCloudSDK about the notification [SFMCSdk requestPushSdk:^(id _Nonnull mp) { [mp setNotificationResponse:response]; }]; if (completionHandler != nil) { completionHandler(); } } - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler: (void (^)(UNNotificationPresentationOptions options))completionHandler { NSLog(@"User Info : %@", notification.request.content.userInfo); completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge); } // This method is REQUIRED for correct functionality of the SDK. // This method will be called on the delegate when the application receives a silent push - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { [SFMCSdk requestPushSdk:^(id _Nonnull mp) { [mp setNotificationUserInfo:userInfo]; }]; completionHandler(UIBackgroundFetchResultNewData); } //URL Handling - (void)sfmc_handleURL:(NSURL * _Nonnull)url type:(NSString * _Nonnull)type { if ([[UIApplication sharedApplication] canOpenURL:url]) { [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) { if (success) { NSLog(@"url %@ opened successfully", url); } else { NSLog(@"url %@ could not be opened", url); } }]; } } @end ``` ### Enable Rich Notifications Rich notifications include images, videos, titles and subtitles, and mutable content. Mutable content can include personalization in the title, subtitle, or body of your message. To enable rich notifications, create a notification service extension. For implementation details, see [Send Rich Notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_push_notifications/mc_engagement_push_notifications_ios_rich_notifications.md). ## URL Handling The SDK doesn’t automatically present URLs from these sources. - CloudPages URLs from push notifications. - OpenDirect URLs from push notifications. - Action URLs from in-app messages. To handle URLs from push notifications in Android apps, use the code in this example. ```java @Override public void onCreate() { super.onCreate(); SFMCSdk.configure((Context) this, SFMCSdkModuleConfig.build(builder -> { builder.setPushModuleConfig(MarketingCloudConfig.builder() .setApplicationId("{MC_APP_ID}") .setAccessToken("{MC_ACCESS_TOKEN}") .setSenderId("{FCM_SENDER_ID_FOR_MC_APP}") .setMarketingCloudServerUrl("{MC_APP_SERVER_URL}") .setNotificationCustomizationOptions(NotificationCustomizationOptions.create(R.drawable.ic_notification)) .setAnalyticsEnabled(true) // Here we set the URL handler to present URLs from CloudPages, OpenDirect, and In-App Messages .setUrlHandler((context, s, s1) -> PendingIntent.getActivity( context, new Random().nextInt(), new Intent(Intent.ACTION_VIEW, Uri.parse(s)), PendingIntent.FLAG_UPDATE_CURRENT )).build(this)); return null; }), initializationStatus -> { Log.e("TAG", "STATUS "+initializationStatus); if (initializationStatus.getStatus() == 1) { Log.e("TAG", "STATUS SUCCESS"); } return null; }); // The rest of the onCreate method } ``` To handle URLs from push notifications in iOS apps, use the code in this example. ``` // AppDelegate.h ---- #import #import ... // Implement the SFMCSdkURLHandlingDelegate delegate @interface AppDelegate : RCTAppDelegate // AppDelegate.mm ---- // This method is called after successfully initializing the SFMCSdk - (void)pushSetup { dispatch_async(dispatch_get_main_queue(), ^{ // Here we set the URL Handling delegate to present URLs from CloudPages, OpenDirect, and In-App Messages [[SFMCSdk mp] setURLHandlingDelegate:self]; // Set UNUserNotificationCenter delegate, register for remote notifications, etc... }); } // ... // Implement the required delegate method to handle URLs - (void)sfmc_handleURL:(NSURL * _Nonnull)url type:(NSString * _Nonnull)type { if ([[UIApplication sharedApplication] canOpenURL:url]) { [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) { if (success) { NSLog(@"url %@ opened successfully", url); } else { NSLog(@"url %@ could not be opened", url); } }]; } } ``` ## See Also - [URL Handling](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_handle_urls.md) # Configure the SDK The configuration example in this section uses the MarketingCloudSDK `ConfigBuilder` configuration method. This method is the most flexible way to use the Mobile App Messaging SDK. All method names contain the prefix `sfmc_`. Using this prefix helps avoid namespace collisions between the external libraries it uses. For more information, see _Apple Developer Documentation_: [Customizing Existing Classes](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/CustomizingExistingClasses/CustomizingExistingClasses.html). Configure the SDK in your application using `mamAppID`, `mamAccessToken`, `mamServerURL`, and `mamTenantId`. **important:** This example imports the `SFMCSDK` module, which is included automatically with the dependencies for the SDK. Never install this dependency manually (such as by using CocoaPods). ```swift import MobileAppMessagingSDK // The SFMCSDK module is included in the dependency packages for the SDK. Don't install it // separately or list it in your podfile. import SFMCSDK class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? // MobileAppMessaging Configuration let mamAppID = YOUR_APP_ID let mamAccessToken = YOUR_ACCESS_TOKEN let mamServerURL = YOUR_SERVER_URL let mamTenantId = YOUR_TENANT_ID let mamAnalyticsEnabled = true // MobilePush SDK: REQUIRED IMPLEMENTATION @discardableResult func configureSdk() -> Bool { // Enable logging for debugging early on. Debug level is not recommended for production apps, as significant data // about the SDK will be logged to the console. #if DEBUG SFMCSdk.setLogger(logLevel: .debug) #endif // Use the `MobileAppMessagingConfigBuilder` to configure the Mobile App Messaging SDK. This gives you the maximum flexibility in SDK configuration. // The builder lets you configure the module parameters at runtime. let mamConfiguration = MobileAppMessagingConfigBuilder(appId: mamAppID) .setAccessToken(mamAccessToken) .setMAMUrl(URL(string: mamServerURL)!) .setTenantId(mamTenantId) .setAnalyticsEnabled(mamAnalyticsEnabled) .build() // Set the completion handler to take action when all modules initialization is completed. // Seting the completion handler is optional. let completionHandler: ((_ status: [ModuleInitStatus]) -> Void) = { [weak self] status in DispatchQueue.main.async { self?.handleSDKInitializationCompletion(status: status) } } SFMCSdk.initializeSdk( ConfigBuilder().setMAM(config: mamConfiguration).build(), completion: completionHandler) return true } // MARK: - SDK Initialization Completion Handler private func handleSDKInitializationCompletion(status: [ModuleInitStatus]) { var allSuccessful = true for moduleStatus in status { print( "Module: \(moduleStatus.moduleName.rawValue), Status: \(moduleStatus.initStatus.rawValue)") if moduleStatus.initStatus == .success { // Handle successful initialization for each module switch moduleStatus.moduleName { case .mobileAppMessaging: // Handle successful initialization for Mobile App Messaging module default: break } } else if moduleStatus.initStatus == .error { allSuccessful = false // module failed to initialize, check logs for more details } else if moduleStatus.initStatus == .cancelled { allSuccessful = false // module initialization was cancelled (for example, if re-configuration // was triggered before init completed) } else if moduleStatus.initStatus == .timeout { allSuccessful = false // module failed to initialize due to timeout, check logs for more details } } if allSuccessful { print("SDK initialization completed successfully") } else { print("SDK initialization completed with errors - check logs above") } } // MobilePush SDK: REQUIRED IMPLEMENTATION func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { self.configureSdk() return true } // MobilePush SDK: OPTIONAL IMPLEMENTATION (if using Data Protection) func applicationProtectedDataDidBecomeAvailable(_ application: UIApplication) { self.configureSdk() } } ``` iOS Data Protection affects the SDK as described in this table. | iOS Data Protection Level | SDK Behavior | | ---------------------------------------- | -------------------------------------------------------------- | | No protection | SDK works in the foreground and background. | | Complete until first user authentication | SDK works in the foreground and background after first unlock. | | Complete unless open | SDK works in the foreground and background after first unlock. | | Complete | SDK works only in the foreground after the device is unlocked. | # Configure the SDK for iOS After you install the SDK dependencies [manually](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/engagement_sdk_guide_integrate_ios_manual.md), with [CocoaPods](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/engagement_sdk_guide_integrate_ios_cocoapods.md), or with [Swift Package Manager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/engagement_sdk_guide_integrate_ios_spm.md), configure the SDK using the `ConfigBuilder` method. **note:** Earlier versions of the SDK supported JSON file configuration, which is deprecated. If your implementation uses JSON configuration, reconfigure it using the builder method. Use these code examples to configure the SDK in your app. Make these changes to the examples: - Add the `Access Token`, `App ID`, `App Endpoint`, and `MID` values that you obtained when you [configured Marketing Cloud Engagement](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_mce_configure.md). - Enable or disable `analytics`, `location`, or `inbox` based on your app's requirements. Also, consider [the ways that iOS Data Protection impact your app](#data-protection-considerations). **important:** These examples import the `SFMCSDK` module, which is included automatically with the dependencies for the SDK. Never install this dependency manually (such as by using CocoaPods). ::::::tabset{tabs='["SDK v10+", "SDK v8 and 9", "SDK v7"]'} :::::tab If your app uses version 10 or later of the SDK, use this code. ```swift import MarketingCloudSDK // The SFMCSDK module is included in the dependency packages for the SDK. Don't install it // separately or list it in your podfile. import SFMCSDK import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? // Marketing Cloud SDK configuration let mcAppID = "" let mcAccessToken = "" let mcServerURL = "" let mcMid = "" // Define features of Marketing Cloud your app uses let mcInboxEnabled = false let mcLocationEnabled = false let mcAnalyticsEnabled = true // MarketingCloud SDK: REQUIRED IMPLEMENTATION @discardableResult func configureSdk() -> Bool { // Enable logging for debugging. Don't use debug level in production apps because the SDK logs // significant data to the console. #if DEBUG SFMCSdk.setLogger(logLevel: .debug) #endif // Use the `MarketingCloudSdkConfigBuilder` to configure the MarketingCloud SDK. // The builder lets you configure the module parameters at runtime. let engagementConfiguration = MarketingCloudSdkConfigBuilder(appId: mcAppID) .setAccessToken(mcAccessToken) .setMarketingCloudServerUrl(URL(string: mcServerURL)!) .setMid(mcMid) .setInboxEnabled(mcInboxEnabled) .setLocationEnabled(mcLocationEnabled) .setAnalyticsEnabled(mcAnalyticsEnabled) .build() // Set the completion handler to take action when module initialization completes. // Setting the completion handler is optional. let completionHandler: ((_ status: [ModuleInitStatus]) -> Void) = { [weak self] status in DispatchQueue.main.async { self?.handleSDKInitializationCompletion(status: status) } } SFMCSdk.initializeSdk( ConfigBuilder().setEngagement(config: engagementConfiguration).build(), completion: completionHandler) return true } // MARK: - SDK Initialization Completion Handler private func handleSDKInitializationCompletion(status: [ModuleInitStatus]) { var allSuccessful = true for moduleStatus in status { print( "Module: \(moduleStatus.moduleName.rawValue), Status: \(moduleStatus.initStatus.rawValue)") if moduleStatus.initStatus == .success { // Handle successful initialization for each module switch moduleStatus.moduleName { case .engagement: // Handle successful initialization for Marketing Cloud module default: break } } else if moduleStatus.initStatus == .error { allSuccessful = false // Module failed to initialize. Check logs for details. } else if moduleStatus.initStatus == .cancelled { allSuccessful = false // Module initialization was cancelled. For example, reconfiguration was triggered before initialization completed. } else if moduleStatus.initStatus == .timeout { allSuccessful = false // Module failed to initialize due to timeout. Check logs for details. } } if allSuccessful { print("SDK initialization completed successfully") } else { print("SDK initialization completed with errors - check logs above") } } func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { // Override point for customization after application launch. self.configureSdk() return true } // Marketing Cloud SDK: OPTIONAL IMPLEMENTATION (if using Data Protection) func applicationProtectedDataDidBecomeAvailable(_ application: UIApplication) { self.configureSdk() } } ``` ::::: :::::tab If your app uses version 8 or 9 of the SDK, use this code. ```swift // The SFMCSDK module is included in the dependency packages for the SDK. Don't install it // separately or list it in your podfile. import SFMCSDK import MarketingCloudSDK class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? // SDK: REQUIRED IMPLEMENTATION // The appID, accessToken, and appEndpoint are required configuration values. #if DEBUG let appId = YOUR_DEV_APP_ID let accessToken = YOUR_DEV_ACCESS_TOKEN let appEndpoint = YOUR_DEV_APP_ENDPOINT let mid = YOUR_DEV_MID #else let appId = YOUR_PROD_APP_ID let accessToken = YOUR_PROD_ACCESS_TOKEN let appEndpoint = YOUR_PROD_APP_ENDPOINT let mid = YOUR_PROD_MID #endif // Define the features your app uses let inbox = false let location = false let analytics = true // SDK: REQUIRED IMPLEMENTATION func configureSDK() { // Enable logging for debugging. Don't use debug level in production apps because the SDK logs // a large amount of data to the console. #if DEBUG SFMCSdk.setLogger(logLevel: .debug) #endif // Use the Config Builder to configure the module parameters at runtime. let mobilePushConfiguration = PushConfigBuilder(appId: appId) .setAccessToken(accessToken) .setMarketingCloudServerUrl(appEndpoint) .setMid(mid) .setInboxEnabled(inbox) .setLocationEnabled(location) .setAnalyticsEnabled(analytics) .build() // Set the completion handler to take action when module initialization completes. The result indicates whether initialization was successful. // Setting the completion handler is optional. let completionHandler: (OperationResult) -> () = { result in if result == .success { // Module is fully configured and ready for use } else if result == .error { // Module failed to initialize. Check logs for details. } else if result == .cancelled { // Module initialization was cancelled. For example, reconfiguration was triggered before initialization completed. } else if result == .timeout { // Module failed to initialize due to timeout. Check logs for details. } } // After you create the configuration, initialize the SDK. SFMCSdk.initializeSdk(ConfigBuilder().setPush(config: mobilePushConfiguration, onCompletion: completionHandler).build()) } // SDK: REQUIRED IMPLEMENTATION func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { self.configureSDK() return true } // SDK: OPTIONAL IMPLEMENTATION (if using Data Protection) func applicationProtectedDataDidBecomeAvailable(_ application: UIApplication) { if (SFMCSdk.mp.getStatus() != .operational) { self.configureSFMCSdk() } } } ``` ::::: :::::tab If your app uses version 7 of the SDK, use this code. ```swift import MarketingCloudSDK class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? // REQUIRED IMPLEMENTATION // The appID, accessToken, and appEndpoint are required configuration values. // Use the builder method to configure the SDK. // The builder lets you configure the SDK parameters at runtime. #if DEBUG let appID = YOUR_DEV_APP_ID let accessToken = YOUR_DEV_ACCESS_TOKEN let appEndpoint = YOUR_DEV_APP_ENDPOINT let mid = YOUR_DEV_MID #else let appId = YOUR_PROD_APP_ID let accessToken = YOUR_PROD_ACCESS_TOKEN let appEndpoint = YOUR_PROD_APP_ENDPOINT let mid = YOUR_PROD_MID #endif // Define the features your app uses let inbox = false let location = false let analytics = true // REQUIRED IMPLEMENTATION @discardableResult func configureMarketingCloudSDK() -> Bool { // Use the builder method to configure the SDK. // The builder lets you configure the SDK parameters at runtime. let builder = MarketingCloudSDKConfigBuilder() .sfmc_setApplicationId(appID) .sfmc_setAccessToken(accessToken) .sfmc_setMarketingCloudServerUrl(appEndpoint) .sfmc_setMid(mid) .sfmc_setInboxEnabled(inbox as NSNumber) .sfmc_setLocationEnabled(location as NSNumber) .sfmc_setAnalyticsEnabled(analytics as NSNumber) .sfmc_build()! var success = false // After you create the builder, pass it to the sfmc_configure method. do { try MarketingCloudSDK.sharedInstance().sfmc_configure(with:builder) success = true } catch let error as NSError { // Configuration errors are returned in the NSError parameter. Use them to determine // whether you implemented the SDK correctly. let configErrorString = String(format: "MarketingCloudSDK sfmc_configure failed with error = %@", error) print(configErrorString) } if success == true { // The SDK is fully configured and ready for use. // Enable logging for debugging. Don't use this in production apps because the SDK logs // a large amount of data to the console. #if DEBUG MarketingCloudSDK.sharedInstance().sfmc_setDebugLoggingEnabled(true) #endif } return success } // REQUIRED IMPLEMENTATION func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { return self.configureMarketingCloudSDK() } // OPTIONAL IMPLEMENTATION (if using Data Protection) func applicationProtectedDataDidBecomeAvailable(_ application: UIApplication) { if(MarketingCloudSDK.sharedInstance().sfmc_isReady() == false) { self.configureMarketingCloudSDK() } } } ``` ::::: :::::: ## Data Protection Considerations iOS Data Protection encrypts files stored on the device and controls when your app can access them based on the lock state of the user’s device. If your app uses Data Protection, you must configure the SDK at the right time to ensure it can access the encrypted data it needs to function. The SDK’s ability to work in the foreground or background depends on the Data Protection level you configure. iOS Data Protection affects the SDK in these ways. | iOS Data Protection Level | SDK Behavior | | ---------------------------------------- | ------------------------------------------------------------- | | No protection | SDK works in the foreground and background | | Complete until first user authentication | SDK works in the foreground and background after first unlock | | Complete unless open | SDK works in the foreground and background after first unlock | | Complete | SDK works only in the foreground after the device is unlocked | For more information, see [iOS Data Protection](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/engagement_sdk_guide_integrate_ios_data_protection.md). ## See Also - [iOS Data Protection](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/engagement_sdk_guide_integrate_ios_data_protection.md) - _SDK Reference_: [SDK for iOS, Version 11](/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/ios-sdk-v11_index.html) - _Apple Developer Documentation_: [Customizing Existing Classes](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/CustomizingExistingClasses/CustomizingExistingClasses.html) # Configure the Service Extension for the iOS Extension SDK Setup and configure the Notification Service Extension for use with the iOS Extension SDK. ## Add a Service Extension Target The notification service app extension is a bundle within your main app. To add a service extension target, complete these steps. 1. In Xcode, go to **File** > **New** > **Target**. 2. In the iOS > Application Extension section, select **Notification Service Extension**. 3. Click **Next**. 4. Configure the app extension and click **Finish**. 5. In the General Settings section for your project target, verify that the new extension is listed under **Frameworks, Libraries, and Embedded Content**. If it isn’t listed there, add it. **important:** Use the same Xcode-managed profile for the extension targets as the main project. Match the service extension version to the main app version whenever possible, and prefix the service extension bundle ID with the main app’s bundle ID. For example, if the main app’s bundle ID is `com.salesforce.MyAwesomeApp`, the service extension bundle ID can be `com.salesforce.MyAwesomeApp.MyServiceExtension`. ## Integrate the Extension SDK with the Service Extension To integrate the Service Extension, add the dependencies to CocoaPods or Swift Package Manager (SPM). You can also add the dependencies manually. - [Integrate the SDK with CocoaPods](#integrate-the-extension-sdk-with-cocoapods) - [Integrate the SDK with Swift Package Manager (SPM)](#integrate-the-extension-sdk-with-swift-package-manager) - [Integrate the SDK Manually](#integrate-the-extension-sdk-manually) ### Integrate the Extension SDK with CocoaPods If you use CocoaPods to manage dependencies for your app, add the extension SDK to your Podfile. 1. Update your Podfile to include the extension SDK. ```swift target '' do use_frameworks! pod 'MarketingCloudSDK' end target '' do use_frameworks! pod 'MarketingCloud-ExtensionSDK' end ``` 2. In your project directory, run `pod install`. 3. Open the `.xcworkspace` file that CocoaPods generates. **important:** Don't open the `.xcodeproj` file directly. Opening a project file instead of a workspace can lead to errors. For more information about updating Podfiles, see _Using CocoaPods_: [Adding pods to an Xcode project](https://guides.cocoapods.org/using/using-cocoapods.html) on the CocoaPods documentation site. ### Integrate the Extension SDK with Swift Package Manager If you use Swift Package Manager (SPM) to manage dependencies for your app, add the extension SDK to your Podfile. 1. On the **Package Dependencies** tab of your project’s settings, click the plus sign (**+**) to add a package. 2. Search for the package `MCExtensionSDK` using the URL `https://github.com/salesforce-marketingcloud/extension-sdk-ios.git` 3. Select the package to include it in your app. ### Integrate the Extension SDK Manually If you don't use CocoaPods or Swift Package Manager, you can add the extension packages manually. 1. Download the [MCExtensionSDK](https://github.com/salesforce-marketingcloud/extension-sdk-ios/releases/tag/v1.0.0). 2. Copy the `MCExtensionSDK` directory from your downloads folder to your project directory. **note:** To keep the binary in a different location, adjust the Framework Search Path (`FRAMEWORK_SEARCH_PATHS`) in your build settings. 3. In your project, select the Service Extension target 4. In the General Settings for your project, in the **Frameworks, Libraries, and Embedded Content** section, add the `MCExtensionSDK` framework. ## Inherit from SFMCNotificationService After you add the dependencies to your project, inherit the main class of the Service Extension from the `SFMCNotificationService` class. If your project is written in Swift, use this code to inherit the service. ```swift import UserNotifications import MCExtensionSDK class NotificationService: SFMCNotificationService { } ``` If your project uses ObjectiveC, use this header. ```objc #import #import @interface NotificationService : SFMCNotificationService @end ``` In your ObjectiveC implementation file, use this code. ```objc #import "NotificationService.h" @implementation NotificationService @end ``` **warning:** Don’t implement any `UNNotificationServiceExtension` methods, such as `func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) → Void)` or `open func serviceExtensionTimeWillExpire()`. ## Additional Configuration Options The `MCExtensionSDK` manages the `UNNotificationServiceExtension` lifecycle methods. You can customize some of the ways the extension behaves. - Enabling or disabling logging and configuring log levels - Downloading and attaching images or videos to push notifications - Adding custom key-value pairs to the notification’s `userInfo` - Performing other necessary operations ### Configure Logging To enable or disable logging and configure log levels, use this code to override the `sfmcProvideConfig()` method: ```swift override func sfmcProvideConfig() → SFNotificationServiceConfig ``` ### Configure Thumbnail To enable or disable the first image of the Carousel template as a thumbnail, use this code to override the `sfmcProvideConfig()` method. ``` override func sfmcProvideConfig() -> SFNotificationServiceConfig { return SFNotificationServiceConfig(logLevel: .debug, shouldShowCarouselThumbnail: false) } ``` Next, set the value of the `shouldShowCarouselThumbnail` property. This property is `true` by default. This property is available in version 9.0.1 and later. ``` - (SFMCNotificationServiceConfig *)sfmcProvideConfig { return [[SFMCNotificationServiceConfig alloc] initWithLogLevel:SFMCExtensionSdkLogLevelDebug shouldShowCarouselThumbnail:NO]; } ``` ### Execute Custom Code To execute custom code, override `func sfmcDidReceive(_ request: UNNotificationRequest, mutableContent: UNMutableNotificationContent, withContentHandler contentHandler: @escaping ([AnyHashable : Any]?) → Void)` to process notifications, such as downloading media or adding custom key-value pairs. This code example depicts a Swift-based implementation where `SFMCNotificationService` is extended to configure logging through `sfmcProvideConfig()` and customize push notification handling in `sfmcDidReceive(_:mutableContent:withContentHandler:)`, allowing for operations like adding custom key-value pairs.
View this code example ```swift import UserNotifications import MCExtensionSDK class NotificationService: SFMCNotificationService { // Use this method to enable logging and change logging levels. override func sfmcProvideConfig() -> SFNotificationServiceConfig { var logLevel: LogLevel = .none #if DEBUG logLevel = .debug #endif return SFNotificationServiceConfig(logLevel: logLevel) } // Use this method only when you need to do custom processing. // Don’t modify mutableContent.request.content.userInfo directly. // To add a custom key in notification userInfo, then return a dictionary in the completion handler. // Like the `UNNotificationServiceExtension` method - func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) → Void), // the system limits the amount of time that can be allocated to performing the processing operation. override func sfmcDidReceive(_ request: UNNotificationRequest, mutableContent: UNMutableNotificationContent, withContentHandler contentHandler: @escaping ([AnyHashable : Any]?) -> Void) { // Your custom code here // Add custom key-value pairs here var customUserInfo: [AnyHashable : Any] = [:] customUserInfo["MyCustomKey"] = "MyCustomValue" // Call the content handler to signal the end of your processing operation. contentHandler(customUserInfo) } } ```
This example shows an Objective-C-based implementation where `SFMCNotificationService` is extended to configure logging and handle custom push notification processing.
View this code example ```objc #import "NotificationService.h" @implementation NotificationService // Use this method to enable logging and change logging levels - (SFMCNotificationServiceConfig *)sfmcProvideConfig { SFMCExtensionSdkLogLevel logLevel = SFMCExtensionSdkLogLevelNone; #if DEBUG logLevel = SFMCExtensionSdkLogLevelDebug; #endif return [[SFMCNotificationServiceConfig alloc] initWithLogLevel: logLevel]; } // Use this method only when you need to do custom processing. // Don’t modify mutableContent.request.content.userInfo directly. // To add a custom key in notification userInfo, then return a dictionary in the completion handler. // Like the `UNNotificationServiceExtension` method - func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) → Void), // the system limits the amount of time that can be allocated to performing the processing operation. - (void)sfmcDidReceiveRequest:(UNNotificationRequest *)request mutableContent:(UNMutableNotificationContent *)mutableContent withContentHandler:(void (^)(NSDictionary * __nullable))contentHandler { // Your custom code here //... // Add custom key-value pairs here NSDictionary *customUserInfo = @{@"MyCustomKey": @"MyCustomValue"}; // Call the content handler to signal the end of your processing operation. contentHandler(customUserInfo); } @end ```
# Configure the Service Extension for the iOS Extension SDK Set up the Notification Service Extension to enable push delivery tracking. ## Add a Service Extension Target The notification service extension runs as a separate bundle within your main app. 1. In Xcode, go to **File** > **New** > **Target**. 2. In the **iOS** > **Application Extension** section, select **Notification Service Extension**. 3. Click **Next**. 4. Configure the app extension and click **Finish**. 5. In your project target’s **General** settings, verify that the new extension is listed under **Frameworks, Libraries, and Embedded Content**. If it’s not there, add it. ![The Frameworks, Libraries, and Embedded Content section for a project, showing the new extension highlighted.](https://developer.salesforce.com/media/quickstart/configure-ext-ios-sdk-2.png) **important:** Use the same Xcode-managed profile for the extension targets as your main app. Match the service extension version to the main app version, and prefix the service extension bundle ID with the main app’s bundle ID. For example, if your main app’s bundle ID is `com.salesforce.MyAwesomeApp`, use `com.salesforce.MyAwesomeApp.MyServiceExtension` for the service extension. ## Integrate the Extension SDK with the Service Extension Choose an integration method based on your project setup. - [Integrate the SDK with CocoaPods](#integrate-the-sdk-with-cocoapods) - [Integrate the SDK with Swift Package Manager (SPM)](#integrate-the-sdk-with-spm) - [Integrate the SDK Manually](#integrate-the-sdk-manually) ### Integrate the SDK with CocoaPods Add the SDK as a dependency in your app’s Podfile. Follow the instructions for [Adding pods to an Xcode project](https://guides.cocoapods.org/using/using-cocoapods.html) in the CocoaPods documentation. After installation completes, open the `.xcworkspace` file that CocoaPods created. **important:** Avoid opening `.xcodeproj` directly. Opening a project file instead of a workspace can lead to errors. ### Integrate the SDK with SPM Integrate the iOS Extension SDK using Swift Package Manager. 1. In Xcode, open your project and select **Project Settings**. 2. Go to the **Package Dependencies** tab, and click **+** to add a new package. 3. Enter the repository URL and add these packages required for your implementation: - [MobileAppMessagingSDK](https://github.com/salesforce-marketingcloud/mam-core-sdk-ios.git) - [PushFeatureSDK](https://github.com/salesforce-marketingcloud/push-feature-sdk-ios.git) 4. Review the package details and confirm to complete the installation. ### Integrate the SDK Manually To integrate the extension SDK manually: 1. Download these SDKs: - [MobileAppMessagingSDK](https://github.com/salesforce-marketingcloud/mam-core-sdk-ios/releases/tag/v1.0.0) - [PushFeatureSDK](https://github.com/salesforce-marketingcloud/push-feature-sdk-ios/releases/tag/v1.0.0) - [SFMCSDK](https://github.com/salesforce-marketingcloud/sfmc-sdk-ios/releases/latest) 2. Copy the relevant `.xcframework` directories from your downloads folder into your project folder. 3. In Xcode, open your project and select the appropriate target. Add the required `.xcframework` files to **Frameworks, Libraries, and Embedded Content** in the target’s General settings. 4. Add `MarketingCloudSDK.bundle` to **Copy Bundle Resources** under **Build Phases**. 5. In **Build Settings**, add `-ObjC` to **Other Linker Flags**. ## Inherit from SFMCNotificationService Remove the autogenerated code from your Service Extension class and inherit from `SFMCNotificationService`.
View Swift code example ```swift import UserNotifications import MCExtensionSDK class NotificationService: SFMCNotificationService { } ```
View Objective-C code example ```objc #import #import @interface NotificationService : SFMCNotificationService @end ``` ```objc #import "NotificationService.h" @implementation NotificationService @end ```
**warning:** Don’t implement any `UNNotificationServiceExtension` methods, such as `func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) → Void)` and `open func serviceExtensionTimeWillExpire()`. The `SFMCNotificationService` class handles these methods. ## Additional Configuration Options The `MCExtensionSDK` manages the `UNNotificationServiceExtension` lifecycle methods. Customize the extension’s behavior to: - Enable or disable logging and configure log levels - Download and attach images or videos to push notifications - Add custom key-value pairs to the notification’s `userInfo` - Perform other operations your app requires ### Configure Logging Enable or disable logging and configure log levels by overriding the `sfmcProvideConfig()` method: `override func sfmcProvideConfig() → SFNotificationServiceConfig` ### Configure Thumbnail Show the first image of a carousel as a thumbnail by overriding the `sfmcProvideConfig()` method and setting `shouldShowCarouselThumbnail` to `false`.
View Swift code example ```swift override func sfmcProvideConfig() -> SFNotificationServiceConfig { return SFNotificationServiceConfig(logLevel: .debug, shouldShowCarouselThumbnail: false) } ```
View Objective-C code example ```objc - (SFMCNotificationServiceConfig *)sfmcProvideConfig { return [[SFMCNotificationServiceConfig alloc] initWithLogLevel:SFMCExtensionSdkLogLevelDebug shouldShowCarouselThumbnail:NO]; } ```
### Execute Custom Code Execute custom code by overriding `func sfmcDidReceive(_ request: UNNotificationRequest, mutableContent: UNMutableNotificationContent, withContentHandler contentHandler: @escaping ([AnyHashable : Any]?) → Void)`. Use this method to process notifications, download media, or add custom key-value pairs. These examples show how to configure logging and customize notification handling.
View Swift code example ```swift import UserNotifications import MCExtensionSDK class NotificationService: SFMCNotificationService { // Use this method to enable logging or change logging levels. override func sfmcProvideConfig() -> SFNotificationServiceConfig { var logLevel: LogLevel = .none #if DEBUG logLevel = .debug #endif return SFNotificationServiceConfig(logLevel: logLevel) } // Use this method to do custom processing, such as image and video downloads or inserting // custom keys in notification userInfo. // Don’t modify `mutableContent.request.content.userInfo` directly. If you need to add a custom // key in notification userInfo, return a dictionary in the completion handler. // The system provides limited time to perform your processing operation. override func sfmcDidReceive(_ request: UNNotificationRequest, mutableContent: UNMutableNotificationContent, withContentHandler contentHandler: @escaping ([AnyHashable : Any]?) -> Void) { // Your custom code here // To add custom key/value pairs in the notifications userInfo object, update this line. var customUserInfo: [AnyHashable : Any] = [:] customUserInfo["MyCustomKey"] = "MyCustomValue" // Call the content handler to signal the end of your processing operation. contentHandler(customUserInfo) } } ```
View Objective-C code example ```objc #import "NotificationService.h" @implementation NotificationService // Use this method to enable logging and change logging levels. - (SFMCNotificationServiceConfig *)sfmcProvideConfig { SFMCExtensionSdkLogLevel logLevel = SFMCExtensionSdkLogLevelNone; #if DEBUG logLevel = SFMCExtensionSdkLogLevelDebug; #endif return [[SFMCNotificationServiceConfig alloc] initWithLogLevel: logLevel]; } // Use this method to do custom processing, such as image and video downloads or inserting // custom keys in notification userInfo. // Don’t modify `mutableContent.request.content.userInfo` directly. If you need to add a custom // key in notification userInfo, return a dictionary in the completion handler. // The system provides limited time to perform your processing operation. - (void)sfmcDidReceiveRequest:(UNNotificationRequest *)request mutableContent:(UNMutableNotificationContent *)mutableContent withContentHandler:(void (^)(NSDictionary * __nullable))contentHandler { // Your custom code here // To add custom key/value pairs in the notifications userInfo object, update this line. NSDictionary *customUserInfo = @{@"MyCustomKey": @"MyCustomValue"}; // Call the content handler to signal the end of your processing operation. contentHandler(customUserInfo); } @end ```
**important:** When you customize `func sfmcDidReceive(_ request: mutableContent: withContentHandler:)`, don’t modify `mutableContent.request.content.userInfo` directly. Use `contentHandler` to add custom key-value pairs. The system provides limited time for processing, so minimize custom processing time and invoke the completion handler on every return path. # Contact Dissociation Sometimes, a contact can become dissociated from any known device. As a result, this contact is no longer targetable by marketers. Contacts who are dissociated from all known devices are sometimes called orphaned contacts. ## Common Causes When a user launches an app for the first time, the SDK initialization process begins. After a successful initialization, the SDK submits a registration request to Marketing Cloud. At this stage, the user is anonymous in Marketing Cloud because the app hasn’t set the contact key for them yet. Marketing Cloud assigns a random GUID as the contact key for these anonymous users. This process allows developers to capture information about anonymous users, and enables marketers to send messages to users who aren’t logged in or identified. After the app identifies the user and sets their contact key, Marketing Cloud creates a contact associated with the device. As part of this process, Marketing Cloud automatically migrates the existing device from the anonymous contact represented by the random GUID and assigns the device to the new contact. The anonymous contact still exists, but has no devices associated with it. Some apps support multiple users. In these apps, different users can log into the same app on the same device, and each user is assigned a unique contact key. However, in Marketing Cloud, a device can only be linked to one contact at a time. Consequently, when a new user logs in and a new contact key is assigned, the contact key of the previously logged-in user is dissociated from the device. Marketers have the option to maintain or delete these dissociated anonymous contacts for billing purposes. ## Avoid Contact Dissociation Depending on your app’s design or usage, it can be difficult to avoid having dissociated contacts. For example, if your goal is to target anonymous users, you could choose to not set a contact key. In such cases, if these anonymous users eventually create an account, their previous anonymous GUID becomes dissociated from any devices. However, you can minimize the likelihood of dissociated contacts by implementing a strategy such as delaying registrations in SDK configuration. ## Delay Registrations Until Contact Key is Set Delaying registrations helps mitigate the possibility of contacts being disassociated from devices. This configuration only registers users when they're identified. Your application is responsible for configuring the SDK to delay registration until the contact key is set. **important:** Use this configuration mode only in situations where devices must be tied to a specific contact key that represents an individual user. Don't use this configuration if you intend to set a generic contact key for your devices and users, or if you plan to send messages to unknown or anonymous users. To delay registration on Android apps, use the `setDelayRegistrationUntilContactKeyIsSet` method.
View code example for SDK version 10 or later ```java SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { engagementModuleConfig = MarketingCloudConfig.builder().apply { // Other configuration values setDelayRegistrationUntilContactKeyIsSet(true) // default = false }.build(applicationContext) }) { // Handle initialization status } ```
View code example for SDK version 8 ```java SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { pushModuleConfig = MarketingCloudConfig.builder().apply { // Other configuration values setDelayRegistrationUntilContactKeyIsSet(true) // default = false }.build(applicationContext) }) { // Handle initialization status } ```
View code example for SDK version 7 ```java MarketingCloudSdk.init(applicationContext as Application, MarketingCloudConfig.builder().apply { // Other configuration values setDelayRegistrationUntilContactKeyIsSet(true) // default = false }.build(applicationContext)) { // Handle initialization status } ```
To delay registration on iOS apps, use the [setDelayRegistrationUntilContactKeyIsSet](/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/marketingcloudsdkconfigbuilder.html) method.
View code example for SDK version 10 or later ```swift let engagementConfiguration = MarketingCloudSdkConfigBuilder(appId: appId) .setAccessToken(accessToken) .setMarketingCloudServerUrl(appEndpoint) .setDelayRegistrationUntilContactKeyIsSet(true) // default = false .build() ```
View code example for SDK version 8 ```swift let mobilePushConfiguration = PushConfigBuilder(appId: appId) .setAccessToken(accessToken) .setMarketingCloudServerUrl(appEndpoint) .setDelayRegistrationUntilContactKeyIsSet(true) // default = false .build() ``` **important:** In the Objective-C SDK 8 for iOS, use the configuration builder with `setDelayRegistrationUntilContactKeyIsSet:@(YES)`
View code example for SDK version 7 ```swift let builder = MarketingCloudSDKConfigBuilder() .sfmc_setApplicationId(appID) .sfmc_setAccessToken(accessToken) .sfmc_setMarketingCloudServerUrl(appEndpoint) .sfmc_setDelayRegistration(untilContactKeyIsSet: true as NSNumber) // default = false .sfmc_build()! ``` **important:** In the Objective-C SDK version 7 for iOS, use the configuration builder with `sfmc_setDelayRegistrationUntilContactKeyIsSet:@(YES)`.
# Contact Dissociation in Android Apps that use SDK Version 10 The process for dissociating contacts has been updated in version 10 of the SDK. To upgrade your app to version 10 of the SDK, first [update the initialization code](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v10.md) -->. Then, use this example to update the contact dissociation code in your app. ```kotlin SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { engagementModuleConfig = MarketingCloudConfig.builder().apply { // Other configuration values setDelayRegistrationUntilContactKeyIsSet(true) // default = false }.build(applicationContext) }) { // TODO handle initialization status } ``` # Contact Dissociation in iOS Apps that use SDK Version 10 The process for dissociating contacts has been updated in version 10 of the SDK. To upgrade your app to version 10 of the SDK, first [update the initialization code](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v10.md). Then, use this example to update the contact dissociation code in your app. ```swift let engagementConfiguration = MarketingCloudSdkConfigBuilder(appId: appId) .setAccessToken(accessToken) .setMarketingCloudServerUrl(appEndpoint) .setDelayRegistrationUntilContactKeyIsSet(true) // default = false .build() ``` # Cordova Plugin Use the [Cordova Plugin](https://github.com/salesforce-marketingcloud/MC-Cordova-Plugin) to implement the Salesforce Engagement SDK for Android and iOS applications built using the Apache Cordova framework. ## Prerequisites First, make sure that you have the latest version of Apache Cordova. See _Cordova Documentation_: [Installation](https://cordova.apache.org/docs/en/latest/guide/cli/installation.html). Next, create and configure your Cordova app. See _Cordova Documentation_: [Creating an App](https://cordova.apache.org/docs/en/latest/guide/cli/index.html). ## Install the Cordova Plugin To install the Cordova plugin in your development environment, complete these steps. 1. At the command line, run this command to add the plugin to your app. ```shell cordova plugin add cordova-plugin-marketingcloudsdk ``` 2. To configure the plugin, the `config.xml` file for your app. ```xml ``` 3. Configure the Engagement SDK in your app. For Android apps, see [Configure the Cordova Plugin for Android Apps](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_development_frameworks_cordova_android.md). For iOS apps, see [Configure the Cordova Plugin for iOS Apps](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_development_frameworks_cordova_ios.md). ## See Also - [Cordova Plugin API Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_development_frameworks_cordova_ref.md) - [Cordova Documentation](https://cordova.apache.org/docs/en/latest/) - _npm_: [cordova-plugin-marketingcloudsdk](https://www.npmjs.com/package/cordova-plugin-marketingcloudsdk) # Cordova Plugin API Reference For reference information about the Cordova plugin for the Salesforce Engagement SDK, see the Cordova Plugin API Reference (this link opens in a new tab). # Cordova Plugin API Reference This section provides reference information for the Cordova plugin for the MobilePush SDK. ## Methods - [addTag](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/addTag.md) - [clearAttribute](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/clearAttribute.md) - [disableLogging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/disableLogging.md) - [disablePush](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/disablePush.md) - [enableLogging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/enableLogging.md) - [enablePush](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/enablePush.md) - [getAttributes](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/getAttributes.md) - [getContactKey](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/getContactKey.md) - [getDeviceId](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/getDeviceId.md) - [getSystemToken](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/getSystemToken.md) - [getTags](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/getTags.md) - [isAnalyticsEnabled](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/isAnalyticsEnabled.md) - [isPiAnalyticsEnabled](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/isPiAnalyticsEnabled.md) - [isPushEnabled](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/isPushEnabled.md) - [logSdkState](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/logSdkState.md) - [removeTag](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/removeTag.md) - [setAttribute](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/setAttribute.md) - [setContactKey](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/setContactKey.md) - [setOnNotificationOpenedListener](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/setOnNotificationOpenedListener.md) - [setOnUrlActionListener](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/setOnUrlActionListener.md) - [setPiAnalyticsEnabled](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/setPiAnalyticsEnabled.md) - [track](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/track.md) ## Typedefs - [MCCordovaPlugin~notificationOpenedCallback](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/typedef_notificationOpenedCallback.md) - [MCCordovaPlugin~urlActionCallback](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/typedef_urlActionCallback.md) # CustomEvent `Class` ## Declaration ```swift @objc(SFMCSdkCustomEvent) public final class CustomEvent : NSObject, UserEvent public let id: String public let name: String public let category: EventCategory public let attributes: [String : Any]? public let userId: String? @objc public let priority: CustomEventPriority @objc public convenience init?(name: String, attributes: [String : Any]? = nil) ``` ## Cases ### `id` ```swift public let id: String ``` --- ### `name` ```swift public let name: String ``` --- ### `category` ```swift public let category: EventCategory ``` --- ### `attributes` ```swift public let attributes: [String : Any]? ``` --- ### `userId` ```swift public let userId: String? ``` --- ### `priority` Priority for this custom event (default: low). Read-only; can be used by MAM and other modules for handling. Only SFMCSDK can set this when creating events. ```swift @objc public let priority: CustomEventPriority ``` --- ### `init(name:attributes:)` Creates a custom event with the given name and optional attributes. Priority is always low when using this initializer. ```swift @objc public convenience init?(name: String, attributes: [String : Any]? = nil) ``` --- # Customize Fonts for In-App Messages on Android By default, in-app messages use the system font of the user’s device. Override the default font face to customize the appearance of the title, body, and button labels for your in-app message. The design of the message determines the font size, so you can’t change it. To set the display font, pass the SDK a valid [TypeFace](https://developer.android.com/reference/android/graphics/Typeface) for the device’s installed fonts, or your app’s custom fonts. ::::::tabset{tabs='["SDK v11", "SDK v10", "SDK v8", "SDK v7"]'} :::::tab Use this code to customize fonts in version 11 of the SDK for Android. ```java // set at configuration time SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { inAppMessagingFeatureModuleConfig = InAppMessagingFeatureConfig.builder().apply { setTypeface(appFontFace) }.build() }) // OR set after configuration time InAppMessagingFeature.requestSdk { inAppMessagingFeatureModule -> inAppMessagingFeatureModule.getInAppMessageManager().setTypeface(appFontFace) } ``` ::::: :::::tab Use this code to customize fonts in version 10 of the SDK for Android. ```java MarketingCloudSdk.requestSdk { engagementSdk -> engagementSdk.inAppMessageManager.setTypeface(appFontFace) } ``` ::::: :::::tab Use this code to customize fonts in version 8 of the SDK for Android. ```java SFMCSdk.requestSdk { sdk -> sdk.mp { it.inAppMessageManager.setTypeface(appFontFace) } } ``` ::::: :::::tab Use this code to customize fonts in version 7 of the SDK for Android. ```java MarketingCloudSdk.requestSdk { sdk-> sdk.inAppMessageManager.setTypeface(appFontFace) } ``` ::::: :::::: # Customize Fonts for In-App Messages on iOS By default, in-app messages use your device’s system font. You can override the default font face to customize the appearance of an in-app message’s `title`, `body`, `button`, and `tertiary text` labels. However, you can’t change the font size because it’s defined by the design of the message. To set the display font, use the `setInAppMessageFont` method to pass the SDK a valid font name. The font you specify must be installed on the device or be present in your app’s custom fonts. ::::::tabset{tabs='["SDK v11", "SDK v10", "SDK v8.1", "SDK v8.0", "SDK v7"]'} :::::tab Use this code to customize fonts in version 11 of the SDK for iOS. ```swift InAppMessagingFeature.requestSdk { iam in iam?.setInAppMessageFont(name: "Zapfino") } ``` ::::: :::::tab Use this code to customize fonts in version 10 of the SDK for iOS. ```swift MarketingCloudSdk.requestSdk { mc in mc?.setInAppMessage(fontName: "Zapfino") } ``` ::::: :::::tab Use this code to customize fonts in version 8.1 of the SDK for iOS. ```swift SFMCSdk.requestPushSdk { mp in mp.setInAppMessage(fontName: "Zapfino") } ``` ::::: :::::tab Use this code to customize fonts in version 8.0 of the SDK for iOS. ```swift // Make sure the SDK is operational SFMCSdk.mp.setInAppMessage(fontName: "Zapfino") ``` ::::: :::::tab Use this code to customize fonts in version 7 of the SDK for iOS. ```swift MarketingCloudSDK.sharedInstance().sfmc_set(inAppMessageFontName: "Zapfino") ``` ::::: :::::: If the font isn’t found, the SDK returns `false` and uses the system font. # Customize Push Notification Functionality for Android Apps The Salesforce Engagement SDK offers several customization options that extend push notification support for Android. Customize notification channels, launch intents, tap actions, and display properties to create a tailored experience for your app users. ## Customization Options Start with [Customize Push Notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_android_customize_basic.md) to learn how to customize notifications, launch intents, and tap actions. For complete control over your notifications, see [Advanced Push Notification Customization](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_android_customize_full_control.md). This approach lets you manage all aspects of notification display properties and tap actions, including notification channel creation and launch intent actions. ## Notification Channels Versions 8.0 and later of the Android operating system require you to specify a notification channel. The SDK creates a default channel called `marketing`, but you can also [create custom notification channels](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_android_custom_notification.md). ## Interactive Notifications [Configure the actions](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_android_button_carousel.md) that occur when a user taps a button or a carousel image in a push notification. ## Notification Segmentation Deliver location messages to specific audience segments by [implementing logic that determines whether to display a notification](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_android_subsegments_send.md). By using segmentation, your app can assess factors like user preferences, login status, custom profile data, or regional information before showing a message. ## Analytics and Advanced Features Track successful delivery of your messages by using [push delivery analytics](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_android_push_analytics_enable.md). # Customize Push Notification Functionality for iOS Apps The Salesforce Engagement SDK offers several customization options that extend push notification support for iOS. Customize sounds, add interactive buttons, include rich media, handle URLs, and send custom data to create a tailored experience for your app users. ## Custom Sounds [Play a custom sound](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_sounds_customize.md) when a push notification arrives. Include a sound file in your app bundle and enable the custom sound option on the MobilePush Administration page. ## Interactive Notifications [Add buttons to push notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_interactive_notifications.md) to enable user interactions directly from the notification. Create notification categories with actions, and Engagement sends the category name in the message payload. Your app responds when a user interacts with a button. ## Rich Notifications [Include images and videos in your notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_rich_notifications.md) to create more engaging messages. Rich notifications support titles, subtitles, and mutable content that can include personalization. A Notification Service Extension handles media downloads and attachment creation. ## Custom Keys [Send extra data with push notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_custom_keys_handle.md) by using custom keys. Use custom keys to add tracking, pass additional information, or trigger specific app functionality. Your push notification handler extracts the values from the notification’s `userInfo` dictionary. ## URL Handling The SDK doesn’t automatically present URLs from CloudPages or OpenDirect push notifications. [Implement URL handling](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_urls_handle.md) to control how your app responds to URLs in push notifications and inbox messages. For OpenDirect-specific guidance, see [Messages with an OpenDirect URL](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_opendirect_urls_handle.md). ## Analytics Track successful delivery of your messages by using [push delivery analytics](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_push_analytics_enable.md). Versions 9.0.0 and later of the SDK track when push notifications reach the SDK. # Customize Push Notifications for Android The `NotificationCustomizationOptions` class of the Salesforce Engagement SDK facilitates push notification customization through a [NotificationChannelIdProvider](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.notifications/-notification-manager/-notification-channel-id-provider/index.html), enabling the assignment of a specific [Notification Channel](https://developer.android.com/develop/ui/views/notifications/channels) for each `NotificationMessage`. Additionally, [NotificationLaunchIntentProvider](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.notifications/-notification-manager/-notification-launch-intent-provider/index.html) defines the action to take when a user taps a [NotificationMessage](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushmodelsmodule/com.salesforce.marketingcloud.pushmodels/-notification-message/index.html), alongside your application’s notification icon. **note:** When you target apps that run Android 12 or later, specify the mutability of your Pending Intent. See _Android Developer Documentation_: [Intents and Intent Filters](https://developer.android.com/guide/components/intents-filters#DeclareMutabilityPendingIntent). ::::::tabset{tabs='["SDK v10+", "SDK v8", "SDK v7"]'} :::::tab ```java SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { this.pushFeatureModuleConfig = PushFeatureConfig.builder().apply { // Other configuration values setNotificationCustomizationOptions( NotificationCustomizationOptions.create(R.drawable.ic_notification_icon, NotificationManager.NotificationLaunchIntentProvider { context, notificationMessage -> val requestCode = Random().nextInt() val url = notificationMessage.url when { url.isNullOrEmpty() -> PendingIntent.getActivity( context, requestCode, Intent(context, MainActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) else -> PendingIntent.getActivity( context, requestCode, Intent(Intent.ACTION_VIEW, url.toUri()), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) } }, NotificationManager.NotificationChannelIdProvider { context, notificationMessage -> if (TextUtils.isEmpty(notificationMessage.url)) { NotificationManager.createDefaultNotificationChannel(context) } else { "UrlNotification" } } ) ) }.build() }) { // Handle initialization status } ``` ::::: :::::tab ``` SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { pushModuleConfig = MarketingCloudConfig.builder().apply { // Other configuration values setNotificationCustomizationOptions( NotificationCustomizationOptions.create(R.drawable.ic_notification_icon, NotificationManager.NotificationLaunchIntentProvider { context, notificationMessage -> val requestCode = Random().nextInt() val url = notificationMessage.url when { url.isNullOrEmpty() -> PendingIntent.getActivity( context, requestCode, Intent(context, MainActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) else -> PendingIntent.getActivity( context, requestCode, Intent(Intent.ACTION_VIEW, Uri.parse(url)), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) } }, NotificationManager.NotificationChannelIdProvider { context, notificationMessage -> if (TextUtils.isEmpty(notificationMessage.url)) { NotificationManager.createDefaultNotificationChannel(context) } else { "UrlNotification" } } ) ) }.build(applicationContext) }) { // TODO handle initialization status } ``` ::::: :::::tab ``` MarketingCloudSdk.init(applicationContext as Application, MarketingCloudConfig.builder().apply { // Other configuration values setNotificationCustomizationOptions( NotificationCustomizationOptions.create(R.drawable.ic_notification_icon, NotificationManager.NotificationLaunchIntentProvider { context, notificationMessage -> val requestCode = Random().nextInt() val url = notificationMessage.url() when { url.isNullOrEmpty() -> PendingIntent.getActivity( context, requestCode, Intent(context, MainActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) else -> PendingIntent.getActivity( context, requestCode, Intent(Intent.ACTION_VIEW, Uri.parse(url)), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) } }, NotificationManager.NotificationChannelIdProvider { context, notificationMessage -> if (TextUtils.isEmpty(notificationMessage.url())) { NotificationManager.createDefaultNotificationChannel(context) } else { "UrlNotification" } } ) ) }.build(applicationContext)) { // TODO handle initialization status } ``` ::::: :::::: ### Icons The SDK supports icons in various notification elements, including small icons (in the status bar and notification header), large icons (in the notification body) and rich button icons. You can use icons by placing icon files in the PNG format inside `drawables-**hdpi` folders within your client app’s resources. The SDK then references these icons by their resource names (for example, `ic_notification_icon`). Here’s how you can configure and set icons: - Small icons: Provide the resource ID within `NotificationCustomizationOptions` when using `MarketingCloudConfigBuilder`. Alternatively, you can specify the icon’s resource name directly in the Engagement UI. - Large icons: Provide the resource name and optional public URL for remote retrieval in the Engagement UI. - Rich button icons: Provide the resource names in the Engagement UI. For example, to use an icon named `ic_notification_icon.png`, place it in the appropriate `drawables-**hdpi` folder. Then, provide `ic_notification_icon` as the resource name on the Engagement UI. If its a small icon, you can also specify the resource ID in `NotificationCustomizationOptions` when using `MarketingCloudConfigBuilder`. ### Sound You can customize notification channels by setting priorities, colors, and sounds. To use a custom sound in notifications, follow these steps: 1. Add the sound file to the app’s `res/raw/` folder. 2. Create a notification channel for the audio file and configure it in the code using `NotificationChannelIdProvider`. This sample code creates a notification channel named `myaudio`, enables badges and lights, and sets a default importance level. ``` /* Create a notification channel for the audio file */ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { androidNotificationManager.createNotificationChannel( NotificationChannel( "myaudio", "myaudio", AndroidNotificationManager.IMPORTANCE_DEFAULT ).apply { setShowBadge(true) enableLights(true) setSound( Uri.parse("android.resource://${context.packageName}/${context.resources.getIdentifier("custom","raw", context.packageName)}"), AudioAttributes.Builder().setUsage( AudioAttributes.USAGE_NOTIFICATION_EVENT ).build() ) }) } ``` 3. In the Marketing Cloud Engagement UI, set the sound file name and extension in the **Custom** section of Sound settings. Custom sounds can use these file formats: `.mp3`, `.wav`, `.aac`, `.m4a` This sample code configures the SDK for an Android application. It sets up notification customization options, including the small icon, launch intent, and notification channel ID. ``` SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { pushModuleConfig = MarketingCloudConfig.builder().apply { // Other configuration values setNotificationCustomizationOptions( // Set small icon via NotificationCustomizationOptions NotificationCustomizationOptions.create(R.drawable.ic_notification_icon, NotificationManager.NotificationLaunchIntentProvider { context, notificationMessage -> val requestCode = Random().nextInt() val url = notificationMessage.url when { url.isNullOrEmpty() -> PendingIntent.getActivity( context, requestCode, Intent(context, MainActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) else -> PendingIntent.getActivity( context, requestCode, Intent(Intent.ACTION_VIEW, Uri.parse(url)), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) } }, NotificationManager.NotificationChannelIdProvider { context, notificationMessage -> if (TextUtils.isEmpty(notificationMessage.url)) { NotificationManager.createDefaultNotificationChannel(context) } else if(notificationMessage.sound == NotificationMessage.Sound.CUSTOM) { notificationMessage.soundName // This will be myaudio if sound sent with push is myaudio.mp3 } else { "UrlNotification" } } ) ) }.build(applicationContext) }) { // TODO handle initialization status } ``` # Data Protection and Privacy The Engagement SDK helps you comply with data protection regulations, such as the European Union’s General Data Protection Regulation (GDPR). The SDK supports three privacy modes that affect your app’s ability to send messages and collect data: - [Right to be Forgotten](#right-to-be-forgotten) - [Restriction of Processing](#restriction-of-processing) - [Do Not Track](#do-not-track) **note:** These data protection and privacy features are available only in Marketing Cloud Engagement. ## Right to Be Forgotten Use Right to Be Forgotten mode when a contact requests that you remove all their data from Marketing Cloud Engagement. This mode marks a contact, identified by the SDK’s [contact key string](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_register_contacts_devices/mc_engagement_register_contacts_devices_determine_key_strategy.md), as `forgotten`. This setting prevents data collection from that contact and blocks messages to them. **note:** By default, this suppression lasts for 14 days. You can configure the suppression period in Contact Builder in Marketing Cloud Engagement. At the end of the suppression period, Marketing Cloud Engagement permanently deletes the contact data. The SDK restricts all functionality after it receives the first Right to Be Forgotten mode change for a contact from the server. The SDK receives this change through a silent push notification or when your app enters the foreground. Right to Be Forgotten mode disables these functions for that contact for the life of your app: - Push notifications - Analytics tracking - Inbox messaging - Geofence and beacon messaging - Configuration changes When a contact deletes and reinstalls your app on their device, they move out of Right to Be Forgotten mode. ## Restriction of Processing Restriction of Processing mode marks a contact, identified by the SDK’s contact key string, as restricted from data processing. Restriction of Processing mode restricts these data operations for the contact: - Modifying information - Deleting information - Changing registration state - Sending pushes - Creating inbox messages - Processing Analytics The SDK restricts all functionality after it receives a Restriction of Processing mode change for a contact. This mode completely disables these functions when the contact is in a restricted state: - Push notifications - Analytics tracking - Inbox messaging - Geofence and beacon messaging - Configuration changes When the contact moves out of the restriction state, the SDK receives notification through a silent push notification or when your app enters the foreground. The SDK automatically reconfigures itself based on your last-used configuration settings. ## Do Not Track Do Not Track mode marks a contact, identified by the SDK’s contact key string, as restricted from tracking activities. This setting restricts data operations that collect or act on Personally Identifiable Information (PII). When a contact moves to Do Not Track mode, the SDK restricts functionality after it receives the first mode change from the server through a silent push notification or when your app enters the foreground. This mode completely disables behavioral analytic tracking, geofences, and beacons. Push notifications and inbox functionality continue to work. In the Do Not Track state, the SDK can still track message delivery receipts and changes in registration attributes, such as tags and attributes. Behavioral analytic tracking includes these events: - User events - Message open events - App open and close events When the contact moves out of the Do Not Track state, the SDK receives notification through a silent push notification or when your app enters the foreground. The SDK automatically reconfigures itself based on your last-used configuration settings. ## Prepare for Data Privacy Compliance All recent versions of the SDK include the architecture required to enable data compliance functionality. Version 5.5.0 and later of the SDK for Android and version 5.1.0 and later of the SDK for iOS include this functionality. If your app uses an earlier version of the SDK, upgrade it. In iOS apps, enable background refresh to ensure that silent pushes work as expected. For more information on data protection, see [iOS Data Protection](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting/mc_engagement_troubleshooting_ios_data_protection.md). ## See Also - [Salesforce Privacy](https://www.salesforce.com/privacy/overview/) # Delay Registrations Until Contact Key is Set on Android Delaying registrations helps mitigate the possibility of contacts being disassociated from devices. This configuration only registers users when they’re identified. Your application is responsible for configuring the SDK to delay registration until the contact key is set. **important:** Use this configuration mode only in situations where devices must be tied to a specific contact key that represents an individual user. Don’t use this configuration if you intend to set a generic contact key for your devices and users, or if you plan to send messages to unknown or anonymous users. To delay registration on Android apps, use the `setDelayRegistrationUntilContactKeyIsSet` method. ::::::tabset{tabs='["SDK v10+", "SDK v8", "SDK v7"]'} :::::tab This code example shows how to delay registration on Android apps that use SDK version 10 or higher. ``` SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { engagementModuleConfig = MarketingCloudConfig.builder().apply { // Other configuration values setDelayRegistrationUntilContactKeyIsSet(true) // default = false }.build(applicationContext) }) { // Handle initialization status } ``` ::::: :::::tab This code example shows how to delay registration on Android apps that use SDK version 8. ``` SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { pushModuleConfig = MarketingCloudConfig.builder().apply { // Other configuration values setDelayRegistrationUntilContactKeyIsSet(true) // default = false }.build(applicationContext) }) { // Handle initialization status } ``` ::::: :::::tab This code example shows how to delay registration on Android apps that use SDK version 7. ``` MarketingCloudSdk.init(applicationContext as Application, MarketingCloudConfig.builder().apply { // Other configuration values setDelayRegistrationUntilContactKeyIsSet(true) // default = false }.build(applicationContext)) { // Handle initialization status } ``` ::::: :::::: # Delay Registrations Until Contact Key is Set on iOS Delaying registrations helps mitigate the possibility of contacts being disassociated from devices. This configuration only registers users when they’re identified. Your application is responsible for configuring the SDK to delay registration until the contact key is set. **important:** Use this configuration mode only in situations where devices must be tied to a specific contact key that represents an individual user. Don’t use this configuration if you intend to set a generic contact key for your devices and users, or if you plan to send messages to unknown or anonymous users. To delay registration on iOS apps, use the [setDelayRegistrationUntilContactKeyIsSet](/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/marketingcloudsdkconfigbuilder.html) method in version 11 of the SDK, or its equivalent in earlier versions of the SDK. ::::::tabset{tabs='["SDK v10+", "SDK v8", "SDK v7"]'} :::::tab This code example shows how to delay registration on iOS apps that use SDK version 10 or higher. ```swift let engagementConfiguration = MarketingCloudSdkConfigBuilder(appId: appId) .setAccessToken(accessToken) .setMarketingCloudServerUrl(appEndpoint) .setDelayRegistrationUntilContactKeyIsSet(true) // default = false .build() ``` ::::: :::::tab This code example shows how to delay registration on iOS apps that use SDK version 8. ```swift let mobilePushConfiguration = PushConfigBuilder(appId: appId) .setAccessToken(accessToken) .setMarketingCloudServerUrl(appEndpoint) .setDelayRegistrationUntilContactKeyIsSet(true) // default = false .build() ``` **important:** In the Objective-C SDK 8.x for iOS, use the configuration builder with `setDelayRegistrationUntilContactKeyIsSet:@(YES)` ::::: :::::tab This code example shows how to delay registration on iOS apps that use SDK version 7. ```swift let builder = MarketingCloudSDKConfigBuilder() .sfmc_setApplicationId(appID) .sfmc_setAccessToken(accessToken) .sfmc_setMarketingCloudServerUrl(appEndpoint) .sfmc_setDelayRegistration(untilContactKeyIsSet: true as NSNumber) // default = false .sfmc_build()! ``` **important:** In the Objective-C SDK version 7.x for iOS, use the configuration builder with `sfmc_setDelayRegistrationUntilContactKeyIsSet:@(YES)`. ::::: :::::: # deleteMessage Deletes a specific inbox message. ## Syntax ```dart Future deleteMessage(String messageId) ``` ## Parameters - `messageId` (String) - The unique identifier of the message to delete ## Returns - `Future` - Completes when the message has been deleted. ## Example ```dart try { await SfmcSdk.deleteMessage('msg123'); print('Message deleted'); } catch (e) { print('Failed to delete message: $e'); } ``` ## Related Methods - [setMessageRead()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_setMessageRead.md) - [markAllMessagesDeleted()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_markAllMessagesDeleted.md) # DeliverOrderEvent ## Package `com.salesforce.marketingcloud.sfmcsdk.components.events` ## Description **Class:** `DeliverOrderEvent` **Inheritance:** Extends `OrderEvent` An E-commerce event class for managing order delivery details within the Salesforce Marketing Cloud Unified SDK. ## Platform - **Target:** androidJvm ## Class Declaration ```kotlin class DeliverOrderEvent : OrderEvent ``` ## Overview This class is part of the SFMC SDK v3.1.0 event system and specializes in handling delivery-related order events. As a subclass of `OrderEvent`, it inherits base order functionality while providing specific capabilities for delivery tracking. ## Related Classes - Parent class: `OrderEvent` # Determine Your Contact Key Strategy A contact key is a unique identifier that represents an individual in Marketing Cloud and is required when sending messages. In Marketing Cloud Engagement, the contact key is used to map and unify an individual’s identity across Email, MobileConnect, and MobilePush. It also unifies, aggregates, and helps identify each contact’s devices. You can use the SDK to manually specify the contact key. If you don’t specify the contact key, the SDK assigns each contact a random GUID as the contact key. Review these use cases and implications for each option. Work with your marketing team to determine your contact key strategy. Your strategy can influence your approach to implementing the registration of contacts and devices. It’s also important to decide on your contact key strategy because frequent changes to a user’s contact key can lead to contacts being disassociated or orphaned from a device. It can also cause confusion when sending to contacts, and while troubleshooting implementation and billing issues. Also determine whether to send messages to anonymous users only, known users only, or both. ## Message Targeting and Contact Key Timing - Send to both anonymous and known users - : To send to both anonymous and known users, set the contact key after you’ve identified the user (after they create an account and log in), but don’t delay registrations. Sending to both anonymous and known users can cause contacts to become disassociated from a device (orphaned), but your marketer can manage these contacts in Engagement. - Send only to known users - : To send only to known users, set the contact key yourself, and delay registration of anonymous users in the SDK until the contact key is set. Delaying registration until after the user is known prevents contacts from being disassociated from a device. - Send only to anonymous users - : To send to anonymous users only, don’t set the contact key, and don’t delay registrations. For information about delaying registrations until the contact key is set, see [Contact Dissociation](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_register_contacts_devices_contact_dissociation.md). ## Contact Key Selection Set the contact key to a specific value provided by your end user or to a unique identifier. Use a value such as a customer ID, mobile number, email address, or loyalty number. This value should be the same identifier that your company uses to identify the user across other Marketing Cloud Engagement channels, such as email and SMS. The contact key must meet these requirements: - It can’t be null or an empty string. - It can’t have leading or trailing whitespaces. - After it’s set, you can change the contact key for a contact, but you can’t clear it. - It must be unique. # Developer Resources Use these resources to learn more about Marketing Cloud and implement the Salesforce Engagement SDK. ## Marketing Cloud Documentation The Help documentation for Marketing Cloud Engagement and Marketing Cloud Next contains important information about setting up and using your Marketing Cloud account. - _Salesforce Help_: [Marketing Cloud Engagement](https://help.salesforce.com/s/articleView?id=mktg.mc_overview_marketing_cloud.htm) - _Salesforce Help_: [Marketing Cloud Next](https://help.salesforce.com/s/articleView?id=mktg.mktg_main.htm) Both documents contain information related to managing mobile app messages. - [MobilePush for Marketing Cloud Engagement](https://help.salesforce.com/s/articleView?id=mktg.mc_mp_mobilepush.htm) - [Mobile Apps in Marketing Cloud Next](https://help.salesforce.com/s/articleView?id=mktg.mc_overview_marketing_cloud.htm) ## Example Apps These open-source example apps demonstrate several best practices for using the SDK. - [iOS Learning App](https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS/tree/master/examples) - [Android Learning App](https://github.com/salesforce-marketingcloud/MarketingCloudSDK-Android) ## SDK Repositories These repositories contain the source code for the SDKs. - [Android SDK](https://github.com/salesforce-marketingcloud/MarketingCloudSDK-Android) - [iOS App SDK](https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS) - [iOS Extension SDK](https://github.com/salesforce-marketingcloud/extension-sdk-ios) Marketing Cloud Engagement includes support for third-party development frameworks. These repositories contain the source code for the Cordova, Flutter, and React Native libraries. - [Cordova Github repository](https://github.com/salesforce-marketingcloud/MC-Cordova-Plugin) - [Cordova npm package](https://www.npmjs.com/package/cordova-plugin-marketingcloudsdk) - [Flutter GitHub repository](https://github.com/salesforce-marketingcloud/sdk-flutter-plugin) - [Flutter package](https://pub.dev/packages/sfmc) - [React Native GitHub repository](https://github.com/salesforce-marketingcloud/react-native-marketingcloudsdk) - [React Native npm package](https://www.npmjs.com/package/react-native-marketingcloudsdk) ## Marketing Cloud Engagement REST API Marketing Cloud Engagement includes REST APIs for sending mobile app messages. - _Salesforce Developers_: [MobilePush REST APIs](https://developer.salesforce.com/docs/marketing/marketing-cloud/references/mc_rest_push) - _Salesforce Developers_: [MobilePush Transactional APIs](https://developer.salesforce.com/docs/marketing/marketing-cloud/references/mc_rest_transactional_messaging_push?meta=Summary) # Development Frameworks The Marketing Cloud Engagement SDK supports multiple development frameworks beyond native iOS and Android, enabling you to integrate push notifications, analytics, and location-based messaging into cross-platform and hybrid mobile applications. Use these framework-specific plugins and modules to access SDK functionality within your preferred development environment. ## Supported Frameworks Choose your development framework to access implementation guides, platform-specific configuration, and API references for integrating the Marketing Cloud SDK. ### Cordova Apache Cordova is an open-source mobile development framework maintained by the Apache Software Foundation. It enables developers to build mobile applications using standard web technologies (HTML, CSS, and JavaScript) while accessing native device capabilities through plugins. Cordova wraps web applications in native containers, allowing a single codebase to run on multiple platforms. [Implement the Marketing Cloud SDK in Cordova applications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_development_frameworks_cordova.md) using the Cordova plugin. Configure push notifications, analytics, and location messaging for both iOS and Android platforms within your hybrid mobile app. ### Flutter Flutter is an open-source UI framework created by Google for building natively compiled applications from a single codebase. Built on the Dart programming language, Flutter provides a rich set of pre-built widgets and tools for creating high-performance mobile, web, and desktop applications. Flutter compiles to native ARM code, delivering performance close to native apps while maintaining cross-platform compatibility. [Implement the Marketing Cloud SDK in Flutter applications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_development_frameworks_flutter.md) using the Flutter plugin. Access native SDK features through Dart code to enable push notifications, track analytics, and configure location-based messaging for cross-platform Flutter apps. ### React Native React Native is an open-source framework developed by Meta for building native mobile applications using JavaScript and React. It allows developers to write mobile apps using familiar web development patterns while rendering native UI components. React Native bridges JavaScript code with native platform APIs, providing near-native performance and a native look and feel across iOS and Android. [Implement the Marketing Cloud SDK in React Native applications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_development_frameworks_react_native.md) using the React Native module. Integrate push notifications, analytics, and location messaging into your JavaScript-based mobile applications with native performance. ### Ionic and Capacitor Ionic is an open-source framework for building cross-platform mobile applications using web technologies, maintained by Ionic. Capacitor, also developed by Ionic, is a modern native runtime that serves as a spiritual successor to Cordova. Capacitor provides a consistent API for accessing native functionality while embedding web applications in native containers. It offers high performance, simpler plugin development, and first-class support for modern web applications. [Implement the Marketing Cloud SDK in Ionic and Capacitor applications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_development_frameworks_ionic_capacitor.md) using the Capacitor-compatible wrapper. Enable push notifications and SDK features in your web-based mobile applications built with Ionic framework. ## Feature Support Each framework plugin provides access to core SDK capabilities including: - Push notification registration and handling - Contact and device registration - Analytics tracking for push opens and custom events - In-app messaging display and tracking - Inbox messaging retrieval and management - Location-based messaging with geofences and beacons - Custom attributes and tags for contact data - Runtime SDK configuration and management For detailed method signatures and platform-specific implementation guidance, see the API reference for each framework. # disableLogging Disables verbose logging within the native MobilePush SDK. ## Syntax `MCCordovaPlugin.disableLogging([successCallback], [errorCallback])` ## Kind Static method of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | ----------------- | ---------- | ----------- | | `successCallback` | `function` | | | `errorCallback` | `function` | | ## See Also - [Troubleshoot Issues in Android Apps](/docs/marketing/mobilepush/guide/troubleshooting-android.html#check-the-sdks-log-output) - _SDK Reference for iOS_: [Logger Methods](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/ios-sdk-v11/sfmc-sdk/classes/sfmcsdk.md#logger-methods) # disableLogging Disables SDK logging. ## Syntax ```dart Future disableLogging() ``` ## Returns - `Future` - Completes when logging has been disabled. ## Example ```dart try { await SfmcSdk.disableLogging(); print('SDK logging disabled'); } catch (e) { print('Failed to disable logging: $e'); } ``` ## Related Methods - [enableLogging()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_enableLogging.md) - [logSdkState()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_logSdkState.md) # disableLogging Disables verbose logging within the native MobilePush SDK. ## Syntax ```javascript MCReactModule.disableLogging(); ``` ## Returns - `void` - No return value. ## Example ```javascript import { MCReactModule } from "react-native-marketingcloudsdk"; const disableSDKLogging = () => { try { MCReactModule.disableLogging(); console.log("SDK logging disabled"); } catch (error) { console.error("Error disabling logging:", error); } }; ``` ## See Also - [enableLogging() Methods](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_enableLogging.md) - [logSdkState() Methods](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_logSdkState.md) - [Troubleshoot Issues in Android Apps](/docs/marketing/mobilepush/guide/troubleshooting-android.html#check-the-sdks-log-output) - _SDK Reference for iOS_: [Logger Methods](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/ios-sdk-v11/sfmc-sdk/classes/sfmcsdk.md#logger-methods) # disablePush Disables push messaging in the native MobilePush SDK. ## Syntax `MCCordovaPlugin.disablePush([successCallback], [errorCallback])` ## Kind Static method of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | ----------------- | ---------- | ----------- | | `successCallback` | `function` | | | `errorCallback` | `function` | | # disablePush Disables push notifications for the device. ## Syntax ```dart Future disablePush() ``` ## Returns - `Future` - Completes when push notifications have been disabled. ## Example ```dart try { await SfmcSdk.disablePush(); print('Push notifications disabled successfully'); } catch (e) { print('Failed to disable push notifications: $e'); } ``` ## Related Methods - [isPushEnabled()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_isPushEnabled.md) - [enablePush()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_enablePush.md) # disablePush Disables push messaging in the MobilePush SDK. ## Syntax ```javascript MCReactModule.disablePush(); ``` ## Returns - `void` - No return value. ## Example ```javascript import { MCReactModule } from "react-native-marketingcloudsdk"; const disablePushNotifications = () => { try { MCReactModule.disablePush(); console.log("Push notifications disabled"); } catch (error) { console.error("Error disabling push:", error); } }; ``` ## See Also - [isPushEnabled() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_isPushEnabled.md) - [enablePush() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_enablePush.md) # Display Interactive Notifications Use interactive notifications to add buttons to push notifications from your mobile app. Marketing Cloud Engagement sends the category name for these interactive notifications in the message payload. 1. Set up interactive notifications for your app using the sample code below. Adapt it to your specific requirements. The sample code applies to the `AppDelegate.m` `didFinishLaunchingWithOptions` application delegate method and shows how to create a category named `Example`. When you send this category with the payload from Marketing Cloud Engagement, the message appears in the notification center with buttons for user interaction. 2. Examine the push notification’s payload in your push handler to check if your action triggered and your app performed the necessary response. 3. After setup, work with an admin to enable interactive notifications on the MobilePush Administration page. ![The MobilePush Administration page in the Marketing Cloud Engagement UI, showing the Interactive Notifications option enabled.](https://developer.salesforce.com/media/push-messaging/interactive-notification-marketer-setup.png) Configure the SDK to create notification categories with custom actions. This code creates a category named `Example` with an action button. When Marketing Cloud Engagement sends a notification with this category, the notification displays with buttons that users can tap to trigger specific actions in your app. ::::::tabset{tabs='["SDK v10+", "SDK v8", "SDK v7"]'} :::::tab ```swift func configureSdk() -> Bool { // Enable logging for debugging early on. Debug level is not recommended for // production apps, because a large amount of data is logged to the console. #if DEBUG SFMCSdk.setLogger(logLevel: .debug) #endif // Use the `MarketingCloudSdkConfigBuilder` to configure the MarketingCloud // SDK. This gives you the maximum flexibility in SDK configuration. // The builder lets you configure the module parameters at runtime. let engagementConfiguration = MarketingCloudSdkConfigBuilder(appId: appId) .setAccessToken(accessToken) .setMarketingCloudServerUrl(URL(string: appEndpoint)!) .setMid(mid) .setInboxEnabled(inbox) .setLocationEnabled(location) .setAnalyticsEnabled(pushAnalytics) .build() // Set the completion handler to take action when all modules initialization // is completed. Setting the completion handler is optional. let completionHandler: ((_ status: [ModuleInitStatus]) -> Void) = { [weak self] status in DispatchQueue.main.async { self?.handleSDKInitializationCompletion(status: status) } } SFMCSdk.initializeSdk( ConfigBuilder().setEngagement(config: engagementConfiguration).build(), completion: completionHandler ) return true } // MARK: - SDK Initialization Completion Handler private func handleSDKInitializationCompletion(status: [ModuleInitStatus]) { var allSuccessful = true for moduleStatus in status { print("Module: \(moduleStatus.moduleName.rawValue), Status: \(moduleStatus.initStatus.rawValue)") if moduleStatus.initStatus == .success { // Handle successful initialization for each module switch moduleStatus.moduleName { case .engagement: setupEngagement() default: break } } else if moduleStatus.initStatus == .error { allSuccessful = false // module failed to initialize, check logs for more details } else if moduleStatus.initStatus == .cancelled { allSuccessful = false // module initialization was cancelled (for example due to // re-configuration triggered before init was completed) } else if moduleStatus.initStatus == .timeout { allSuccessful = false // module failed to initialize due to timeout, check logs for more details } } if allSuccessful { print("SDK initialization completed successfully") } else { print("SDK initialization completed with errors - check logs above") } } func setupEngagement() { // Get the LocationDelegate to a class adhering to the protocol. // In this example, the AppDelegate class adheres to the protocol (see below) // and handles URLs passed back from the SDK. // For more information, see MarketingCloudSdk.requestSdk { mc in mc?.addTag("Hiking Supplies") } // Make sure to dispatch this to the main thread. UNUserNotificationCenter // causes the app to show UI elements. DispatchQueue.main.async { // Set the delegate if needed, request authorization. If you use a //delegate, set it here. UNUserNotificationCenter.current().delegate = self UNUserNotificationCenter.current().requestAuthorization( options: [.alert, .sound, .badge], completionHandler: {(_ granted: Bool, _ error: Error?) -> Void in if error == nil { (if granted == true { // If app is authorized to use notifications, request a //device token. DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } // Support notification categories let exampleAction = UNNotificationAction( identifier: "App", title: "Example", options: [] ) let appCategory = UNNotificationCategory( identifier: "Example", actions: [exampleAction], intentIdentifiers: [] as? [String] ?? [String](), options: [] ) let categories = Set([appCategory]) UNUserNotificationCenter.current().setNotificationCategories( categories as? Set ?? Set() ) }) } }) } } func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. self.configureSdk() return true } ``` ::::: :::::tab ```swift func configureSdk() -> Bool { #if DEBUG SFMCSdk.setLogger(logLevel: .debug) #endif let mobilePushConfiguration = PushConfigBuilder(appId: appId) .setAccessToken(accessToken) .setMarketingCloudServerUrl(appEndpoint) .setMid(mid) .setInboxEnabled(inbox) .setLocationEnabled(location) .setAnalyticsEnabled(pushAnalytics) .build() let completionHandler: (OperationResult) -> () = { result in if result == .success { // This is a good place to set the contact key, tags, and attributes, // because we know the SDK is ready. self.setupMobilePush() } else { os_log("The SDK configuration failed. Current status: %@", result.rawValue) } } SFMCSdk.initializeSdk(ConfigBuilder().setPush(config: mobilePushConfiguration, onCompletion: completionHandler).build()) return true } func setupMobilePush() { SFMCSdk.identity.setProfileId("user@example.com") SFMCSdk.identity.setProfileAttributes([["FavoriteTeamName": "favoriteTeamName"]]) SFMCSdk.requestPushSdk { mp in mp.addTag("Hiking Supplies") } DispatchQueue.main.async { // Set the delegate if needed. Then, ask if we're authorized - the delegate must be set here if used UNUserNotificationCenter.current().delegate = self UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {(_ granted: Bool, _ error: Error?) -> Void in if error == nil { if granted == true { // we are authorized to use notifications, request a device token for remote notifications DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } // Support notification categories let exampleAction = UNNotificationAction(identifier: "App", title: "Example", options: []) let appCategory = UNNotificationCategory(identifier: "Example", actions: [exampleAction], intentIdentifiers: [] as? [String] ?? [String](), options: []) let categories = Set([appCategory]) UNUserNotificationCenter.current().setNotificationCategories(categories as? Set ?? Set()) } } }) } } // REQUIRED IMPLEMENTATION func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { return self.configureSdk() } ``` ::::: :::::tab ```swift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { var error: NSError? let success: Bool = MarketingCloudSDK.sharedInstance().sfmc_configure(&error) if success == true { // The SDK has been fully configured and is ready for use! // Turn on logging for debugging. Not recommended for production apps. MarketingCloudSDK.sharedInstance().sfmc_setDebugLoggingEnabled(true) // Great place for setting the contact key, tags and attributes since you know the SDK is setup and ready. MarketingCloudSDK.sharedInstance().sfmc_setContactKey("user@example.com") MarketingCloudSDK.sharedInstance().sfmc_addTag("Hiking Supplies") MarketingCloudSDK.sharedInstance().sfmc_setAttributeNamed("FavoriteTeamName", value: "favoriteTeamName") DispatchQueue.main.async { if #available(iOS 10.0, *) { // Set the delegate, if needed. Then, ask if we're authorized - the delegate must be set here if used UNUserNotificationCenter.current().delegate = self UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {(_ granted: Bool, _ error: Error?) -> Void in if error == nil { if granted == true { // we are authorized to use notifications, request a device token for remote notifications DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } // Support notification categories let exampleAction = UNNotificationAction(identifier: "App", title: "Example", options: []) let appCategory = UNNotificationCategory(identifier: "Example", actions: [exampleAction], intentIdentifiers: [] as? [String] ?? [String](), options: []) let categories = Set([appCategory]) UNUserNotificationCenter.current().setNotificationCategories(categories as? Set ?? Set()) } } }) } else { let type: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound] let setting = UIUserNotificationSettings(types: type, categories: nil) UIApplication.shared.registerUserNotificationSettings(setting) UIApplication.shared.registerForRemoteNotifications() } } } else { // MarketingCloudSDK sfmc_configure failed if #available(iOS 10.0, *) { os_log("MarketingCloudSDK sfmc_configure failed with error = %@", error!) } else { // Fallback on earlier versions NSLog("MarketingCloudSDK sfmc_configure failed with error = %@", error!) } } return success } ``` ::::: :::::: Next, configure your app to respond when a user taps an action button. Implement the `userNotificationCenter(_:didReceive:withCompletionHandler:)` method to detect which action the user selected and respond accordingly. Check the `actionIdentifier` to determine which button the user tapped, then execute code that corresponds to that action. ::::::tabset{tabs='["SDK v10+", "SDK v8.1", "SDK v8", "SDK v7"]'} :::::tab ```swift // The method is called on the delegate when the user responds to the // notification by opening the app, dismissing the notification, or choosing a // UNNotificationAction. Set the delegate before the app returns from // applicationDidFinishLaunching:. func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void ) { // Tell the SDK about the notification PushFeature.requestSdk { pushFeature in pushFeature?.setNotificationResponse(response) } // Check your notification custom actions if (response.actionIdentifier == "App") { // Handle your notification’s custom action here } } ``` ::::: :::::tab ```swift // The method is called on the delegate when the user responds to the // notification by opening the app, dismissing the notification, or choosing a // UNNotificationAction. Set the delegate before the app returns from // applicationDidFinishLaunching:. func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void ) { // tell the SDK about the notification SFMCSdk.requestPushSdk { mp in mp.setNotificationRequest(response.notification.request) } // Check your notification custom actions if (response.actionIdentifier == "App") { // Handle your notification’s custom action here } } ``` ::::: :::::tab ```swift // The method is called on the delegate when the user responds to the // notification by opening the app, dismissing the notification, or choosing a // UNNotificationAction. Set the delegate before the app returns from // applicationDidFinishLaunching:. func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void ) { // tell the SDK about the notification // See Step 5: Capture Notifications on Launch only for 8.0.x under Migrate to // Mobile Push SDK Version 8.x for iOS to capture the notification request. SFMCSdk.mp.setNotificationRequest(response.notification.request) // Check your notification custom actions if (response.actionIdentifier == "App") { // Handle your notification’s custom action here } } ``` ::::: :::::tab ```swift // The method is called on the delegate when the user responds to the // notification by opening the app, dismissing the notification, or choosing a // UNNotificationAction. Set the delegate before the app returns from // applicationDidFinishLaunching:. func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void ) { // tell the MarketingCloudSDK about the notification MarketingCloudSDK.sharedInstance().sfmc_setNotificationRequest( response.notification.request ) // Check your notification custom actions if (response.actionIdentifier == "App") { // Handle your notification’s custom action here } } ``` ::::: :::::: # Display Interactive Notifications Use interactive notifications to add buttons to push notifications from your mobile app. This code example shows how to configure the SDK to display interactive notifications. ```swift func configureSdk() -> Bool { // Enable logging for debugging early on. Debug level is not recommended for // production apps because a large amount of data is logged to the console. #if DEBUG SFMCSdk.setLogger(logLevel: .debug) #endif // Use the `PushFeatureConfigBuilder` to configure the Push Feature SDK. This // gives you the maximum flexibility in SDK configuration. The builder lets you //configure the module parameters at runtime. let pushFeatureConfiguration = PushFeatureConfigBuilder() .setApplicationControlsBadging(true) .build() // Set the completion handler to take action when all modules initialization // is completed. Setting the completion handler is optional. let completionHandler: ((_ status: [ModuleInitStatus]) -> Void) = { [weak self] status in DispatchQueue.main.async { self?.handleSDKInitializationCompletion(status: status) } } SFMCSdk.initializeSdk( ConfigBuilder().setPushFeature(config: pushFeatureConfiguration).build(), completion: completionHandler) return true } // MARK: - SDK Initialization Completion Handler private func handleSDKInitializationCompletion(status: [ModuleInitStatus]) { var allSuccessful = true for moduleStatus in status { print( "Module: \(moduleStatus.moduleName.rawValue), Status: \(moduleStatus.initStatus.rawValue)") if moduleStatus.initStatus == .success { // Handle successful initialization for each module switch moduleStatus.moduleName { case .pushFeature: setupPushFeature() default: break } } else if moduleStatus.initStatus == .error { allSuccessful = false // module failed to initialize, check logs for more details } else if moduleStatus.initStatus == .cancelled { allSuccessful = false // module initialization was cancelled // (for example if re-configuration was triggered before init completed) } else if moduleStatus.initStatus == .timeout { allSuccessful = false // module failed to initialize due to timeout, check logs for more details } } if allSuccessful { print("SDK initialization completed successfully") } else { print("SDK initialization completed with errors - check logs above") } } func setupPushFeature() { // Set the URLHandlingDelegate to handle URLs from CloudPage, OpenDirect, // Location, and Inbox messages. In this example, the AppDelegate class adheres // to the URLHandlingDelegate protocol (see below). PushFeature.requestSdk { pushFeature in DispatchQueue.main.async { pushFeature?.setURLHandlingDelegate(self) } } // Make sure to dispatch this to the main thread, as UNUserNotificationCenter // will present UI. DispatchQueue.main.async { // Set the UNUserNotificationCenterDelegate to a class adhering to this protocol. // In this example, the AppDelegate class adheres to the protocol (see below) // and handles Notification Center delegate methods from iOS. UNUserNotificationCenter.current().delegate = self // Request authorization from the user for push notification alerts. UNUserNotificationCenter.current().requestAuthorization( options: [.alert, .sound, .badge], completionHandler: { (_ granted: Bool, _ error: Error?) -> Void in if error == nil { if granted == true { DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } // Support notification categories let exampleAction = UNNotificationAction( identifier: "App", title: "Example", options: []) let appCategory = UNNotificationCategory( identifier: "Example", actions: [exampleAction], intentIdentifiers: [] as? [String] ?? [String](), options: []) let categories = Set([appCategory]) UNUserNotificationCenter.current().setNotificationCategories( categories as? Set ?? Set()) } } } ) } } func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { self.configureSFMCSdk() return true } ``` ## Handle Actions In your push handler, examine the push notification’s payload to see if your action is triggered and if your application performed the action, as shown in this code example. ```swift // The method is called on the delegate when the user responds to the notification // by opening the application, dismissing the notification, or choosing a // UNNotificationAction. The delegate must be set before the application returns //from applicationDidFinishLaunching:. func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void ) { // tell the SDK about the notification PushFeature.requestSdk { pushFeature in pushFeature?.setNotificationResponse(response) } // Check your notification custom actions if response.actionIdentifier == "App" { // Handle your notification’s custom action here } } ``` # Enable and Use Analytics on Android Enable analytics in your mobile app using [`MarketingCloudConfig.Builder()`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud/-marketing-cloud-config/-builder/index.html) to set the necessary parameters for tracking push notifications, inbox messages, and Einstein Recommendations events. - To implement analytics in your mobile app, set the [`analyticsEnabled`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud/-marketing-cloud-config/-builder/set-analytics-enabled.html) parameter to `true`. - To implement web and mobile analytics in your mobile app via Einstein Recommendations, set the [`piAnalyticsEnabled`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud/-marketing-cloud-config/-builder/set-pi-analytics-enabled.html) parameter to `true`. Configure the SDK with analytics enabled during initialization. ::::::tabset{tabs='["SDK v10+", "SDK v8 or 9", "SDK v7"]'} :::::tab For SDK version 10 or higher, use this example. ```java SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { engagementModuleConfig = MarketingCloudConfig.builder().apply { // Other configuration values setAnalyticsEnabled(true) // Enable ET Analytics, default = false setPiAnalyticsEnabled(true) // Enable Predictive Intelligence Analytics, default = false /* To explicitly control PI analytic attribution set setUseLegacyPiIdentifier to false and set a value for the Predictive Intelligence Identifier in the SDK's AnalyticsManager. */ setUseLegacyPiIdentifier(false) }.build(applicationContext) }) { // Handle initialization status } ``` ::::: :::::tab For SDK version 8 or 9, use this example. ```java SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { pushModuleConfig = MarketingCloudConfig.builder().apply { // Other configuration values setAnalyticsEnabled(true) // Enable ET Analytics, default = false setPiAnalyticsEnabled(true) // Enable Predictive Intelligence Analytics, default = false /* To explicitly control PI analytic attribution set setUseLegacyPiIdentifier to false and set a value for the Predictive Intelligence Identifier in the SDK's AnalyticsManager. */ setUseLegacyPiIdentifier(false) }.build(applicationContext) }) { // Handle initialization status } ``` ::::: :::::tab For SDK version 7, use this example. ```java MarketingCloudSdk.init(applicationContext as Application, MarketingCloudConfig.builder().apply { // Other configuration values setAnalyticsEnabled(true) // Enable ET Analytics, default = false setPiAnalyticsEnabled(true) // Enable Predictive Intelligence Analytics, default = false /* To explicitly control PI analytic attribution setUseLegacyPiIdentifier to false and set a value for the Predictive Intelligence Identifier in the SDK's AnalyticsManager. */ setUseLegacyPiIdentifier(false) }.build(applicationContext)) { // Handle initialization status } ``` ::::: :::::: ## Integrate Einstein Recommendations and Collect API [Integrate Einstein Recommendations](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_analytics_android_recommendations_integrate.md) to attribute collected analytics to specific users and track cart contents, conversions, page views, and inbox message opens. Configure the PIID identifier and use the integration methods to connect your mobile app with Einstein Recommendations. # Enable and Use Analytics on Android Enable analytics in your mobile app using [`MobileAppMessagingConfig.builder()`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/mobileappmessaging/com.salesforce.marketingcloud.mobileappmessaging/-mobile-app-messaging-config/-builder/index.html) to set the necessary parameters. - To implement analytics in your mobile app, set the [`analyticsEnabled`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/mobileappmessaging/com.salesforce.marketingcloud.mobileappmessaging/-mobile-app-messaging-config/-builder/analytics-enabled.html) parameter to `true`. ```kotlin SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { mamModuleConfig = MobileAppMessagingConfig.builder().apply { analyticsEnabled(true) // Enable analytics, default = false }.build() }) { // Handle initialization status } ``` # Enable and Use Analytics on iOS Enable analytics in your configuration file using the `analytics:true` value. The SDK collects analytics in the background and when SDK methods are called to track push notifications, inbox messages, and Einstein Recommendations events. ## Track Push Notifications [Track push notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_analytics_ios_push_track.md) to ensure proper tracking by the SDK and Marketing Cloud Engagement analytics. Call the SDK in your push notification handler method to track open counts for your push messaging campaigns. ## Track Inbox Message Opens [Track inbox message opens](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_analytics_ios_opens_track.md) to send open analytic values to Engagement. Call `trackMessageOpened` with an inbox message dictionary to record analytics when users select messages. ## Integrate Einstein Recommendations and Collect API [Integrate Einstein Recommendations](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_analytics_ios_recommendations_integrate.md) to attribute collected analytics to specific users and track cart contents, conversions, and page views. Configure the PIID identifier and use the integration methods to connect your mobile app with Einstein Recommendations. # Enable and Use Analytics on iOS Enable analytics in your configuration file using the `analytics:true` value. The SDK collects analytics in the background and when your app calls SDK methods. ## Track Push Notifications To make sure that the SDK and Marketing Cloud Next track push notifications accurately, call the SDK in your push notification handler method. If you don’t, analytic events can’t track open counts for your push messaging campaigns. ```swift /** The method is called on the delegate when the user responds to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. Set the delegate before the application returns from applicationDidFinishLaunching:. **/ func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void ) { // tell the SDK about the notification PushFeature.requestSdk { pushFeature in pushFeature?.setNotificationResponse(response) } completionHandler() } ``` ## See Also - [Enable and Use Analytics on Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_analytics_android.md) - [Runtime Toggles](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_next_runtime_toggles.md) # Enable App Groups Capability To ensure that push delivery events and the carousel template work as intended, add the App Groups capability to your app. This capability is required because the main app, the service extension, and the content extension are separate processes. For security and performance reasons, iOS limits interprocess communication between the extensions and the main app. ## Configure App Groups for the Main App Target Set up your main app to use the App Groups feature. You can add the main app to a new group or an existing one. 1. Select your main app target. 2. On the **Signing & Capabilities** tab, add the **App Groups** capability. 3. Add an app group container or select an existing one. If you create a container, use a name in this format to make it easy to identify later: `group..sfmarketingcloudsdk` 4. Add the container name to a new `Info.plist` key with these details: - Key name: `SF_MARKETINGCLOUD_APP_GROUP_KEY` - Value type: String - Value: The app group container name, such as `group.com.salesforce.MyAwesomeApp.sfmarketingcloudsdk` ## Configure App Groups for the Service and Content Extensions After you add an app group to the main app target, add the service and content extension targets to the same group. 1. Select the service extension target. 2. On the **Signing & Capabilities** tab, add the **App Groups** capability. 3. Select the same app group name that you assigned in the main app target. 4. Edit the Info.plist file for the extension to include the same `SF_MARKETINGCLOUD_APP_GROUP_KEY` value that you added in the Info.plist file for the main app. 5. Repeat these steps for the content extension target. **important:** The `SF_MARKETINGCLOUD_APP_GROUP_KEY` value must be identical in the Info.plist files for the main app, the service extension, and the content extension. # Enable App Groups for the iOS Extension SDK for Marketing Cloud Next The main app, Service Extension, and Content Extension run in separate processes. iOS limits communication between extensions and the main app, so the SDK uses the App Groups capability to share data between them. ## Configure App Groups for the Main App Target 1. In your main app target, on the **Signing & Capabilities** tab, add the **App Groups** capability. 2. Add an app group container or use an existing one. If you create a container, use a name in this format: `group..sfmarketingcloudsdk` 3. Add the container name to a new `Info.plist` key with these details: - `Info.plist` key name: `SF_MARKETINGCLOUD_APP_GROUP_KEY` - `Info.plist` value type: String - `Info.plist` value: The app group container name, such as `group.com.salesforce.MyAwesomeApp.sfmarketingcloudsdk`. ## Configure App Groups for the Extension Targets Repeat the preceding steps to add app groups for your Service Extension and Content Extension targets. Use the same container name and `SF_MARKETINGCLOUD_APP_GROUP_KEY` value in each extension’s Info.plist. **important:** In the Info.plist file, the value of `SF_MARKETINGCLOUD_APP_GROUP_KEY` must be identical for the main app, the service extension, and the content extension. ## See Also - [Integrate the iOS Extension SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_integrate_ios_extension.md) # Enable Background Location Updates Normally, the app downloads new regions and messages as the device moves more than 5 kilometers from the last location and download of this data. However, if your app serves users who spend much time within a single 5-kilometer radius, consider adding the ability to do a background refresh of regions and messages. Apple controls when this background refresh takes place. However, Apple also allows the SDK to download new regions and messages for those times your user spends a considerable amount of time in a single 5-kilometer region. In your `Info.plist`, implement this key to enable this function. To refresh geofences and beacons, the SDK requires the app to implement the **App downloads content from the network** mode. This mode gives the app permission to periodically download new regions and messages. In your `Info.plist`, add keys under `UIBackgroundModes`: ```xml fetch location remote-notification ``` In your application delegate method `-application:didFinishLaunchingWithOptions:`, implement this code: ```swift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { ... if UIApplication.shared.backgroundRefreshStatus == .available { // setting this will enable iOS to call the app delegate method performFetchWithCompletionHandler periodically. The implementation of that method (see below) // will call the MarketingCloudSDK at most once per day to update location and proximity messages in the background - if those services have been enabled. // Only call this method if you have enabled location in your MarketingCloudConfiguration.json file // Note that you will require "App downloads content from the network" in your plist for this background app refresh to work UIApplication.shared.setMinimumBackgroundFetchInterval(UIApplication.backgroundFetchIntervalMinimum) } } ``` Finally, implement the handler for this functionality in your application delegate class. ::::::tabset{tabs='["SDK v10+", "SDK v8", "SDK v7"]'} :::::tab For SDK v10 and later, use this code. ```swift MarketingCloudSdk.requestSdk { mc in let location = mc?.lastKnownLocation() } ``` ::::: :::::tab For SDK v8, use this code. ```swift SFMCSdk.requestPushSdk { mp in let location = mp.lastKnownLocation() } ``` ::::: :::::tab For SDK v7, use this code. ```swift // iOS calls this method to tell the MarketingCloudSDK to update location and // proximity messages. This method is only called if // [UIApplication sharedApplication] setMinimumBackgroundFetchInterval: is set // to a value other than UIApplicationBackgroundFetchIntervalNever and // Background App Refresh is enabled. func application( _ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void ) { MarketingCloudSDK.sharedInstance().sfmc_refresh( fetchCompletionHandler: completionHandler ) } ``` ::::: :::::: See `MarketingCloudSDK+Base.h` for more information about this method. # Enable Beacon Debug Logging Proximity logging is disabled by default. You can enable it using [AltBeacon's](https://github.com/AltBeacon/android-beacon-library) `LogManager` class to troubleshoot beacon-related issues. The following example shows how to enable debug logging for beacons using [`LogManager`](https://altbeacon.github.io/android-beacon-library/javadoc/org/altbeacon/beacon/logging/LogManager.html). The AltBeacon logger implementation in this example routes its logs through the Engagement [`MCLogListener`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud/-m-c-log-listener/index.html) interface. ```javascript // Enable verbose logging from AltBeacon // This is very noisy and should only be done when an issue occurs. LogManager.setVerboseLoggingEnabled(true); // Pipe AltBeacon's logs through the MarketingCloud MCLogListener interface. // This will adhere to the log level set by MarketingCloudSdk.setLogLevel() LogManager.setLogger(BeaconLogger()) // You can also implement your own AltBeacon Logger LogManager.setLogger(object:Logger {}) ``` # Enable Beacon Support Beacon support is enabled when you implement the location requirements for iOS location messaging. To range for beacons in the background, add an entry to your app's `Info.plist`. This permission ensures that your app can range for beacons when your app is in the background or suspended. **important:** The SDK suppresses beacon messages with no content. If you include AMPscript or a merge field in your message that returns an empty string, your app doesn't display that message to the user. To understand how beacons behave in different situations, see _Salesforce Help_: [MobilePush Beacon Scenarios](https://help.salesforce.com/s/articleView?id=mktg.mc_mp_beacon_behavior.htm). If you create your own `CLLocationManager` object, we can't guarantee that features of our SDK work as intended. If you have enabled notifications using MarketingCloudSDK and have called `mp.startWatchingLocation()`, you can access the device's last known location using the SDK. ::::::tabset{tabs='["SDK v10+", "SDK v8", "SDK v7"]'} :::::tab ``` MarketingCloudSdk.requestSdk { mc in let location = mc?.lastKnownLocation() } ``` ::::: :::::tab ``` SFMCSdk.requestPushSdk { mp in let location = mp.lastKnownLocation() } ``` ::::: :::::tab ``` let location = MarketingCloudSDK.sharedInstance().sfmc_lastKnownLocation() ``` ::::: :::::: # Enable Push Notifications Use this code example to add support for push notifications to your app. Replace `YOUR_SENDER_ID` with the sender ID for your app. You can find the sender ID on the Project Settings page of the Firebase console. ```java SFMCSdk.configure(this, SFMCSdkModuleConfig.build { // other config(s) this.pushFeatureModuleConfig = PushFeatureConfig.builder().apply { setSenderId("YOUR_SENDER_ID") setNotificationCustomizationOptions( PushNotificationCustomizationOptions.create(R.drawable.ic_notification) ) }.build() // ... }){ initializationStatus -> // Handle Initialization Status } ``` # Enable Push Notifications for iOS Configure your iOS app send push notifications. 1. Enable push notifications in your target’s **Capabilities** settings. 2. Set your `AppDelegate` class to adhere to the `UIApplicationDelegate` and `UNUserNotificationCenterDelegate` protocol. ``` class AppDelegate: UIApplicationDelegate, UNUserNotificationCenterDelegate ... ``` 3. Extend the SDK configuration code to add support for push registration. ```swift // Mobile APP Messaging SDK: REQUIRED IMPLEMENTATION func configureSdk() -> Bool { // Enable logging for debugging early on. Debug level is not recommended for production apps, as significant data // about the SDK will be logged to the console. #if DEBUG SFMCSdk.setLogger(logLevel: .debug) #endif // Use the `PushFeatureConfigBuilder` to configure the Push Feature SDK. This gives you the maximum flexibility in SDK configuration. // The builder lets you configure the module parameters at runtime. let pushFeatureConfiguration = PushFeatureConfigBuilder() .setApplicationControlsBadging(true) .build() // Set the completion handler to take action when all modules initialization is completed. // Seting the completion handler is optional. let completionHandler: ((_ status: [ModuleInitStatus]) -> Void) = { [weak self] status in DispatchQueue.main.async { self?.handleSDKInitializationCompletion(status: status) } } SFMCSdk.initializeSdk(ConfigBuilder().setMAM( config: pushFeatureConfiguration).build(), completion: completionHandler ) return true } // MARK: - SDK Initialization Completion Handler private func handleSDKInitializationCompletion(status: [ModuleInitStatus]) { var allSuccessful = true for moduleStatus in status { print("Module: \(moduleStatus.moduleName.rawValue), Status: \(moduleStatus.initStatus.rawValue)") if moduleStatus.initStatus == .success { // Handle successful initialization for each module switch moduleStatus.moduleName { case .pushFeature: setupPushFeature() default: break } } else if moduleStatus.initStatus == .error { allSuccessful = false // module failed to initialize, check logs for more details } else if moduleStatus.initStatus == .cancelled { allSuccessful = false // module initialization was cancelled (for example if the // re-configuration was triggered before initialization completed) } else if moduleStatus.initStatus == .timeout { allSuccessful = false // module failed to initialize due to timeout, check logs for more details } } if allSuccessful { print("SDK initialization completed successfully") } else { print("SDK initialization completed with errors - check logs above") } } func setupPushFeature() { // Set the URLHandlingDelegate to handle URLs from CloudPage, OpenDirect, //Location, and Inbox messages. In this example, the AppDelegate class adheres // to the URLHandlingDelegate protocol (see below). PushFeature.requestSdk { pushFeature in DispatchQueue.main.async { pushFeature?.setURLHandlingDelegate(self) } } } func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { self.configureSdk() return true } ``` 4. Add the required `UIApplicationDelegate` protocol methods to support push registration to your `AppDelegate` class. ```swift // PushFeature SDK: REQUIRED IMPLEMENTATION func application( _ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data ) { // Save the device token PushFeature.requestSdk { pushFeature in pushFeature?.setDeviceToken(deviceToken) } } // Mobile App Messaging SDK: REQUIRED IMPLEMENTATION func application( _ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error ) { // Log the error print(error) } // PushFeature SDK: REQUIRED IMPLEMENTATION /** This delegate method lets apps with the "remote-notification" background mode fetch data in response to an incoming remote notification. Call the fetchCompletionHandler as soon as you're finished performing that operation so the system can accurately estimate its power and data cost. This method is invoked even if the application was launched or resumed because of the remote notification. The delegate methods are invoked first. This behavior is in contrast to `application(_:didReceiveRemoteNotification:)`, which isn't called in those cases, and isn't invoked if this method is implemented. **/ func application( _ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping ( UIBackgroundFetchResult ) -> Void ) { PushFeature.requestSdk { pushFeature in pushFeature?.setNotificationUserInfo(userInfo) } completionHandler(.newData) } ``` 5. Add the required `UNUserNotificationCenterDelegate` protocol methods to support push notifications to your `AppDelegate` class. ```swift /** The method is called on the delegate when the user responds to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from applicationDidFinishLaunching:. **/ func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void ) { // Required: Tell theSDK about the notification so that it begins to // collect analytics and process the notification for your app. PushFeature.requestSdk { pushFeature in pushFeature?.setNotificationResponse(response) } completionHandler() } /** The method is called on the delegate only if the application is in the foreground. If the method isn't implemented or the handler isn't called in a timely manner, then the notification isn't shown. The application can have the notification presented as a sound, badge, alert, or it can appear in the notification list. This decision should be based on whether the information in the notification is otherwise visible to the user. **/ func userNotificationCenter( _ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping ( UNNotificationPresentationOptions ) -> Void ) { completionHandler(.alert) } ``` # Enable Push Notifications on iOS After you integrate and [configure the SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_integrate_ios/mc_engagement_integrate_ios_configure.md), enable push notifications in your iOS app. This process involves enabling push capabilities in Xcode, implementing the required delegate protocols, and registering for remote notifications. 1. In Xcode, on the Signing & Capabilities tab for your app, enable push notifications. 2. Set your `AppDelegate` class to adhere to the `UIApplicationDelegate` and `UNUserNotificationCenterDelegate` protocol. ```swift class AppDelegate: UIApplicationDelegate, UNUserNotificationCenterDelegate ... ``` 3. Extend the SDK configuration code to add support for push registration.
Code example for version 10 and later If your app uses version 10 or later of the SDK, use this code. ```swift // REQUIRED IMPLEMENTATION func configureSdk() -> Bool { // Enable logging for debugging early on. Debug level is not recommended for production apps, as significant data // about the SDK will be logged to the console. #if DEBUG SFMCSdk.setLogger(logLevel: .debug) #endif // Use the `PushFeatureConfigBuilder` to configure the Push Feature SDK. This gives you the maximum flexibility in SDK configuration. // The builder lets you configure the module parameters at runtime. let pushFeatureConfiguration = PushFeatureConfigBuilder() .setApplicationControlsBadging(true) .build() // Set the completion handler to take action when all modules initialization is completed. // Setting the completion handler is optional. let completionHandler: ((_ status: [ModuleInitStatus]) -> Void) = { [weak self] status in DispatchQueue.main.async { self?.handleSDKInitializationCompletion(status: status) } } SFMCSdk.initializeSdk(ConfigBuilder().setMAM( config: pushFeatureConfiguration).build(), completion: completionHandler ) return true } // MARK: - SDK Initialization Completion Handler private func handleSDKInitializationCompletion(status: [ModuleInitStatus]) { var allSuccessful = true for moduleStatus in status { print("Module: \(moduleStatus.moduleName.rawValue), Status: \(moduleStatus.initStatus.rawValue)") if moduleStatus.initStatus == .success { // Handle successful initialization for each module switch moduleStatus.moduleName { case .pushFeature: setupPushFeature() default: break } } else if moduleStatus.initStatus == .error { allSuccessful = false // module failed to initialize, check logs for more details } else if moduleStatus.initStatus == .cancelled { allSuccessful = false // module initialization was cancelled (for example if the // re-configuration was triggered before initialization completed) } else if moduleStatus.initStatus == .timeout { allSuccessful = false // module failed to initialize due to timeout, check logs for more details } } if allSuccessful { print("SDK initialization completed successfully") } else { print("SDK initialization completed with errors - check logs above") } } func setupPushFeature() { // Set the URLHandlingDelegate to handle URLs from CloudPage, OpenDirect, //Location, and Inbox messages. In this example, the AppDelegate class adheres // to the URLHandlingDelegate protocol (see below). PushFeature.requestSdk { pushFeature in DispatchQueue.main.async { pushFeature?.setURLHandlingDelegate(self) } } } func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? ) -> Bool { self.configureSdk() return true } ```
Code example for version 8 and 9 If your app uses version 8 or 9 of the SDK, use this code. ```swift // SDK: REQUIRED IMPLEMENTATION func configureSDK() { #if DEBUG SFMCSdk.setLogger(logLevel: .debug) #endif let mobilePushConfiguration = PushConfigBuilder(appId: appId) .setAccessToken(accessToken) .setMarketingCloudServerUrl(appEndpoint) .setMid(mid) .setInboxEnabled(inbox) .setLocationEnabled(location) .setAnalyticsEnabled(analytics) .build() let completionHandler: (OperationResult) -> () = { result in if result == .success { self.setupMobilePush() } } SFMCSdk.initializeSdk(ConfigBuilder().setPush(config: mobilePushConfiguration, onCompletion: completionHandler).build()) } func setupMobilePush() { // Set the MarketingCloudSDKURLHandlingDelegate to a class adhering to the protocol. // In this example, the AppDelegate class adheres to the protocol (see below) // and handles URLs passed back from the SDK. SFMCSdk.requestPushSdk { mp in mp.setURLHandlingDelegate(self) } // Make sure to dispatch this to the main thread, as UNUserNotificationCenter will present UI. DispatchQueue.main.async { // Set the UNUserNotificationCenterDelegate to a class adhering to the protocol. // In this example, the AppDelegate class adheres to the protocol (see below) // and handles Notification Center delegate methods from iOS. UNUserNotificationCenter.current().delegate = self // Request authorization from the user for push notification alerts. UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {(_ granted: Bool, _ error: Error?) -> Void in if error == nil { if granted == true { // Your application may want to do something specific if the user has granted authorization // for the notification types specified; it would be done here. } } }) // In any case, your application should register for remote notifications *each time* // your application launches to ensure that the push token used by MobilePush (for silent push) // is updated if necessary. // Registering in this manner does *not* mean that a user will see a notification - it only means // that the application will receive a unique push token from iOS. UIApplication.shared.registerForRemoteNotifications() } } ```
Code example for version 7 This code example shows how to configure the version 7 of the SDK for iOS apps. ```swift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // ... SDK configuration setup var success = false do { try MarketingCloudSDK.sharedInstance().sfmc_configure(with:builder) success = true } catch let error as NSError { // Errors returned from configuration will be in the NSError parameter and can be used to determine // if you've implemented the SDK correctly. let configErrorString = String(format: "MarketingCloudSDK sfmc_configure failed with error = %@", error) print(configErrorString) } if success == true { // The SDK has been fully configured and is ready for use! // Enable logging for debugging. Not recommended for production apps, as significant data // about MobilePush will be logged to the console. #if DEBUG MarketingCloudSDK.sharedInstance().sfmc_setDebugLoggingEnabled(true) #endif // Set the MarketingCloudSDKURLHandlingDelegate to a class adhering to the protocol. // In this example, the AppDelegate class adheres to the protocol // and handles URLs passed back from the SDK. MarketingCloudSDK.sharedInstance().sfmc_setURLHandlingDelegate(self) // Make sure to dispatch this to the main thread, as UNUserNotificationCenter will present UI. DispatchQueue.main.async { if #available(iOS 10.0, *) { // Set the UNUserNotificationCenterDelegate to a class adhering to thie protocol. // In this exmple, the AppDelegate class adheres to the protocol (see below) // and handles Notification Center delegate methods from iOS. UNUserNotificationCenter.current().delegate = self // Request authorization from the user for push notification alerts. UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {(_ granted: Bool, _ error: Error?) -> Void in if error == nil { if granted == true { // Your application may want to do something specific // if the user has granted authorization for the // notification types specified; it would be done here. print(MarketingCloudSDK.sharedInstance().sfmc_deviceToken() ?? "error: no token - was UIApplication.shared.registerForRemoteNotifications() called?") } } }) } // In any case, your application should register for remote notifications *each time* // your application launches to ensure that the push token used by MobilePush (for silent push) is updated if necessary. // Registering in this manner does *not* mean that a user will see a notification, // it only means that the application will receive a unique push token from iOS. UIApplication.shared.registerForRemoteNotifications() } } return true } ```
4. Add the required `UIApplicationDelegate` protocol methods to support push registration to your `AppDelegate` class.
Code example for version 10 and later If your app uses version 10 or later of the SDK, use this code. ```swift // PushFeature SDK: REQUIRED IMPLEMENTATION func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { PushFeature.requestSdk { pushFeature in pushFeature?.setDeviceToken(deviceToken) } } // PushFeature SDK: REQUIRED IMPLEMENTATION func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print(error) } // PushFeature SDK: REQUIRED IMPLEMENTATION /** This delegate method lets apps with the "remote-notification" background mode fetch data in response to an incoming remote notification. Call the fetchCompletionHandler as soon as you're finished performing that operation so the system can accurately estimate its power and data cost. This method is invoked even if the application was launched or resumed because of the remote notification. The delegate methods are invoked first. This behavior is in contrast to `application(_:didReceiveRemoteNotification:)`, which isn't called in those cases, and isn't invoked if this method is implemented. **/ func application( _ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { PushFeature.requestSdk { pushFeature in pushFeature?.setNotificationUserInfo(userInfo) } completionHandler(.newData) } ```
Code example for version 8 and 9 If your app uses version 8 or 9 of the SDK, use this code. ```swift // REQUIRED IMPLEMENTATION func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { SFMCSdk.requestPushSdk { mp in mp.setDeviceToken(deviceToken) } } // REQUIRED IMPLEMENTATION func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print(error) } // REQUIRED IMPLEMENTATION /** This delegate method offers an opportunity for applications with the "remote-notification" background mode to fetch appropriate new data in response to an incoming remote notification. //You should call the fetchCompletionHandler as soon as you’re finished performing that operation, // so the system can accurately estimate its power and data cost. // This method will be invoked even if the application was launched or resumed because of the remote notification. // The respective delegate methods will be invoked first. // Note that this behavior is in contrast to application:didReceiveRemoteNotification:, which is not called in those cases, and which will not be invoked if this method is implemented. **/ func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { SFMCSdk.requestPushSdk { mp in mp.setNotificationUserInfo(userInfo) } completionHandler(.newData) } ```
Code example for version 7 If your app uses version 7 of the SDK, use this code. ```swift // REQUIRED IMPLEMENTATION func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { MarketingCloudSDK.sharedInstance().sfmc_setDeviceToken(deviceToken) } // REQUIRED IMPLEMENTATION func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print(error) } // REQUIRED IMPLEMENTATION /** This delegate method offers an opportunity for applications with the "remote-notification" background mode to fetch appropriate new data in response to an incoming remote notification. //You should call the fetchCompletionHandler as soon as you’re finished performing that operation, so the system can accurately estimate its power and data cost. // This method will be invoked even if the application was launched or resumed because of the remote notification. // The respective delegate methods will be invoked first. Note that this behavior is in contrast to application:didReceiveRemoteNotification:, which is not called in those cases, and which will not be invoked if this method is implemented. **/ func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { MarketingCloudSDK.sharedInstance().sfmc_setNotificationUserInfo(userInfo) completionHandler(.newData) } ```
5. Add the required `UNUserNotificationCenterDelegate` protocol methods to support push notifications to your `AppDelegate` class.
Code example for version 10 and later If your app uses version 10 or later of the SDK, use this code. ```swift /// The method is called on the delegate when the user responds to the notification /// by opening the application, dismissing the notification or choosing a /// UNNotificationAction. The delegate must be set before the application returns /// from applicationDidFinishLaunching:. /// * func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void ) { // Required: Tell the SDK about the notification so that it begins to // collect analytics and process the notification for your app. PushFeature.requestSdk { pushFeature in pushFeature?.setNotificationResponse(response) } completionHandler() } /// The method is called on the delegate only if the application is in the /// foreground. If the method isn't implemented or the handler isn't called in a /// timely manner, then the notification isn't shown. The application can /// have the notification presented as a sound, badge, alert, or it can appear /// in the notification list. This decision should be based on whether the /// information in the notification is otherwise visible to the user. /// * func userNotificationCenter( _ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping ( UNNotificationPresentationOptions ) -> Void ) { completionHandler(.alert) } ```
Code example for version 9 If your app uses version 9 of the SDK, use this code. ```swift // REQUIRED IMPLEMENTATION // The method will be called on the delegate when the user responded to the notification by opening the application, // dismissing the notification or choosing a UNNotificationAction. // The delegate must be set before the application returns from applicationDidFinishLaunching:. @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // Required: tell the MarketingCloudSDK about the notification. This will collect MobilePush analytics // and process the notification on behalf of your application. SFMCSdk.requestPushSdk { mp in mp.setNotificationResponse(response) } completionHandler() } // REQUIRED IMPLEMENTATION // The method will be called on the delegate only if the application is in the foreground. // If the method is not implemented or the handler is not called in a timely manner then the notification will not be presented. // The application can choose to have the notification presented as a sound, badge, alert and/or in the notification list. // This decision should be based on whether the information in the notification is otherwise visible to the user. @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler(.alert) } ```
Code example for version 8 If your app uses version 8 of the SDK, use this code. ```swift // REQUIRED IMPLEMENTATION // The method will be called on the delegate when the user responded to the notification by opening the application, // dismissing the notification or choosing a UNNotificationAction. // The delegate must be set before the application returns from applicationDidFinishLaunching:. @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // Required: tell the MarketingCloudSDK about the notification. This will collect MobilePush analytics // and process the notification on behalf of your application. SFMCSdk.requestPushSdk { mp in mp.setNotificationRequest(response.notification.request) } completionHandler() } // REQUIRED IMPLEMENTATION // The method will be called on the delegate only if the application is in the foreground. // If the method is not implemented or the handler is not called in a timely manner then the notification will not be presented. // The application can choose to have the notification presented as a sound, badge, alert and/or in the notification list. // This decision should be based on whether the information in the notification is otherwise visible to the user. @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler(.alert) } ```
Code example for version 7 If your app uses version 7 of the SDK, use this code. ```swift // REQUIRED IMPLEMENTATION // The method will be called on the delegate when the user responded to the notification by opening the application, // dismissing the notification or choosing a UNNotificationAction. // The delegate must be set before the application returns from applicationDidFinishLaunching:. @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // Required: Tell MarketingCloudSDK about the notification. // This will collect MobilePush analytics and process the notification on behalf of your application. MarketingCloudSDK.sharedInstance().sfmc_setNotificationRequest(response.notification.request) completionHandler() } // REQUIRED IMPLEMENTATION // The method will be called on the delegate only if the application is in the foreground. // If the method is not implemented or the handler is not called in a timely manner then the notification will not be presented. // The application can choose to have the notification presented as a sound, badge, alert and/or in the notification list. // This decision should be based on whether the information in the notification is otherwise visible to the user. @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler(.alert) } ```
**note:** The delegate methods in this procedure use Marketing Cloud SDK APIs to manage push notifications, contact registration, and analytics tracking. If you implement the delegate methods without calling the corresponding SDK methods, these features don’t work. # enableLogging Enables verbose logging within the native MobilePush SDK. ## Syntax `MCCordovaPlugin.enableLogging([successCallback], [errorCallback])` ## Kind Static method of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | ----------------- | ---------- | ----------- | | `successCallback` | `function` | | | `errorCallback` | `function` | | ## See Also - [Troubleshoot Issues in Android Apps](/docs/marketing/mobilepush/guide/troubleshooting-android.html#check-the-sdks-log-output) - _SDK Reference for iOS_: [Logger Methods](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/ios-sdk-v11/sfmc-sdk/classes/sfmcsdk.md#logger-methods) # enableLogging Enables SDK logging for debugging purposes. ## Syntax ```dart Future enableLogging() ``` ## Returns - `Future` - Completes when logging has been enabled. ## Example ```dart try { await SfmcSdk.enableLogging(); print('SDK logging enabled'); } catch (e) { print('Failed to enable logging: $e'); } ``` ## Related Methods - [disableLogging()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_disableLogging.md) - [logSdkState()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_logSdkState.md) # enableLogging Enables verbose logging within the native MobilePush SDK and Unified SFMC SDK. ## Syntax ```javascript MCReactModule.enableLogging(); ``` ## Returns - `void` - No return value. ## Example ```javascript import { MCReactModule } from "react-native-marketingcloudsdk"; const enableSDKLogging = () => { try { MCReactModule.enableLogging(); console.log("SDK logging enabled"); } catch (error) { console.error("Error enabling logging:", error); } }; ``` ## See Also - [disableLogging() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_disableLogging.md) - [logSdkState() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_logSdkState.md) - [Troubleshoot Issues in Android Apps](/docs/marketing/mobilepush/guide/troubleshooting-android.html#check-the-sdks-log-output) - _SDK Reference for iOS_: [Logger Methods](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/ios-sdk-v11/sfmc-sdk/classes/sfmcsdk.md#logger-methods) # enablePush Enables push messaging in the native MobilePush SDK. ## Syntax `MCCordovaPlugin.enablePush([successCallback], [errorCallback])` ## Kind Static method of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | ----------------- | ---------- | ----------- | | `successCallback` | `function` | | | `errorCallback` | `function` | | # enablePush Enables push notifications for the device. ## Syntax ```dart Future enablePush() ``` ## Returns - `Future` - Completes when push notifications have been enabled. ## Example ```dart try { await SfmcSdk.enablePush(); print('Push notifications enabled successfully'); } catch (e) { print('Failed to enable push notifications: $e'); } ``` ## Related Methods - [isPushEnabled()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_isPushEnabled.md) - [disablePush()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_disablePush.md) # enablePush Enables push messaging in the MobilePush SDK. ## Syntax ```javascript MCReactModule.enablePush(); ``` ## Returns - `void` - No return value. ## Example ```javascript import { MCReactModule } from "react-native-marketingcloudsdk"; const enablePushNotifications = () => { try { MCReactModule.enablePush(); console.log("Push notifications enabled"); } catch (error) { console.error("Error enabling push:", error); } }; ``` ## See Also - [isPushEnabled() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_isPushEnabled.md) - [disablePush() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_disablePush.md) # EngagementEvent **Package:** `com.salesforce.marketingcloud.sfmcsdk.components.events` **SDK Version:** 11.0.0 (also available in 10.0.0) **Target Platform:** androidJvm ## Overview `EngagementEvent` is a sealed class representing engagement events in the Salesforce Marketing Cloud Unified SDK for Android. It extends the `Event` class and serves as a base class for specific engagement event types. ## Declaration ```kotlin sealed class EngagementEvent : Event ``` ## Inheritance Hierarchy ``` Event └── EngagementEvent ├── CartEvent ├── CatalogEvent └── OrderEvent ``` ## Description This is a base class for engagement-related events in the SDK. As a sealed class, it can only be extended within the same module, and all direct subclasses are known at compile time. This provides type safety and exhaustive when expressions when handling different engagement event types. ## Inheritors ### CartEvent A sealed class representing cart-related events. - **Subclasses:** `AddToCartEvent`, `RemoveFromCartEvent`, `ReplaceCartEvent` - **Property:** `lineItems: List` - A list of line items associated with the cart event ### CatalogEvent A sealed class representing catalog-related events. - **Subclasses:** `ViewCatalogEvent`, `ViewCatalogDetailEvent`, `QuickViewCatalogEvent`, `ShareCatalogEvent`, `ReviewCatalogEvent`, `CommentCatalogEvent`, `FavoriteCatalogEvent` - **Property:** `catalogObject: CatalogObject` - The catalog object associated with this event ### OrderEvent A sealed class representing order-related events. - **Subclasses:** `PurchaseOrderEvent`, `PreorderEvent`, `CancelOrderEvent`, `ShipOrderEvent`, `DeliverOrderEvent`, `ReturnOrderEvent`, `ExchangeOrderEvent` - **Property:** `order: Order` - The order associated with this event ## Properties ### category ```kotlin open override var category: Event.Category ``` The Event category name. Category contains a list of allowed values from the `Event.Category` enum. **Related:** See [Event.Category Enum](#eventcategory-enum) for available values. ### priority ```kotlin open override val priority: Priority ``` The priority level for this event. ## Functions ### attributes ```kotlin open override fun attributes(): Map ``` **Returns:** A map containing the Event attributes for this event. **Description:** This method returns a key-value map of all attributes associated with the event. These attributes are used when the event is tracked and sent to the Marketing Cloud. ### name ```kotlin open override fun name(): String ``` **Returns:** The name for the event. This value must match the Event Name used when creating the event in the Marketing Cloud UI for any action to result from tracking this event. **Description:** The event name is a critical identifier that links the SDK event to the corresponding event configuration in Marketing Cloud. ## Inherited Functions The following methods are inherited from the `Event` class: ### toJson ```kotlin fun toJson(): JSONObject ``` Converts the event to a JSON object representation. ### track ```kotlin fun track() ``` Tracks this Event via `EventManager` to subscriber `EventSubscriber`. **Usage Example:** ```kotlin val event = /* create your engagement event */ event.track() ``` ## Related Classes ### Event Class `EngagementEvent` extends the abstract `Event` class. **Package:** `com.salesforce.marketingcloud.sfmcsdk.components.events` #### Event Properties ##### id ```kotlin @JvmField val id: String ``` The event identifier. ##### producer ```kotlin open val producer: Event.Producer ``` Returns the Event Producer Name from the allowed `Producer` enum values. #### Event Methods ##### attributes() ```kotlin abstract fun attributes(): Map ``` Returns the Event attributes for this event. ##### name() ```kotlin abstract fun name(): String ``` Returns the event name, which must match the Event Name used when creating the event in the Marketing Cloud UI. ### Event.Category Enum An enumeration defining possible category values for sending Events. **Package:** `com.salesforce.marketingcloud.sfmcsdk.components.events` **Declaration:** ```kotlin enum Category : Enum ``` #### Enum Values | Value | Description | | ------------- | -------------------------- | | `APPLICATION` | Application-related events | | `ENGAGEMENT` | User engagement events | | `IDENTITY` | Identity-related events | | `SYSTEM` | System events | | `BILLING` | Billing-related events | | `CUSTOM` | Custom event categories | #### Properties ##### entries ```kotlin val entries: EnumEntries ``` Returns a representation of an immutable list of all enum entries, in the order they're declared. #### Methods ##### valueOf ```kotlin fun valueOf(value: String): Event.Category ``` Returns the enum constant of this type with the specified name. The string must match exactly an identifier used to declare an enum constant. Extraneous whitespace is not permitted. ##### values ```kotlin fun values(): Array ``` Returns an array containing the constants of this enum type, in the order they're declared. ### Event.Producer Enum An enumeration representing possible Producer values for sending Events. **Package:** `com.salesforce.marketingcloud.sfmcsdk.components.events` **Declaration:** ```kotlin enum Producer : Enum ``` ## Usage Guidelines 1. **Event Name Matching:** Ensure the event name returned by `name()` exactly matches the Event Name configured in the Marketing Cloud UI. This is critical for triggering the correct actions and automations. 2. **Event Tracking:** Use the `track()` method to send the event to Marketing Cloud. The event will be processed by the `EventManager` and delivered to registered `EventSubscriber` instances. 3. **Event Attributes:** Implement the `attributes()` method to provide all relevant data for your engagement event. This data will be available in Marketing Cloud for segmentation and personalization. 4. **Event Category:** Set the appropriate `category` value from the `Event.Category` enum to properly classify your engagement event. ## Example Usage ```kotlin // Example of creating and tracking a custom engagement event class MyCustomEngagementEvent : EngagementEvent() { override val category = Event.Category.ENGAGEMENT override val priority = Priority.HIGH override fun name(): String { return "CustomEngagementEvent" } override fun attributes(): Map { return mapOf( "userId" to "12345", "action" to "custom_interaction", "timestamp" to System.currentTimeMillis() ) } } // Track the event val event = MyCustomEngagementEvent() event.track() ``` ## See Also - [Event Class Documentation](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.events/-event/index.html) - [CartEvent Documentation](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.events/-cart-event/index.html) - [CatalogEvent Documentation](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.events/-catalog-event/index.html) - [OrderEvent Documentation](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.events/-order-event/index.html) # Enums - [LogLevel](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/loglevel.md) - [MediaProviders](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/mediaproviders.md) # Enums - [InAppMessageAlignment](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagealignment.md) - [InAppMessageAnimationType](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessageanimationtype.md) - [InAppMessageButtonActionType](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagebuttonactiontype.md) - [InAppMessageButtonConfiguration](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagebuttonconfiguration.md) - [InAppMessageCloseButtonAlignment](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessageclosebuttonalignment.md) - [InAppMessageDismissReason](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagedismissreason.md) - [InAppMessageImageContentMode](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessageimagecontentmode.md) - [InAppMessageImageSize](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessageimagesize.md) - [InAppMessageLayoutOrder](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagelayoutorder.md) - [InAppMessageSize](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagesize.md) - [InAppMessageType](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagetype.md) - [ModuleName](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/modulename.md) - [OperationResult](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/operationresult.md) - [URLType](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/urltype.md) # ErrorCode ## Overview An enumeration class representing error codes for push-related exceptions in the Salesforce Marketing Cloud Unified SDK. **Module:** Push Models Module v1.0.2 **Package:** com.salesforce.marketingcloud.pushmodels.exceptions **Parent Class:** PushException **Type:** Enum class extending `Enum` --- ## Enum Values The ErrorCode enum defines the following error types: | Enum Value | Description | | --------------------- | ---------------------------------------------------- | | `UNKNOWN_ERROR` | Represents an unspecified or unknown error condition | | `INVALID_JSON` | Indicates the JSON data is malformed or invalid | | `INVALID_COMPRESSION` | Indicates issues with data compression format | | `MISSING_FIELD` | Indicates a required field is absent from the data | | `UNSUPPORTED_TYPE` | Indicates an unsupported data type was encountered | | `BAD_MEDIA` | Indicates media content is invalid or corrupted | --- ## Properties ### entries ```kotlin val entries: EnumEntries ``` Returns an immutable list representation of all enum entries in declaration order. --- ## Functions ### valueOf ```kotlin fun valueOf(value: String): PushException.ErrorCode ``` Returns the enum constant matching the specified name. **Parameters:** - `value: String` - The name of the enum constant to retrieve **Returns:** The corresponding ErrorCode enum constant **Note:** The string must exactly match an identifier used to declare an enum constant. Extraneous whitespace is not permitted. --- ### values ```kotlin fun values(): Array ``` Returns an array containing all enum constants in declaration order. **Returns:** Array of all ErrorCode enum constants # Event **Package:** `com.salesforce.marketingcloud.sfmcsdk.components.events` **Platform:** androidJvm **SDK Version:** 11.0.0 ## Description An abstract base class representing events in the Salesforce Marketing Cloud Unified SDK. This class provides the foundation for tracking and managing events within the SDK. ## Declaration ```kotlin abstract class Event ``` ## Inheritance **Known Subclasses:** - `EngagementEvent` ## Constructors ### Event ```kotlin constructor() ``` Default constructor for creating an Event instance. ## Properties ### id ```kotlin @JvmField val id: String ``` Unique identifier for the event. ### category ```kotlin open val category: Event.Category ``` The Event category name. See `Category` enum for allowed values. ### producer ```kotlin open val producer: Event.Producer ``` The Event producer name. See `Producer` enum for allowed values. ## Methods ### name ```kotlin abstract fun name(): String ``` **Returns:** The event name as a String **Description:** The name for the event. This value must match the Event Name used when creating the event in the Marketing Cloud UI. ### attributes ```kotlin abstract fun attributes(): Map ``` **Returns:** A map of attribute key-value pairs **Description:** The Event attributes for this event. ### toJson ```kotlin fun toJson(): JSONObject ``` **Returns:** A JSONObject representation of the event **Description:** Converts the event to JSON format. ### track ```kotlin fun track() ``` **Description:** Method to track this Event via EventManager to subscriber EventSubscriber. ## Nested Types ### Category ```kotlin enum Category : Enum ``` List of possible Category values for sending Events. #### Enum Values | Constant | Description | | ------------- | --------------------------------------- | | `APPLICATION` | Category for application-related events | | `ENGAGEMENT` | Category for engagement-related events | | `IDENTITY` | Category for identity-related events | | `SYSTEM` | Category for system-related events | | `BILLING` | Category for billing-related events | | `CUSTOM` | Category for custom events | #### Properties - `entries: EnumEntries` - Returns an immutable list representation of all enum entries in declaration order #### Methods - `valueOf(value: String): Event.Category` - Returns the enum constant matching the specified name - `values(): Array` - Returns an array containing all enum constants in declaration order ### Producer ```kotlin enum Producer : Enum ``` List of possible Producer values for sending Events. #### Enum Values | Constant | Description | | --------------------- | ---------------------------- | | `CUSTOMER_APP` | Application-level producer | | `UNIFIED_SDK` | Unified SDK producer | | `MCE_MODULE` | MCE module producer | | `DC_MODULE` | DC module producer | | `MAM_MODULE` | MAM module producer | | `PUSH_FEATURE_MODULE` | Push feature module producer | | `IAM_FEATURE_MODULE` | IAM feature module producer | #### Properties - `entries: EnumEntries` - Returns an immutable list representation of all enum entries in declaration order #### Methods - `valueOf(value: String): Event.Producer` - Returns the enum constant matching the specified name - `values(): Array` - Returns an array containing all enum constants in declaration order # Event Tracking The SDK can track analytical events related to end-user interactions in your app. Use these events to orchestrate journeys or trigger in-app messages in response to user activity. Version 8 and later of the SDK support event tracking. ## Implement Event Tracking A tracked event contains the event name and optional event attributes. Your app builds an event object according to your business requirements and then sends it to the SDK. When you define these events, make sure that the events implemented in the SDK are identical to the events defined in Marketing Cloud Engagement. ## Create an Event To create an event in an Android app, use this example. ``` val event = EventManager.customEvent("EventName", mapOf("key1" to "value2", "key2" to "value2")) ``` To create an event in an iOS app, use this example. ``` let event = CustomEvent(name: "EventName", attributes: ["key1": "value1", "key2": "value2"]) ``` ## Track an Event To track an event in an Android app, use this example. ``` SFMCSdk.track(event) ``` To track an event in an iOS app, use this example. ``` SFMCSdk.track(event: event) ``` # Event Tracking Mobile App Messaging SDK has methods that you can use to track analytical events related to end-user interactions in your app. You can use these events to orchestrate journeys or trigger in-app messages in response to real-time user activity. ## Implement Event Tracking A tracked event contains the event name and optional event attributes. Your app builds an event object according to your business requirements and then sends it to the MobilePush SDK. When you define these events, make sure that the events implemented in the SDK are identical to the events defined in Marketing Cloud Engagement. ## Create the Event To create an event in an Android app, use this example. ``` val event = EventManager.customEvent("EventName", mapOf("key1" to "value2", "key2" to "value2")) ``` To create an event in an iOS app, use this example. ``` let event = CustomEvent(name: "EventName", attributes: ["key1": "value1", "key2": "value2"]) ``` ## Track the Event To track an event in an Android app, use this example. ``` SFMCSdk.track(event) ``` To track an event in an iOS app, use this example. ``` SFMCSdk.track(event: event) ``` ## Flush Events To trigger existing analytics that are queued to be sent, use the `flush` function. To flush events in an Android app, use this example. ``` SFMCSdk.flush() ``` To flush events in an iOS app, use this example. ``` SFMCSdk.flush() ``` ## Send an Event Immediately To send events immediately in an Android app, use this example. ``` SFMCSdk.sendImmediate(event) ``` To send events immediately in an iOS app, use this example. ``` SFMCSdk.sendImmediate(event: event) ``` # EventManager **Package:** `com.salesforce.marketingcloud.sfmcsdk.components.events` **Platform:** androidJvm **SDK Version:** 11.0.0 ## Description A class that facilitates event management for each module. Initialized during `SFMCSdk.configure` invocation. ## Declaration ```kotlin class EventManager ``` ## Types ### Companion ```kotlin object Companion ``` Companion object for EventManager. ## Methods ### track ```kotlin fun track(vararg events: Event) ``` Tracks events from a module through `SFMCSdkComponents.eventManager`. **Parameters:** - `events: Event` - Variable number of Event objects to track # ExchangeOrderEvent ## Package ``` com.salesforce.marketingcloud.sfmcsdk.components.events ``` ## Description An E-commerce event to manage details of exchanging an order. This class is part of the Salesforce Marketing Cloud Unified SDK and is used to track order exchange activities in your Android application. ## Platform - **Target**: androidJvm - **SDK Version**: 11.0.0 (also available in 10.0.0) - **SFMC SDK**: v3.1.0 ## Class Declaration ```kotlin class ExchangeOrderEvent : OrderEvent ``` ## Inheritance Hierarchy ``` Event (abstract) └── EngagementEvent (sealed) └── OrderEvent (sealed) └── ExchangeOrderEvent ``` ## Constructor Based on the OrderEvent pattern, the constructor accepts: ```kotlin ExchangeOrderEvent(order: Order) ``` ### Parameters - **order**: `Order` - An Order object containing the details of the order being exchanged ## Properties ### Inherited from OrderEvent #### order ```kotlin val order: Order ``` Contains order information associated with the event. ### Inherited from EngagementEvent #### category ```kotlin open override var category: Event.Category ``` The Event category Name. Category contains list of allowed values. #### priority ```kotlin open override val priority: Priority ``` Priority level for the event. ### Inherited from Event #### id ```kotlin @JvmField val id: String ``` Event identifier. #### producer ```kotlin val producer: Event.Producer ``` The Event Producer Name. Producer contains list of allowed values. ## Methods ### Inherited from EngagementEvent #### name() ```kotlin open override fun name(): String ``` Returns the name for the event. This value must match the Event Name used when creating the event in the Marketing Cloud UI for tracking functionality. **Returns**: Event name as a String #### attributes() ```kotlin open override fun attributes(): Map ``` The Event attributes for this event. **Returns**: A map of attribute names to values ### Inherited from Event #### track() ```kotlin fun track(): void ``` Method to track this Event via EventManager to subscriber EventSubscriber. #### toJson() ```kotlin fun toJson(): JSONObject ``` Converts the event to JSON format. **Returns**: JSONObject representation of the event ## Related Classes ### Order Data Class ```kotlin @JvmOverloads constructor( id: String, lineItems: List = listOf(), totalValue: Double? = null, currency: String? = null, attributes: Map = mapOf() ) ``` #### Properties - **id**: `String` (required) - A unique identifier representing the order - **lineItems**: `List` (default: empty list) - A list of Line Item Data values - **totalValue**: `Double?` (default: null) - The total value of the order - **currency**: `String?` (default: null) - The currency of the total value for the order - **attributes**: `Map` (default: empty map) - A map of user-supplied values ### LineItem Data Class ```kotlin @JvmOverloads constructor( catalogObjectType: String, catalogObjectId: String, quantity: Int, price: Double? = null, currency: String? = null, attributes: Map = mapOf() ) ``` #### Properties - **catalogObjectType**: `String` (required) - A type name representing the catalog object referenced in the line item - **catalogObjectId**: `String` (required) - A unique identifier representing the catalog object referenced in the line item - **quantity**: `Int` (required) - The number of catalog objects in this line item - **price**: `Double?` (optional) - The price of the catalog object referenced in the line item - **currency**: `String?` (optional) - The currency for the price field - **attributes**: `Map` (default: empty map) - A map of user-supplied values ## Enum Values ### Event.Category List of possible Category values for sending Events: - **APPLICATION** - **ENGAGEMENT** - **IDENTITY** - **SYSTEM** - **BILLING** - **CUSTOM** ### Event.Producer List of possible Producer values for sending Events: - **CUSTOMER_APP** - Represents events from the customer's application - **UNIFIED_SDK** - Represents events from the unified SDK - **MCE_MODULE** - Represents events from the MCE module - **DC_MODULE** - Represents events from the DC module - **MAM_MODULE** - Represents events from the MAM module - **PUSH_FEATURE_MODULE** - Represents events from the push feature module - **IAM_FEATURE_MODULE** - Represents events from the in-app messaging feature module ## Sibling Classes Other OrderEvent subclasses for tracking different order lifecycle events: - **PurchaseOrderEvent** - An E-commerce event for when a user makes a purchase - **PreorderEvent** - An E-commerce event for when a user places a preorder - **CancelOrderEvent** - An E-commerce event for when a user cancels an order - **ShipOrderEvent** - An E-commerce event to manage details of an order shipment - **DeliverOrderEvent** - An E-commerce event to manage details of an order delivery - **ReturnOrderEvent** - An E-commerce event to manage details of returning an order ## Usage Example ```kotlin // Create line items for the exchange val lineItem = LineItem( catalogObjectType = "product", catalogObjectId = "PROD-12345", quantity = 2, price = 49.99, currency = "USD", attributes = mapOf("color" to "blue", "size" to "M") ) // Create an order object val order = Order( id = "ORDER-98765", lineItems = listOf(lineItem), totalValue = 99.98, currency = "USD", attributes = mapOf("reason" to "size_exchange") ) // Create and track the exchange event val exchangeEvent = ExchangeOrderEvent(order) exchangeEvent.track() ``` ## Notes - This is a concrete implementation of the sealed class `OrderEvent` - The `@JvmOverloads` annotation on Order and LineItem constructors provides Java interoperability with multiple constructor overloads - The event name must match the Event Name configured in the Marketing Cloud UI for proper tracking - Use the `track()` method to send the event to the Marketing Cloud SDK for processing # Extension SDK (Rich Notifications) Notification Service and Content Extensions for rich push notifications ## API Reference ### [Classes](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/extension-sdk_classes_index.md) 2 classes ### [Enumerations](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/enums/extension-sdk_enums_index.md) 2 enumerations # FavoriteCatalogEvent ## Overview ```kotlin class FavoriteCatalogEvent : CatalogEvent ``` An event class for tracking when a user marks a catalog item as a favorite in the Salesforce Marketing Cloud SDK. ## Package `com.salesforce.marketingcloud.sfmcsdk.components.events` ## Inheritance - **Parent Class**: `CatalogEvent` ## Description This class represents "when a user marks a catalog object as a favorite" within the SFMC SDK event tracking system. It extends the base `CatalogEvent` class to provide specific functionality for favorite-related catalog interactions. ## Availability - **Platform**: androidJvm - **SDK Version**: 11.0.0 - **Previous Versions**: Also available in 10.0.0 # Flutter Plugin Use the [Flutter Plugin](https://github.com/salesforce-marketingcloud/sdk-flutter-plugin) to integrate the Salesforce Engagement SDK into your Flutter applications. **important:** If you're integrating the Flutter plugin for the first time, use the [Flutter Unified Plugin](https://developer.salesforce.com/docs/marketing/unified_modules/hybrid-frameworks/flutter/flutter-setup.md), which works with both Marketing Cloud Engagement and Marketing Cloud Next. If your `pubspec.yaml` contains the `sfmc` dependency, your app uses the Engagement-specific Flutter plugin. Use this section to update your configuration or troubleshoot issues. For the most seamless experience, [migrate to the Flutter unified plugin](https://developer.salesforce.com/docs/marketing/unified_modules/hybrid-frameworks/flutter/migrate-to-flutter-unified-plugin.md). To install the Flutter plugin, run this command to add the plugin to your application using [Pub](https://pub.dev/packages/sfmc). ```bash flutter pub add sfmc ``` # Flutter Plugin API Reference For reference information about the Flutter plugin, see the Flutter Plugin API Reference (this link opens in a new tab). # Flutter Plugin for Marketing Cloud Engagement API Reference This section provides reference information for the Flutter plugin for the MobilePush SDK. It includes information about these methods: - [addTag](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_addTag.md) - [clearAttribute](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_clearAttribute.md) - [deleteMessage](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_deleteMessage.md) - [disableLogging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_disableLogging.md) - [disablePush](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_disablePush.md) - [enableLogging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_enableLogging.md) - [enablePush](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_enablePush.md) - [getAttributes](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getAttributes.md) - [getContactKey](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getContactKey.md) - [getDeletedMessageCount](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getDeletedMessageCount.md) - [getDeletedMessages](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getDeletedMessages.md) - [getDeviceId](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getDeviceId.md) - [getMessageCount](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getMessageCount.md) - [getMessages](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getMessages.md) - [getReadMessageCount](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getReadMessageCount.md) - [getReadMessages](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getReadMessages.md) - [getSystemToken](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getSystemToken.md) - [getTags](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getTags.md) - [getUnreadMessageCount](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getUnreadMessageCount.md) - [getUnreadMessages](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getUnreadMessages.md) - [isAnalyticsEnabled](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_isAnalyticsEnabled.md) - [isPiAnalyticsEnabled](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_isPiAnalyticsEnabled.md) - [isPushEnabled](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_isPushEnabled.md) - [logSdkState](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_logSdkState.md) - [markAllMessagesDeleted](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_markAllMessagesDeleted.md) - [markAllMessagesRead](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_markAllMessagesRead.md) - [refreshInbox](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_refreshInbox.md) - [registerInboxResponseListener](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_registerInboxResponseListener.md) - [removeTag](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_removeTag.md) - [setAnalyticsEnabled](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_setAnalyticsEnabled.md) - [setAttribute](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_setAttribute.md) - [setContactKey](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_setContactKey.md) - [setMessageRead](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_setMessageRead.md) - [setPiAnalyticsEnabled](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_setPiAnalyticsEnabled.md) - [trackEvent](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_trackEvent.md) - [unregisterInboxResponseListener](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_unregisterInboxResponseListener.md) # Flutter Unified Plugin API Reference For information about APIs in the Unified Flutter plugin, see the [Flutter Unified Plugin API Reference](/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/hybrid-flutter-plugin-api-reference.html). # Flutter Unified Plugin API Reference This section contains the API reference information for Flutter unified plugin packages in Marketing Cloud Unified Mobile SDK. - [SFMC Core](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter-sfmc-core.md) - [Marketing Cloud Engagement SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter-marketing-cloud-engagement-sdk.md) - [Marketing Cloud Mobile App Messaging SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter-marketing-cloud-mobile-app-messaging-sdk.md) - [Push Messaging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter-push-messaging.md) - [In-App Messaging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter-in-app-messaging.md) # Full Control Push Notification Customization for Android When providing a builder to the [NotificationCustomizationOptions](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.notifications/-notification-customization-options/index.html) class, you’re responsible for managing all aspects of the notification’s display properties and tap actions, including Notification Channel creation, Launch Intent action, and so on. You can access the [NotificationCompat.Builder](https://developer.android.com/reference/androidx/core/app/NotificationCompat.Builder) that would have been used by the SDK and use it as a baseline for modifications. Additionally, the SDK can create a default [NotificationChannel](https://developer.android.com/reference/android/app/NotificationChannel) for your application. ```java SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { pushFeatureModuleConfig = PushFeatureConfig.builder().apply { // Other configuration values setNotificationCustomizationOptions( NotificationCustomizationOptions.create { context, notificationMessage -> val builder = NotificationManager.getDefaultNotificationBuilder( context, notificationMessage, NotificationManager.createDefaultNotificationChannel(context), R.drawable.ic_notification_icon ) builder.setContentIntent( NotificationManager.redirectIntentForAnalytics( context, PendingIntent.getActivity( context, Random().nextInt(), Intent(context, MainActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ), notificationMessage, true ) ) } ) }.build() }) { // Handle initialization status } ``` # GeofenceMessageResponse **Package:** `com.salesforce.marketingcloud.messages.geofence` **SDK Version:** 11.0.0 ## Class Declaration ```kotlin class GeofenceMessageResponse : MessageResponse ``` ## Description A response class that extends `MessageResponse` and represents geofence-related message data from the Salesforce Marketing Cloud SDK. ## Properties ### fences ```kotlin @JvmField val fences: List ``` A list of `Region` objects representing the geofence boundaries. ### refreshCenter ```kotlin open override val refreshCenter: LatLon ``` Inherited from `MessageResponse`. Represents the central location coordinates for refreshing geofence data. ### refreshRadius ```kotlin open override val refreshRadius: Int ``` Inherited from `MessageResponse`. Defines the radius (in meters) around the refresh center within which geofences should be refreshed. ## Target Platform - **androidJvm** ## Inheritance Hierarchy ``` MessageResponse └── GeofenceMessageResponse ``` # Get Started with the Salesforce Engagement SDK Use the Salesforce Engagement SDK to deliver personalized mobile experiences to users of your mobile apps. The SDK includes methods for sending push notifications, in-app messages, inbox messages, and location-based messages. It can also track user behavior across iOS and Android platforms and send it to Marketing Cloud Engagement and Marketing Cloud Next. ## First Steps Before you integrate the Salesforce Engagement SDK into your mobile app, review its prerequisites and familiarize yourself with the fundamentals. Understanding how the SDK works helps ensure a successful implementation. - [Prerequisites](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/engagement_sdk_guides_before_you_begin_prereqs.md): Set up the push notification services and download the required authentication and configuration files. - [How the Engagement SDK Works](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/engagement_sdk_guides_before_you_begin_how_works.md): Learn how the Engagement SDK interacts with your Marketing Cloud environment to deliver push notifications, in-app messages, and inbox messages to your app users. - [Common Terminology](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/engagement_sdk_guides_before_you_begin_terminology.md): Review the terms and concepts used in the SDK. - [Developer Resources](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/engagement_sdk_guides_before_you_begin_resources.md): Learn more about Marketing Cloud and implement the Salesforce Engagement SDK. ## Understand Marketing Cloud Products This SDK contains modules that you can use to send messages via both Marketing Cloud Engagement and Marketing Cloud Next. ### Marketing Cloud Next Marketing Cloud Next is the next-gen, AI-powered marketing solution built on the Salesforce Platform. It offers a unified customer profile and real-time personalization powered by Data Cloud, and seamless integration with data from Sales Cloud and Service Cloud. With Marketing Cloud Next, you can leverage Einstein AI for predictive insights, create highly targeted campaigns using real-time data, and deliver consistent experiences across email, mobile, and other channels, all within the familiar Salesforce interface. If you use Marketing Cloud Next, use this SDK to: - [Register contacts and devices](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_next/mc_next_register_contacts_devices/mc_next_register_contacts_devices.md) - [Send in-app messages](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_next/mc_next_in-app_messages/mc_next_in-app_messages.md) - [Send push notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_next/mc_next_push_notifications/mc_next_push_notifications.md) - [Track app analytics](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_next/mc_next_analytics/mc_next_analytics.md) ### Marketing Cloud Engagement Marketing Cloud Engagement is the established marketing automation platform that enables you to create and manage customer journeys across multiple channels. Marketing Cloud Engagement was previously called Salesforce Marketing Cloud (SFMC) and ExactTarget. With the Mobile Push component of Marketing Cloud Engagement, you can reach your mobile app users with personalized push notifications, in-app messages, and location-based messaging. The platform provides robust journey building capabilities, audience segmentation, and analytics to help you engage customers at every stage of their lifecycle. If you use Marketing Cloud Engagement, use this SDK to: - [Register contacts and devices](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement/mc_engagement_register_contacts_devices/mc_engagement_register_contacts_devices.md) - [Send in-app messages](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement/mc_engagement_in-app_messages/mc_engagement_in-app_messages.md) - [Send inbox messages](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement/mc_engagement_inbox_messages/mc_engagement_inbox_messages.md) - [Send push notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement/mc_engagement_push_notifications/mc_engagement_push_notifications.md) - [Send location-based messages](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement/mc_engagement_location_messages/mc_engagement_location_messages.md) - [Track app analytics](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement/mc_engagement_analytics/mc_engagement_analytics.md) ## Next Steps To get started with the SDK, complete the [prerequisites](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/engagement_sdk_guides_before_you_begin_prereqs.md). Next, integrate the SDK with your app. The steps you take to integrate the SDK depend on which Marketing Cloud product you use. If you use Marketing Cloud Next, see [Use the SDK with Marketing Cloud Next](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_next/mc_next.md). If you use Marketing Cloud Engagement, see [Use the SDK with Marketing Cloud Engagement](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement/mc_engagement.md). # getAttributes Returns the maps of attributes set in the registration. ## Syntax `MCCordovaPlugin.getAttributes(successCallback, [errorCallback])` ## Kind Static method of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | ---------------------------- | ------------------------- | -------------------------------------------------------- | | `successCallback` | `function` | | | `successCallback.attributes` | `Object.` | The key-value map of attributes set in the registration. | | `errorCallback` | `function` | | ## See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/MarketingCloudSdk/8.0/-marketing%20-cloud%20-s-d-k/com.salesforce.marketingcloud.registration/-registration-manager/get-attributes.html) - _SDK Reference for iOS_: [attributes() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/ios-sdk-v11/mce-sdk/classes/marketingcloudsdk.md#attributes) # getAttributes Retrieves all custom attributes associated with the device. ## Syntax ```dart Future?> getAttributes() ``` ## Returns - `Future?>` - Returns a map of all custom attributes, or `null` if no attributes are set. ## Example ```dart Map? attributes = await SfmcSdk.getAttributes(); if (attributes != null) { attributes.forEach((key, value) { print('$key: $value'); }); } else { print('No attributes found'); } ``` ## Related Methods - [setAttribute()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_setAttribute.md) - [clearAttribute()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_clearAttribute.md) # getAttributes Returns the maps of attributes set in the registration. ## Syntax ```javascript MCReactModule.getAttributes() ⇒ Promise.> ``` ## Returns - `Promise.>` - A promise to the key-value map of attributes set in the registration. ## Example ```javascript import { MCReactModule } from "react-native-marketingcloudsdk"; const getDeviceAttributes = async () => { try { const attributes = await MCReactModule.getAttributes(); console.log("Device attributes:", attributes); Object.entries(attributes).forEach(([key, value]) => { console.log(`${key}: ${value}`); }); } catch (error) { console.error("Error getting attributes:", error); } }; ``` ## See Also - [setAttribute() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_setAttribute.md) - [clearAttribute() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_clearAttribute.md) - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/MarketingCloudSdk/8.0/-marketing%20-cloud%20-s-d-k/com.salesforce.marketingcloud.registration/-registration-manager/get-attributes.html) - _SDK Reference for iOS_: [attributes() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/ios-sdk-v11/mce-sdk/classes/marketingcloudsdk.md#attributes) # getContactKey Returns the contact key currently set on the device. ## Syntax `MCCordovaPlugin.getContactKey(successCallback, [errorCallback])` ## Kind Static method of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | ---------------------------- | ---------- | ------------------------ | | `successCallback` | `function` | | | `successCallback.contactKey` | `string` | The current contact key. | | `errorCallback` | `function` | | # getContactKey Retrieves the current contact key associated with the device. ## Syntax ```dart Future getContactKey() ``` ## Returns - `Future` - Returns the contact key as a string, or `null` if no contact key is set. ## Example ```dart String? contactKey = await SfmcSdk.getContactKey(); if (contactKey != null) { print('Current contact key: $contactKey'); } else { print('No contact key set'); } ``` ## Related Methods - [setContactKey()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_setContactKey.md) # getContactKey Returns the contact key currently set on the device. ## Syntax ```javascript MCReactModule.getContactKey() ⇒ Promise. ``` ## Returns - `Promise.` - A promise to the current contact key. ## Example ```javascript import { MCReactModule } from "react-native-marketingcloudsdk"; const getCurrentContactKey = async () => { try { const contactKey = await MCReactModule.getContactKey(); if (contactKey) { console.log("Current contact key:", contactKey); } else { console.log("No contact key set"); } } catch (error) { console.error("Error getting contact key:", error); } }; ``` ## See Also - [setContactKey() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_setContactKey.md) - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/MarketingCloudSdk/8.0/-marketing%20-cloud%20-s-d-k/com.salesforce.marketingcloud.registration/-registration-manager/get-contact-key.html) - _SDK Reference for iOS_: [contactKey() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/ios-sdk-v11/mce-sdk/classes/marketingcloudsdk.md#contactkey) # getDeletedMessageCount Retrieves the count of deleted inbox messages for the device. ## Syntax ```dart Future getDeletedMessageCount() ``` ## Returns - `Future` - Returns the number of deleted messages, or `null` if the count cannot be determined. ## Example ```dart int? deletedCount = await SfmcSdk.getDeletedMessageCount(); if (deletedCount != null) { print('Deleted messages: $deletedCount'); } else { print('Unable to get deleted message count'); } ``` ## Related Methods - [getMessageCount()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getMessageCount.md) - [getReadMessageCount()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getReadMessageCount.md) - [getUnreadMessageCount()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getUnreadMessageCount.md) # getDeletedMessages Retrieves all deleted inbox messages for the device. ## Syntax ```dart Future> getDeletedMessages() ``` ## Returns - `Future>` - Returns a list of deleted inbox messages. ## Example ```dart List deletedMessages = await SfmcSdk.getDeletedMessages(); print('Deleted messages: ${deletedMessages.length}'); for (InboxMessage message in deletedMessages) { print('Deleted message: ${message.subject}'); } ``` ## Related Methods - [getMessages()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getMessages.md) - [getReadMessages()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getReadMessages.md) - [getUnreadMessages()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getUnreadMessages.md) # getDeviceId Returns the `deviceId` used by the MobilePush SDK. ## Syntax `MCCordovaPlugin.getDeviceId(successCallback, [errorCallback])` ## Kind Static method of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | -------------------------- | ---------- | -------------------------------------------- | | `successCallback` | `function` | | | `successCallback.deviceId` | `string` | The `deviceId` used by Engagement messaging. | | `errorCallback` | `function` | | ## See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/MarketingCloudSdk/8.0/-marketing%20-cloud%20-s-d-k/com.salesforce.marketingcloud.registration/-registration-manager/get-device-id.html) - _SDK Reference for iOS_: [deviceIdentifier() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/ios-sdk-v11/mce-sdk/classes/marketingcloudsdk.md#deviceidentifier) # getDeviceId Retrieves the unique device identifier. ## Syntax ```dart Future getDeviceId() ``` ## Returns - `Future` - Returns the device ID as a string, or `null` if no device ID is available. ## Example ```dart String? deviceId = await SfmcSdk.getDeviceId(); if (deviceId != null) { print('Device ID: $deviceId'); } else { print('No device ID available'); } ``` ## Notes - The device ID is used internally by the SDK to identify the device. - This ID may be different from the system push token. # getDeviceId Returns the `deviceId` used by Engagement to send push messages to the device. ## Syntax ```javascript MCReactModule.getDeviceId() ⇒ Promise. ``` ## Returns - `Promise.` - A promise to the device ID. ## Example ```javascript import { MCReactModule } from "react-native-marketingcloudsdk"; const getCurrentDeviceId = async () => { try { const deviceId = await MCReactModule.getDeviceId(); if (deviceId) { console.log("Device ID:", deviceId); } else { console.log("No device ID available"); } } catch (error) { console.error("Error getting device ID:", error); } }; ``` ## See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/MarketingCloudSdk/8.0/-marketing%20-cloud%20-s-d-k/com.salesforce.marketingcloud.registration/-registration-manager/get-device-id.html) - _SDK Reference for iOS_: [MarketingCloudSDK Module](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/ios-sdk-v11/mce-sdk/classes/marketingcloudsdk.md#deviceidentifier) # getMessageCount Retrieves the total count of inbox messages for the device. ## Syntax ```dart Future getMessageCount() ``` ## Returns - `Future` - Returns the total number of messages, or `null` if the count cannot be determined. ## Example ```dart int? totalCount = await SfmcSdk.getMessageCount(); if (totalCount != null) { print('Total messages: $totalCount'); } else { print('Unable to get message count'); } ``` ## Related Methods - [getReadMessageCount()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getReadMessageCount.md) - [getUnreadMessageCount()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getUnreadMessageCount.md) - [getDeletedMessageCount()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getDeletedMessageCount.md) # getMessages Retrieves all inbox messages for the device. ## Syntax ```dart Future> getMessages() ``` ## Returns - `Future>` - Returns a list of all inbox messages. ## Example ```dart List messages = await SfmcSdk.getMessages(); print('Total messages: ${messages.length}'); for (InboxMessage message in messages) { print('Message: ${message.subject}'); } ``` ## Related Methods - [getReadMessages()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getReadMessages.md) - [getUnreadMessages()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getUnreadMessages.md) - [getDeletedMessages()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getDeletedMessages.md) # getReadMessageCount Retrieves the count of read inbox messages for the device. ## Syntax ```dart Future getReadMessageCount() ``` ## Returns - `Future` - Returns the number of read messages, or `null` if the count cannot be determined. ## Example ```dart int? readCount = await SfmcSdk.getReadMessageCount(); if (readCount != null) { print('Read messages: $readCount'); } else { print('Unable to get read message count'); } ``` ## Related Methods - [getMessageCount()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getMessageCount.md) - [getUnreadMessageCount()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getUnreadMessageCount.md) - [getDeletedMessageCount()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getDeletedMessageCount.md) # getReadMessages Retrieves all read inbox messages for the device. ## Syntax ```dart Future> getReadMessages() ``` ## Returns - `Future>` - Returns a list of read inbox messages. ## Example ```dart List readMessages = await SfmcSdk.getReadMessages(); print('Read messages: ${readMessages.length}'); for (InboxMessage message in readMessages) { print('Read message: ${message.subject}'); } ``` ## Related Methods - [getMessages()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getMessages.md) - [getUnreadMessages()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getUnreadMessages.md) - [getDeletedMessages()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getDeletedMessages.md) # getSystemToken This method returns the token used by Engagement to send push messages to the device. ## Syntax `MCCordovaPlugin.getSystemToken(successCallback, [errorCallback])` ## Kind Static method of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | ----------------------- | ---------- | ---------------------------------- | | `successCallback` | `function` | | | `successCallback.token` | `string` | The token used for push messaging. | | `errorCallback` | `function` | | ## See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/MarketingCloudSdk/8.0/-marketing%20-cloud%20-s-d-k/com.salesforce.marketingcloud.registration/-registration-manager/get-system-token.html) - _SDK Reference for iOS_: [accessToken() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/ios-sdk-v11/mce-sdk/classes/marketingcloudsdk.md#accesstoken) # getSystemToken Retrieves the system push token for the device. ## Syntax ```dart Future getSystemToken() ``` ## Returns - `Future` - Returns the system push token as a string, or `null` if no token is available. ## Example ```dart String? token = await SfmcSdk.getSystemToken(); if (token != null) { print('System token: $token'); } else { print('No system token available'); } ``` ## Notes - The system token is used by the platform to deliver push notifications to the device. - This token may change over time and should be refreshed periodically. # getSystemToken This method returns the token used by Marketing Cloud Engagement to send push messages to the device. ## Syntax ```javascript MCReactModule.getSystemToken() ⇒ Promise. ``` ## Returns - `Promise.` - A promise to the system token string. ## Example ```javascript import { MCReactModule } from "react-native-marketingcloudsdk"; const getToken = async () => { try { const token = await MCReactModule.getSystemToken(); if (token) { console.log("System token:", token); } else { console.log("No system token available"); } } catch (error) { console.error("Error getting system token:", error); } }; ``` # getTags Returns the tags currently set on the device. ## Syntax `MCCordovaPlugin.getTags(successCallback, [errorCallback])` ## Kind Static method of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | ---------------------- | ---------------- | -------------------------------------------------- | | `successCallback` | `function` | | | `successCallback.tags` | `Array.` | The array of tags currently set in the native SDK. | | `errorCallback` | `function` | | ## See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/MarketingCloudSdk/8.0/-marketing%20-cloud%20-s-d-k/com.salesforce.marketingcloud.registration/-registration-manager/get-tags.html) - _SDK Reference for iOS_: [tags() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/ios-sdk-v11/mce-sdk/classes/marketingcloudsdk.md#tags) # getTags Retrieves all tags associated with the device. ## Syntax ```dart Future> getTags() ``` ## Returns - `Future>` - Returns a list of all tags associated with the device. ## Example ```dart List tags = await SfmcSdk.getTags(); print('Current tags: ${tags.join(', ')}'); ``` ## Related Methods - [addTag()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_addTag.md) - [removeTag()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_removeTag.md) # getTags Returns the tags currently set on the device. ## Syntax ```javascript MCReactModule.getTags() ⇒ Promise.> ``` ## Returns - `Promise.>` - A promise to the array of tags currently set in the native SDK. ## Example ```javascript import { MCReactModule } from "react-native-marketingcloudsdk"; const getDeviceTags = async () => { try { const tags = await MCReactModule.getTags(); console.log("Current tags:", tags); tags.forEach((tag) => { console.log(`Tag: ${tag}`); }); } catch (error) { console.error("Error getting tags:", error); } }; ``` ## See Also - [addTag() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_addTag.md) - [removeTag() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_removeTag.md) # getUnreadMessageCount Retrieves the count of unread inbox messages for the device. ## Syntax ```dart Future getUnreadMessageCount() ``` ## Returns - `Future` - Returns the number of unread messages, or `null` if the count cannot be determined. ## Example ```dart int? unreadCount = await SfmcSdk.getUnreadMessageCount(); if (unreadCount != null) { print('Unread messages: $unreadCount'); } else { print('Unable to get unread message count'); } ``` ## Related Methods - [getMessageCount()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getMessageCount.md) - [getReadMessageCount()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getReadMessageCount.md) - [getDeletedMessageCount()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getDeletedMessageCount.md) # getUnreadMessages Retrieves all unread inbox messages for the device. ## Syntax ```dart Future> getUnreadMessages() ``` ## Returns - `Future>` - Returns a list of unread inbox messages. ## Example ```dart List unreadMessages = await SfmcSdk.getUnreadMessages(); print('Unread messages: ${unreadMessages.length}'); for (InboxMessage message in unreadMessages) { print('Unread message: ${message.subject}'); } ``` ## Related Methods - [getMessages()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getMessages.md) - [getReadMessages()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getReadMessages.md) - [getDeletedMessages()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getDeletedMessages.md) # Handle Carousel Click Actions When a carousel image has an associated URL action and a user taps the image, the URL handling delegate triggers. For more information about configuring URL handling, see [Customize Push Notification Functionality for iOS Apps](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_push_notifications/mc_engagement_push_notifications_ios_customize.md). # Handle Custom Keys Sent with Message Payload Send additional data with your push notifications using custom keys. Custom keys let you pass information beyond the standard notification title, body, and badge. Additional information can include product IDs, user preferences, tracking parameters, or any data your app needs. When a user taps a notification, your app can extract these custom values from the notification’s `userInfo` dictionary and use them to navigate to specific content, update the UI, trigger analytics events, or perform other custom logic. For example, an e-commerce app can include a product ID in a custom key to open the product detail page directly. A news app can pass an article ID to display the full story. Or you can include tracking parameters that third-party analytics tools use to measure campaign effectiveness. Enable custom keys on the Administration page in Marketing Cloud Engagement Setup before sending notifications with custom data. ![The MobilePush Administration page in Marketing Cloud Engagement, showing the Custom Keys option enabled.](https://developer.salesforce.com/media/push-messaging/custom-keys-marketer-enable.png) Next, implement custom key support in your app by extending your push notification handler to extract the push’s `userInfo` dictionary and the values it contains. ::::::tabset{tabs='["SDK v10+", "SDK v9", "SDK v8.1", "SDK v8", "SDK v7"]'} :::::tab This code example shows how to handle custom keys using version 10 or later of the SDK. ```swift // The method is called on the delegate when the user responds to the // notification by opening the app, dismissing the notification, or choosing a // UNNotificationAction. Set the delegate before the application returns from // applicationDidFinishLaunching:. func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void ) { // tell the SDK about the notification PushFeature.requestSdk { pushFeature in pushFeature?.setNotificationResponse(response) } // the dictionary containing custom keys let userInfo = response.notification.request.content.userInfo let someValue = userInfo["someKey"] as? String // App-specific usage print(someValue ?? "someValue is nil") completionHandler() } ``` ::::: :::::tab For version 9 of the SDK, use this code. ```swift // The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from applicationDidFinishLaunching:. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // tell the SDK about the notification SFMCSdk.requestPushSdk { mp in mp.setNotificationResponse(response) } // the dictionary containing custom keys let userInfo = response.notification.request.content.userInfo let someValue = userInfo["someKey"] as? String // application-specific usage follows print(someValue ?? "someValue is nil") completionHandler() } ``` ::::: :::::tab For version 8.1 of the SDK, use this code. ```swift // The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from applicationDidFinishLaunching:. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // tell the SDK about the notification SFMCSdk.requestPushSdk { mp in mp.setNotificationRequest(response.notification.request) } // the dictionary containing custom keys let userInfo = response.notification.request.content.userInfo let someValue = userInfo["someKey"] as? String // application-specific usage follows print(someValue ?? "someValue is nil") completionHandler() } ``` ::::: :::::tab For version 8.0 of the SDK, use this code. ```swift // The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from applicationDidFinishLaunching:. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // Tell the SDK about the notification // See Step 5: Capture Notifications on Launch only for 8.0.x under Migrate to Mobile Push SDK Version 8.x for iOS to capture the notification request. mp.setNotificationRequest(response.notification.request) // the dictionary containing custom keys let userInfo = response.notification.request.content.userInfo let someValue = userInfo["someKey"] as? String // application-specific usage follows print(someValue ?? "someValue is nil") completionHandler() } ``` ::::: :::::tab For version 7 of the SDK, use this code. ```swift // The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction. The delegate must be set before the application returns from applicationDidFinishLaunching:. func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // tell the MarketingCloudSDK about the notification MarketingCloudSDK.sharedInstance().sfmc_setNotificationRequest(response.notification.request) // the dictionary containing custom keys let userInfo = response.notification.request.content.userInfo let someValue = userInfo["someKey"] as? String // application-specific usage follows print(someValue ?? "someValue is nil") completionHandler() } ``` ::::: :::::: # Handle URLs The SDK doesn’t automatically present URLs from these sources: - CloudPages URLs from push notifications - OpenDirect URLs from push notifications - CloudPages URLs from inbox messages using the built-in `UITableView` delegate To handle URLs from these sources, follow these steps. 1. Implement the `URLHandlingDelegate` protocol in your app. 2. Use `setURLHandlingDelegate` method to set a delegate for the protocol. 3. Next, you’re prompted to implement the protocol method `sfmc_handleURL:type:` When an OpenDirect or CloudPages push notification is received, the SDK passes a `NSURL` value to `sfmc_handleURL:type:`. This value contains the push notification or inbox message, and includes the URL. A `type` value also reflects the source of the URL, which is either SFMCURLTypeCloudPages or SFMCURLTypeOpenDirect. **important:** If the development language is `Swift`, the class that implements the `URLHandlingDelegate` must be compatible with Objective-C. Prefix the class with `@objc` and extend `NSObject`, as shown in this example. ```swift // Framework import // The SFMCSDK module is included in the dependency packages for the SDK. Don't install it // separately or list it in your podfile. import SFMCSDK import PushFeatureSDK // Make sure your class adopts the protocol @objc class MyClass: NSObject, URLHandlingDelegate ... // Set the delegate somewhere in your application code (after configuring the SDK) PushFeature.requestSdk { pushFeature in pushFeature?.setURLHandlingDelegate(self) } ... // EXAMPLE IMPLEMENTATIONS // Implement the protocol method and have iOS handle the URL itself func sfmc_handleURL(_ url: URL, type: String) { if UIApplication.shared.canOpenURL(url) == true { if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: [:], completionHandler: { success in if success { print("url \(url) opened successfully") } else { print("url \(url) could not be opened") } }) } else { if UIApplication.shared.openURL(url) == true { print("URL \(url) opened successfully") } else { print("Couldn't open URL \(url)") } } } } // Implement the protocol method and use SFSafariViewController to present the URL within your application func sfmc_handleURL(_ url: URL, type: String) { let safariViewController = SFSafariViewController(url: url) window?.topViewController()?.present(safariViewController, animated: true) {} } // Implement the protocol method and take application-specific actions based on the URL itself func sfmc_handleURL(_ url: URL, type: String) { let queryItems = URLComponents(string: url.absoluteString)?.queryItems for item: URLQueryItem? in queryItems ?? [] { // do something in your application based on the parameters in the URL } } ``` # Handle URLs in Messages For security reasons, the Engagement SDK doesn’t automatically handle URLs sent in Push Notifications, In-App Messages, or Inbox Messages. Instead, your app’s code must handle the URLs that are passed to the SDK. Use the SDK’s URL handling methods to manage and process the URLs in your app. **important:** The SDK doesn’t automatically present URLs from `Alert+CloudPage` push notifications. For more information about handling URLs from push notifications and in-app messages, see: - [Customize Push Notification Handling for Android Apps](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications/mc_engagement_push_notifications_android_custom_notification.md) - [Required Methods for Button Actions in Android Apps For In App Message](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_in-app_messages/mc_engagement_in-app_messages_android.md) ## Handle Custom Keys Marketers use custom keys to provide metadata for personalization and tracking information within a push notification. Here are some example use cases for custom keys: - A marketer uses AMPscript or a merge field to send metadata about a contact’s loyalty level. - A marketer sends an ID value for the app to retrieve additional data. - A marketer sends image URLs with the push notification to allow a developer to build and include a carousel of images for a rich push notification. The Engagement SDK doesn’t automatically act on the custom keys delivered with the push notification. Your app’s code must handle the key-value pairs that it passes to the SDK. The SDK offers methods to facilitate custom key handling. See [NotificationMessage](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/MarketingCloudSdk/9.0/-marketing%20-cloud%20-s-d-k/com.salesforce.marketingcloud.notifications/-notification-message/index.html). ## See Also - [Customize Push Notification Functionality for Android Apps](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications/mc_engagement_push_notifications_android_customize.md) - [Customize Push Notification Functionality for iOS Apps](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications/mc_engagement_push_notifications_ios_customize.md) # Handle URLs in Messages For security reasons, the Mobile App Messaging SDK doesn’t automatically handle URLs that you send in Push Notifications. Instead, your app’s code must handle the URLs it passes to the SDK. Use the SDK’s URL handling methods to manage and process the URLs in your app. ## Handle Custom Keys Marketers use custom keys to provide metadata for personalization and tracking information within a push notification. Here are some example use cases for custom keys: - A marketer uses a merge field to send metadata about a user’s loyalty level. - A marketer sends an ID value for the app to retrieve additional data. - A marketer sends image URLs with the push notification to allow a developer to build and include a carousel of images for a rich push notification. The Mobile App Messaging SDK doesn’t automatically act on the custom keys delivered with the push notification. Your app’s code must handle the key-value pairs that it passes to the SDK. The SDK offers methods to facilitate custom key handling. See [NotificationMessage](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushmodelsmodule/com.salesforce.marketingcloud.pushmodels/-notification-message/index.html). ## See Also - [Customize Push Notification Functionality for Android Apps](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications/mc_next_push_notifications_android.md) - [Customize Push Notification Functionality for iOS Apps](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications/mc_next_push_notifications_ios.md) # Handle URLs in the SDK for iOS Control how your app responds to URLs in push notifications and inbox messages by implementing the URL handling protocol. The SDK passes URLs from CloudPages push notifications, OpenDirect push notifications, and inbox messages to your app, but doesn’t automatically present them. Implement the `URLHandlingDelegate` protocol to open URLs in Safari, display them in your app using `SFSafariViewController`, or trigger custom app logic based on URL parameters. To implement URL handling, follow these steps. 1. Implement the `URLHandlingDelegate` (v8.x) or `MarketingCloudSDKURLHandlingDelegate` (v7.x) protocol in your app. 2. Use `setURLHandlingDelegate` (v8.x) or `sfmc_setURLHandlingDelegate:` method to set a delegate for the protocol. 3. Implement the protocol method `sfmc_handleURL:type:`. When the SDK receives an OpenDirect or CloudPages push notification, it passes a `NSURL` value to `sfmc_handleURL:type:`. This value contains the push notification or inbox message, and includes the URL. A `type` value also reflects the source of the URL, which is either SFMCURLTypeCloudPages or SFMCURLTypeOpenDirect. **important:** If the development language is Swift, make the class that implements `URLHandlingDelegate` in version 8 or later or `MarketingCloudSDKURLHandlingDelegate` in version 7 Objective-C compatible. To make the delegate compatible, prefix the class with `@objc` and extend `NSObject`, as shown in these examples. ::::::tabset{tabs='["SDK v10+", "SDK v8.1", "SDK v8", "SDK v7"]'} :::::tab This code example shows how to handle URLs using version 10 or higher of the SDK. ```swift // Framework import // The SFMCSDK module is included in the dependency packages for the SDK. Don't install it // separately or list it in your podfile. import SFMCSDK import MarketingCloudSDK import PushFeatureSDK // Make sure your class adopts the protocol @objc class MyClass: NSObject, URLHandlingDelegate ... // Set the delegate somewhere in your application code after configuring the SDK PushFeature.requestSdk { pushFeature in pushFeature?.setURLHandlingDelegate(self) } ... // EXAMPLE IMPLEMENTATIONS // Implement the protocol method and have iOS handle the URL itself func sfmc_handleURL(_ url: URL, type: String) { if UIApplication.shared.canOpenURL(url) == true { if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: [:], completionHandler: { success in if success { print("url (url) opened successfully") } else { print("url (url) could not be opened") } }) } else { if UIApplication.shared.openURL(url) == true { print("URL (url) opened successfully") } else { print("Couldn't open URL (url)") } } } } // Implement the protocol method and use SFSafariViewController to present the // URL within your app func sfmc_handleURL(_ url: URL, type: String) { let safariViewController = SFSafariViewController(url: url) window?.topViewController()?.present(safariViewController, animated: true) {} } // Implement the protocol method and take app-specific actions based on the URL func sfmc_handleURL(_ url: URL, type: String) { let queryItems = URLComponents(string: url.absoluteString)?.queryItems for item: URLQueryItem? in queryItems ?? [] { // do something in your application based on the parameters in the URL } } ``` ::::: :::::tab For version 8.1 of the SDK, use this code. ```swift // Framework import // The SFMCSDK module is included in the dependency packages for the SDK. Don't install it // separately or list it in your podfile. import SFMCSDK import MarketingCloudSDK // Make sure your class adopts the protocol @objc class MyClass: NSObject, URLHandlingDelegate ... // Set the delegate somewhere in your application code after configuring the SDK SFMCSdk.requestPushSdk { mp in mp.setURLHandlingDelegate(self) } ... // EXAMPLE IMPLEMENTATIONS // Implement the protocol method and have iOS handle the URL itself func sfmc_handleURL(_ url: URL, type: String) { if UIApplication.shared.canOpenURL(url) == true { if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: [:], completionHandler: { success in if success { print("url (url) opened successfully") } else { print("url (url) could not be opened") } }) } else { if UIApplication.shared.openURL(url) == true { print("url (url) opened successfully") } else { print("url (url) could not be opened") } } } } // Implement the protocol method and use SFSafariViewController to present the // URL within your app func sfmc_handleURL(_ url: URL, type: String) { let safariViewController = SFSafariViewController(url: url) window?.topViewController()?.present(safariViewController, animated: true) { } } // Implement the protocol method and take app-specific actions based on the URL func sfmc_handleURL(_ url: URL, type: String) { let queryItems = URLComponents(string: url.absoluteString)?.queryItems for item: URLQueryItem? in queryItems ?? [] { // do something interesting in your application based on the parameters in the URL } } ``` ::::: :::::tab For version 8.0 of the SDK, use this code. ```swift // Framework import // The SFMCSDK module is included in the dependency packages for the SDK. Don't install it // separately or list it in your podfile. import SFMCSDK import MarketingCloudSDK // Make sure your class adopts the protocol @objc class MyClass: NSObject, URLHandlingDelegate ... // Set the delegate somewhere in your application code after configuring the SDK // and confirming that the SDK is operational mp.setURLHandlingDelegate(self) ... // EXAMPLE IMPLEMENTATIONS // Implement the protocol method and have iOS handle the URL itself func sfmc_handleURL(_ url: URL, type: String) { if UIApplication.shared.canOpenURL(url) == true { if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: [:], completionHandler: { success in if success { print("url (url) opened successfully") } else { print("url (url) could not be opened") } }) } else { if UIApplication.shared.openURL(url) == true { print("url (url) opened successfully") } else { print("url (url) could not be opened") } } } } // Implement the protocol method and use SFSafariViewController to present the // URL within your app func sfmc_handleURL(_ url: URL, type: String) { let safariViewController = SFSafariViewController(url: url) window?.topViewController()?.present(safariViewController, animated: true) { } } // Implement the protocol method and take app-specific actions based on the URL func sfmc_handleURL(_ url: URL, type: String) { let queryItems = URLComponents(string: url.absoluteString)?.queryItems for item: URLQueryItem? in queryItems ?? [] { // do something in the app based on the parameters in the URL } } ``` ::::: :::::tab For version 7 of the SDK, use this code. ```swift // Framework import import MarketingCloudSDK // Make sure your class adopts the protocol @objc class MyClass: NSObject, MarketingCloudSDKURLHandlingDelegate ... // Set the delegate somewhere in your application code after configuring the SDK MarketingCloudSDK.sharedInstance().sfmc_setURLHandlingDelegate(self) ... // EXAMPLE IMPLEMENTATIONS // Implement the protocol method and have iOS handle the URL itself func sfmc_handleURL(_ url: URL, type: String) { if UIApplication.shared.canOpenURL(url) == true { if #available(iOS 10.0, *) { UIApplication.shared.open(url, options: [:], completionHandler: { success in if success { print("url (url) opened successfully") } else { print("url (url) could not be opened") } }) } else { if UIApplication.shared.openURL(url) == true { print("url (url) opened successfully") } else { print("url (url) could not be opened") } } } } // Implement the protocol method and use SFSafariViewController to present the // URL within your app func sfmc_handleURL(_ url: URL, type: String) { let safariViewController = SFSafariViewController(url: url) window?.topViewController()?.present(safariViewController, animated: true) { } } // Implement the protocol method and take app-specific actions based on the URL func sfmc_handleURL(_ url: URL, type: String) { let queryItems = URLComponents(string: url.absoluteString)?.queryItems for item: URLQueryItem? in queryItems ?? [] { // do something in the app based on the parameters in the URL } } ``` ::::: :::::: # How the Engagement SDK Works Learn how the Engagement SDK interacts with your Marketing Cloud environment to deliver push notifications, in-app messages, and inbox messages to your app users. ## Push Notification Sequence of Events Push notifications are messages sent from your Marketing Cloud environment to a user’s device, even when the app isn’t actively running. This flow chart shows how the SDK, Push Notification Service, and Marketing Cloud work together to register devices and deliver notifications. ![Push Notification Sequence of Events](https://developer.salesforce.com/media/overview/Mkting_MobilePush_SequenceDiag_PushNotification_041124_zh.png) 1. When a mobile app opens and successfully initializes the SDK, the SDK communicates with the push notification service to obtain a device token. A push notification service is a service such as Apple Push Notification service (APNs) or Firebase Cloud Messaging (FCM) that manages push notifications for a device. 2. The push notification service returns a unique device token to the SDK, but only if the device has opted in to receive push notifications. 3. After receiving the device token, the SDK registers the device with your Marketing Cloud environment and submits critical information, such as the device token, device ID, push opt-in status, user identifier (contact key or party identifier), and any relevant attributes or tags. This registration process occurs asynchronously. 4. Your Marketing Cloud environment processes the registration to determine whether it can send push notifications to the device. This process includes checking whether the device is opted in or out of receiving push notifications. At this point, Marketing Cloud creates or updates a record. In Marketing Cloud Engagement, if the user is a new contact, Engagement creates a contact record. If the user is an existing contact, Engagement updates the existing contact record with the latest information, such as the user’s most recent app open time. This registration process can take up to five minutes. In Marketing Cloud Next, if the user is a new contact, Marketing Cloud Next creates an Individual record. If the user is an existing Individual, Marketing Cloud Next updates the existing Individual record with the latest information. This registration process can take up to 15 minutes. 5. After your Marketing Cloud environment processes the registration, a marketer sends push notifications using the device token received from the SDK. 6. The push notification service validates device tokens and delivers push notifications in these ways: a. If the device token is valid, the push notification service delivers the message to the device. b. If the device token is invalid or if the device is opted out, the push notification service notifies your Marketing Cloud environment to opt out the user’s device. The user also doesn’t receive the push notification. Opt-outs also occur if the device token is malformed or if the auth key is incorrect. 7. After the user opens and interacts with the push notification, the SDK records the event and sends analytics data to your Marketing Cloud environment. The SDK transmits analytics data after the application moves into the background or comes back into the foreground. If a user force-closes the app, the SDK stores the analytics data and sends it to your Marketing Cloud environment the next time the user opens the app. ## In-App Message Sequence of Events In-app messages are displayed to users while they use your app. The app downloads these messages to the device and displays them based on trigger criteria that you define. This flow chart shows how the SDK registers the device, downloads in-app messages, and displays them when trigger conditions are met. ![In-App Message Sequence of Events](https://developer.salesforce.com/media/overview/Mkting_MobilePush_SequenceDiag_InAppSend_041124_zh.png) 1. The SDK registers the device with your Marketing Cloud environment and asynchronously submits critical information, such as the device token, device ID, push opt-in status, user identifier (contact key or party identifier), and any relevant attributes or tags. 2. Your Marketing Cloud environment processes the registration to determine whether it can send in-app messages to the device. The registration process can take up to 15 minutes, after which updated information is visible in Contact Builder or your Individual records. 3. Your Marketing Cloud environment publishes the rendered in-app message, specifying the message’s trigger criteria, and makes the message available for the device to download. 4. Your Marketing Cloud environment notifies the SDK that a new in-app message is available via a silent push notification. Silent push notifications wake up the SDK without alerting users and are only sent to devices that are opted in to receive push notifications. 5. On receiving the silent push notification, the SDK downloads the new in-app messages, along with their priority and trigger criteria. Additionally, in-app messages are synced with the device at the start of the next session. This sync makes sure that even if the app misses silent push notifications, it can still download available messages when it’s next opened or brought to the foreground. If you edit an in-app message and reactivate the journey, the updated version of the in-app message is downloaded, replacing the older one. 6. After the in-app message is downloaded, it’s displayed on the device after the specified trigger criteria are met and evaluated by the SDK. After the user opens and interacts with the message, the SDK records the event and sends analytics to your Marketing Cloud environment. The SDK sends analytics data after the application moves into the background or comes back into the foreground. If a user force-closes the app, the SDK stores the analytics data and sends it to your Marketing Cloud environment the next time the user opens the app. 7. If you delete the in-app activity or journey after messages are downloaded to a device, messages that are still on the device remain functional. However, any devices that haven’t yet downloaded the message don’t receive it. ## Inbox Message Sequence of Events Inbox messages are persistent messages that are stored in a dedicated inbox within your app. Unlike push notifications or in-app messages, inbox messages remain available for users to view at any time. This flow chart shows how the SDK downloads inbox messages, how your app displays them, and how state changes are tracked. **important:** Inbox messaging is available only in Marketing Cloud Engagement. ![Inbox Message Sequence of Events](https://developer.salesforce.com/media/overview/Mkting_MobilePush_SequenceDiag_Inbox_042224_zh.png) 1. The SDK registers the device with Marketing Cloud Engagement and asynchronously submits critical information, such as the device token, device ID, push opt-in status, contact key, and any relevant attributes or tags. 2. Marketing Cloud Engagement processes the registration to determine whether it can send inbox messages to the device. The registration process can take up to 15 minutes, after which updated information is visible on the contact’s profile in Contact Builder. 3. Marketing Cloud Engagement publishes the rendered inbox message and makes the message available for the device to download. 4. Marketing Cloud Engagement notifies the SDK that a new inbox message is available via a silent push notification. Silent push notifications wake up the SDK without alerting users and are only sent to devices that are opted in to receive push notifications. 5. On receiving the silent push notification, the SDK downloads all of the available inbox messages. Additionally, the SDK also fetches inbox messages when the app comes to the foreground. This fetch makes sure that even if an app can’t receive silent push notifications (assuming it’s not opted in), the app can still download available inbox messages from Marketing Cloud Engagement. While you can use SDK convenience methods to refresh the inbox, the refresh is limited to one time every 60 seconds at most. 6. The app displays the inbox messages and view state. The app itself handles inbox data and uses the data to populate its own UI and view state. 7. The app forwards state changes to the SDK, which then send analytics data to Marketing Cloud Engagement. Make sure that the app code notifies the SDK of any state changes, such as a read or delete event. The SDK then asynchronously submits analytics after the app goes into the background or comes into the foreground. If a user force-closes the app, the SDK stores the analytics data and sends it to Marketing Cloud Engagement the next time the user opens the app. # Hybrid Platform Support for Unified Mobile SDK This section covers hybrid platform support for the Unified Mobile SDK, including frameworks such as React Native and Flutter. Use the topics in this section to set up, configure, and maintain hybrid framework integrations. # IAM Feature Module (In-App Messaging) In-App Messaging module with template rendering and frequency capping ## API Reference ### [Classes](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/iam-feature_classes_index.md) 2 classes # Identity `Class` Main class for managing identity information in the Salesforce Marketing Cloud SDK. The `Identity` class provides a singleton interface for managing user identity data, including profile information, custom attributes, and party identification details. All operations are performed thread-safely using an internal worker queue. ## Declaration ```swift @objc(SFIdentity) public final class Identity : NSObject @objc public func toJson() -> String public func edit(identity updater: @escaping (IdentityModifier) -> IdentityModifier) public func get() -> IdentityInfo? ``` ## Cases ### `toJson()` Converts the current identity information to a JSON string representation. ```swift @objc public func toJson() -> String ``` --- ### `edit(identity:)` Updates the identity information using a modifier closure. This method provides thread-safe access to modify identity data. The updater closure receives an `IdentityModifier` object that allows you to modify profile ID, attributes, and party identification information. All modifications are persisted to the database and trigger identity change events. Thread Safety: This method is thread-safe and uses an internal worker queue to ensure that identity modifications don’t interfere with other operations. Persistence: All changes made through this method are automatically persisted to the database and will trigger identity change events that other SDK modules can observe. ```swift public func edit(identity updater: @escaping (IdentityModifier) -> IdentityModifier) ``` --- ### `get()` Retrieves the current identity information. This method returns the current identity data including profile ID, attributes, and party identification information. The data is retrieved from the in-memory cache for optimal performance. Thread Safety: This method is thread-safe and uses an internal worker queue to ensure consistent data access. Performance: This method retrieves data from the in-memory cache, making it very fast. If no identity has been set, it returns `nil` . ```swift public func get() -> IdentityInfo? ``` **Returns:** An `IdentityInfo` object containing the current identity data, or `nil` if no identity record is found or if the identity manager is not properly initialized. --- # Identity Class ## Overview The `Identity` class is an immutable representation of a user's identity within the Salesforce Marketing Cloud SDK. It encapsulates user identification information including profile ID, party identification details, and custom attributes. ## Getting an Instance To obtain an `Identity` instance: ```kotlin SFMCSdk.requestSdk { sdk -> sdk.identity } ``` ## Updating Identity Two methods are available for updating identity: 1. **Kotlin DSL syntax** (recommended for Kotlin) - using the `edit` function 2. **Builder pattern** - for Java and Kotlin compatibility ## Properties | Property | Type | Description | | --------------------------- | ---------------------- | --------------------------------------------------------------- | | `profileId` | `String?` | Unique identifier for user profile (Marketing Cloud Engagement) | | `partyIdentificationName` | `String?` | User's display name or full name (Mobile App Messaging) | | `partyIdentificationNumber` | `String?` | Unique identifier number for user (Mobile App Messaging) | | `partyIdentificationType` | `String?` | User's category or classification (Mobile App Messaging) | | `attributes` | `Map` | Custom attributes map (shared by both services) | | `registrationId` | `String` | Registration identifier | ## Nested Types ### Builder ```kotlin class Builder ``` Provides a fluent API for setting identity properties and creating new `Identity` instances. ## Functions ### edit ```kotlin fun edit(editor: IdentityEditor.() -> Unit): Boolean ``` Kotlin DSL syntax for modifying `Identity` properties through an `IdentityEditor`. **Parameters:** - `editor`: Lambda function providing DSL editing interface **Returns:** `Boolean` indicating success of the edit operation --- ### newBuilder ```kotlin fun newBuilder(): Identity.Builder ``` Creates a new `Builder` instance initialized with current identity values, enabling modifications. **Returns:** `Identity.Builder` instance for updating properties --- ### toJson ```kotlin fun toJson(): JSONObject ``` Serializes the `Identity` to a `JSONObject` representation, including platform, profile ID, installation ID, party identification details, and attributes. **Returns:** `JSONObject` containing all identity properties --- ### equals ```kotlin open operator override fun equals(other: Any?): Boolean ``` Standard equality comparison implementation. --- ### hashCode ```kotlin open override fun hashCode(): Int ``` Standard hash code implementation. --- ### toString ```kotlin open override fun toString(): String ``` String representation of the identity. # IdentityEditor **Package:** `com.salesforce.marketingcloud.sfmcsdk.components.identity` **Platform:** androidJvm **SDK Version:** 11.0.0 ## Overview The `IdentityEditor` class wraps the `Identity.Builder` functions to provide an idiomatic Kotlin syntax for modifying identity information. ## Description This class enables convenient editing of identity data using Kotlin DSL syntax. It supports both Marketing Cloud Engagement and Mobile App Messaging identity attributes. ## Usage Example ```kotlin SFMCSdk.requestSdk { sdk -> sdk.identity.edit { profileId = "John" } } ``` ## Properties ### attributes ```kotlin val attributes: AttributesEditor ``` Provides an `AttributesEditor` for modifying the attribute map. These attributes are shared between Marketing Cloud Engagement and Mobile App Messaging. --- ### partyIdentificationName ```kotlin var partyIdentificationName: String? ``` The identity name used by Mobile App Messaging. --- ### partyIdentificationNumber ```kotlin var partyIdentificationNumber: String? ``` A unique identifier number for the user in Mobile App Messaging (e.g., "party-123"). --- ### partyIdentificationType ```kotlin var partyIdentificationType: String? ``` The identity's category or classification used by Mobile App Messaging. --- ### profileId ```kotlin var profileId: String? ``` The profile identifier used by Marketing Cloud Engagement. # IdentityInfo `Protocol` ## Declaration ```swift @objc(SFIdentityInfo) public protocol IdentityInfo var profileId: String? { get } var attributes: [String : String] { get } var partyIdentificationNumber: String? { get } var partyIdentificationName: String? { get } var partyIdentificationType: String? { get } ``` ## Cases ### `profileId` ```swift var profileId: String? { get } ``` --- ### `attributes` ```swift var attributes: [String : String] { get } ``` --- ### `partyIdentificationNumber` ```swift var partyIdentificationNumber: String? { get } ``` --- ### `partyIdentificationName` ```swift var partyIdentificationName: String? { get } ``` --- ### `partyIdentificationType` ```swift var partyIdentificationType: String? { get } ``` --- # IdentityModifier `Protocol` ## Declaration ```swift @objc(SFIdentityModifier) public protocol IdentityModifier var profileId: String { get set } var attributes: [String : String] { get } var partyIdentificationNumber: String? { get set } var partyIdentificationName: String? { get set } var partyIdentificationType: String? { get set } func addAttribute(key: String, value: String) func addAttributes(attributes: [String : String]) func clearAttribute(key: String) func clearAttributes(keys: [String]) func clearAllAttributes() ``` ## Cases ### `profileId` ```swift var profileId: String { get set } ``` --- ### `attributes` ```swift var attributes: [String : String] { get } ``` --- ### `partyIdentificationNumber` ```swift var partyIdentificationNumber: String? { get set } ``` --- ### `partyIdentificationName` ```swift var partyIdentificationName: String? { get set } ``` --- ### `partyIdentificationType` ```swift var partyIdentificationType: String? { get set } ``` --- ### `addAttribute(key:value:)` ```swift func addAttribute(key: String, value: String) ``` --- ### `addAttributes(attributes:)` ```swift func addAttributes(attributes: [String : String]) ``` --- ### `clearAttribute(key:)` ```swift func clearAttribute(key: String) ``` --- ### `clearAttributes(keys:)` ```swift func clearAttributes(keys: [String]) ``` --- ### `clearAllAttributes()` ```swift func clearAllAttributes() ``` --- # Implement Default and Custom Notification Channels On devices that run Android 8.0 or later, the SDK creates a default notification channel called `marketing` to assign all notifications to it. To change the name of the default channel, set a string resource value for `mcsdk_default_notification_channel_name`. After the SDK creates the `NotificationChannel`, the channel isn’t updated unless your application calls [`NotificationManager#createDefaultNotificationChannel(Context context, boolean forceRecreate)`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.notifications/-notification-manager/-companion/create-default-notification-channel.html). ## Custom Configuration You can create custom notification channels and assign channels to each notification, as depicted by the following example configuration. ```java val channelId = "my_custom_channel" if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { (getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager).createNotificationChannel( NotificationChannel( channelId, "Marketing Messages", android.app.NotificationManager.IMPORTANCE_DEFAULT ) ) } SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { pushFeatureModuleConfig = PushFeatureConfig.builder().apply { // Other configuration options setNotificationCustomizationOptions( NotificationCustomizationOptions.create( R.drawable.ic_notification_icon, null, NotificationManager.NotificationChannelIdProvider { context, notificationMessage -> // Custom logic to determine which channel to use for the message. channelId } ) ) }.build() }) { // TODO handle initialization status } ``` To assign a notification to a channel, implement the SDK [`NotificationChannelIdProvider`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.notifications/-notification-manager/-notification-channel-id-provider/index.html) interface. Ensure that you include a channel with your message. Otherwise, the app doesn’t display the message to the recipient. **note:** You can customize channel priority, colors, and sounds. To use custom sounds, give each channel its own sound configuration while creating it. You can’t use sounds with the SDK default channel option. # Implement Default and Custom Notification Channels for the Android SDK On devices that run Android 8.0 or later, the SDK creates a default notification channel called `marketing` to assign all notifications to it. To change the name of the default channel, set a string resource value for `mcsdk_default_notification_channel_name`. After the SDK creates the `NotificationChannel`, the channel isn’t updated unless your application calls [`NotificationManager#createDefaultNotificationChannel(Context context, boolean forceRecreate)`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.notifications/-notification-manager/-companion/create-default-notification-channel.html). You can create custom notification channels and assign channels to each notification, as shown in these code examples. ::::::tabset{tabs='["SDK v8+", "SDK v7"]'} :::::tab ```java val channelId = "my_custom_channel" if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { (getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager).createNotificationChannel( NotificationChannel( channelId, "Marketing Messages", android.app.NotificationManager.IMPORTANCE_DEFAULT ) ) } SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { pushModuleConfig = MarketingCloudConfig.builder().apply { // Other configuration options setNotificationCustomizationOptions( NotificationCustomizationOptions.create( R.drawable.ic_notification_icon, null, NotificationManager.NotificationChannelIdProvider { context, notificationMessage -> // Whatever custom logic required to determine which channel should be used for the message. channelId } ) ) }.build(applicationContext) }) { // TODO handle initialization status } ``` ::::: :::::tab ```java val channelId = "my_custom_channel" if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { (getSystemService(Context.NOTIFICATION_SERVICE) as android.app.NotificationManager).createNotificationChannel( NotificationChannel( channelId, "Marketing Messages", android.app.NotificationManager.IMPORTANCE_DEFAULT ) ) } MarketingCloudSdk.init(applicationContext as Application, MarketingCloudConfig.builder().apply { // Other configuration options setNotificationCustomizationOptions( NotificationCustomizationOptions.create( R.drawable.ic_notification_icon, null, NotificationManager.NotificationChannelIdProvider { context, notificationMessage -> // Whatever custom logic required to determine which channel should be used for the message. channelId } ) ) }.build(applicationContext)) { // TODO handle initialization status } ``` ::::: :::::: To assign a notification to a channel, implement the SDK [NotificationChannelIdProvider](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.notifications/-notification-manager/-notification-channel-id-provider/index.html) interface. Ensure that you include a channel with your message. Otherwise, the app doesn’t display the message to the recipient. You can customize channel priority, colors, and sounds. To use custom sounds, give each channel its own sound configuration while creating it. You can’t use sounds with the SDK default channel option. # Implement In-App Messaging on Android The SDK offers features that extend in-app messaging support for Android. Register event listeners, track message lifecycle, control message display, customize fonts, and set status bar colors to create a tailored experience for your app users. ## Button Actions [Implement required methods for button actions](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_in-app_messages_android_button_action_methods.md) to handle Web URL and App URL actions in in-app messages. Configure the SDK with a `UrlHandler` to control what happens when users tap buttons on in-app messages. ## Event Listener [Register an event listener](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_in-app_messages_android_events_listen.md) to control aspects of message display and get information about the in-app message display lifecycle. After the SDK initializes, register your event listener with `InAppMessageManager` to receive callbacks for message events. ## Track View States [Track message view states](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_in-app_messages_android_track_view_states.md) by implementing callback methods that notify your app when an in-app message is shown or closed. Use these methods to manage the activity stack for your app and respond to views appearing or disappearing. ## Control Message Display [Prevent or delay message display](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_in-app_messages_android_prevent_delay_display.md) by returning `false` from the `shouldShowMessage` method. Control when in-app messages appear based on the state of your app, such as during loading processes or sign-in flows. Capture message data to display messages later when your app is ready. ## Customize Fonts [Customize the font](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_in-app_messages_android_customize_fonts.md) for in-app messages to match the branding of your app. Override the default system font for titles, body text, and button labels by passing a valid TypeFace to the SDK. ## Status Bar Color [Set a custom status bar color](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_in-app_messages_android_set_status_bar.md) for in-app messages. The SDK doesn't inherit the status bar color for your app automatically. Define a custom color that the SDK applies on Android Lollipop and newer versions. # Implement In-App Messaging on Android To use certain in-app messaging features, such as button actions, you must change some SDK configurations. ## Required Methods for Button Actions Marketers can configure the action that occurs when an end user taps a button on an in-app message. The SDK handles actions for `Notification Settings` and `Location Settings`, while actions for `Web URL` and `App URL` require that you implement [`UrlHandler`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/common/com.salesforce.marketingcloud/-url-handler/index.html) as a new SDK initialization method. The following example shows how you can configure the SDK to handle button clicks in in-app messages. ``` SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { inAppMessagingFeatureModuleConfig = InAppMessagingFeatureConfig.builder().apply { // Other configuration options // Tell the SDK how to handle button clicks in an In-App Message setUrlHandler { context, url, _ -> getActivity( context, Random().nextInt(), Intent(Intent.ACTION_VIEW, url.toUri()), PendingIntent.FLAG_UPDATE_CURRENT ) } }.build() }) { // TODO handle initialization status } ``` ## Optional Methods To control aspects of message display and to get information about the in-app message display lifecycle, use the SDK’s optional in-app messaging [`EventListener`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/inappmessagingfeaturemodule/com.salesforce.marketingcloud.inappmessagingfeature/-in-app-message-manager/-event-listener/index.html) After the SDK’s initialization is complete, you can register your in-app message [`EventListener`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/inappmessagingfeaturemodule/com.salesforce.marketingcloud.inappmessagingfeature/-in-app-message-manager/-event-listener/index.html) with [`InAppMessageManager`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/inappmessagingfeaturemodule/com.salesforce.marketingcloud.inappmessagingfeature/-in-app-message-manager/index.html). ``` // Set at configuration time SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { inAppMessagingFeatureModuleConfig = InAppMessagingFeatureConfig.builder().apply { setEventListener(object : InAppMessageManager.EventListener { override fun shouldShowMessage(message: InAppMessage): Boolean { return if (shouldShowMessage /* Your Custom logic confirming to show in-app message */) { true } else { // Store message id for later val blockedMessageId = message.id false } } override fun didShowMessage(message: InAppMessage) = Unit override fun didCloseMessage(message: InAppMessage, action: InAppMessageCloseAction) = Unit }) }.build() }) // Or set at anytime after configuration InAppMessagingFeature.requestSdk { inAppMessagingFeatureModule -> inAppMessagingFeatureModule.getInAppMessageManager().setInAppMessageListener(...) } ``` ### didShowMessage and didCloseMessage The `didShowMessage` and `didCloseMessage` callback methods help ensure that you can appropriately manage your app’s view state. In-app messages are shown in an activity controlled by the SDK within your app’s activity stack. Your app is required to respond to a view appearing or disappearing. - [`didShowMessage`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/inappmessagingfeaturemodule/com.salesforce.marketingcloud.inappmessagingfeature/-in-app-message-manager/-event-listener/did-show-message.html) is invoked when the in-app message is initially presented. - [`didCloseMessage`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/inappmessagingfeaturemodule/com.salesforce.marketingcloud.inappmessagingfeature/-in-app-message-manager/-event-listener/did-close-message.html) is invoked after the user closes the message and includes the close reason. ### Prevent or Delay Message Display You can delay or prevent an in-app message’s display. For example, you can choose to prevent an in-app message from displaying during the loading process, sign-in flow, and other situations. To prevent or delay message display, set the [`shouldShowMessage`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/inappmessagingfeaturemodule/com.salesforce.marketingcloud.inappmessagingfeature/-in-app-message-manager/-event-listener/should-show-message.html) method to return `false`. Furthermore, you can capture data of any [in-app message](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/inappmessagingmodelsmodule/com.salesforce.marketingcloud.inappmessaging.models/-in-app-message/index.html) and use it for displaying the specific message at a later time. For example, you can present the message after an end user has successfully signed in by capturing the [`ID`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/inappmessagingmodelsmodule/com.salesforce.marketingcloud.inappmessaging.models/-in-app-message/id.html) of the message and showing that message later, as shown in this example. ``` InAppMessagingFeature.requestSdk { inAppMessagingFeatureModule -> inAppMessagingFeatureModule.getInAppMessageManager().showMessage(blockedMessageInd) } ``` ### Customize Display By default, in-app messages use your device’s system font. However, you can override the default font face to customize the appearance of an in-app message’s `title`, `body`, and `button` labels. **note:** You can’t alter the font size since the message’s design defines it. To set the display font, pass the SDK a valid [`TypeFace`](https://developer.android.com/reference/android/graphics/Typeface) for the device’s installed fonts, or your app’s custom fonts as shown in this example. ``` // set at configuration time SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { inAppMessagingFeatureModuleConfig = InAppMessagingFeatureConfig.builder().apply { setTypeface(appFontFace) }.build() }) // OR set after configuration time InAppMessagingFeature.requestSdk { inAppMessagingFeatureModule -> inAppMessagingFeatureModule.getInAppMessageManager().setTypeface(appFontFace) } ``` ### Set Status Bar Color The SDK doesn’t use [`AppCompatActivity`](https://developer.android.com/reference/androidx/appcompat/app/AppCompatActivity) and can’t inherit your app’s status bar color automatically. Instead, you must define a custom status bar color. The SDK applies this color on Android API versions that support the status bar color, which is Lollipop and newer. ``` // set at configuration time SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { inAppMessagingFeatureModuleConfig = InAppMessagingFeatureConfig.builder().apply { setStatusBarColor( ContextCompat.getColor(this as Context, R.color.colorPrimary) ) }.build() }) // OR set after configuration time InAppMessagingFeature.requestSdk { inAppMessagingFeatureModule -> inAppMessagingFeatureModule.getInAppMessageManager().setStatusBarColor( ContextCompat.getColor(this as Context, R.color.colorPrimary) ) } ``` # Implement In-App Messaging on iOS The SDK offers features that extend in-app messaging support for iOS. Set event delegates, track message lifecycle, control message display, customize fonts, and configure push permissions to create a tailored experience for your app users. ## Event Delegate [Set an event delegate](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_in-app_messages_ios_set_event_delegate.md) to receive notifications about the in-app message display lifecycle. By implementing the event delegate, you can track when messages are shown or closed, control whether messages can be displayed based on the state of your app, and manage the view hierarchy when messages appear. ## Track View States [Track message view states](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_in-app_messages_ios_track_view_states.md) by implementing delegate methods that notify your app when an in-app message appears or closes. Use these methods to pause or resume animations, update UI state, track analytics, and manage app behavior based on message visibility. ## Control Message Display [Prevent or delay message display](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_in-app_messages_ios_prevent_delay_display.md) by using the `shouldShow` method. Control when in-app messages appear based on the state of your app, such as during loading processes or sign-in flows. Capture message data to display messages later when your app is ready. ## Customize Fonts [Customize the font face](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_in-app_messages_ios_customize_fonts.md) used in in-app messages to match your app's branding. Override the default system font for titles, body text, buttons, and tertiary text labels by passing a valid font name to the SDK. ## Push Permission Authorization [Configure push permission authorization](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_in-app_messages_ios_configure_push_permission.md) for Push Primers, which are in-app messages that educate users about the benefits of push notifications. Control which specific push notification permissions are requested when users interact with a Push Primer, such as alerts, sounds, or badges. # Implement In-App Messaging on iOS To use certain in-app messaging features, such as button actions, some SDK configurations are needed. The following sections describe these configurations. ## Enable In-App Module To enable and configure In-App Messaging, extend the initialization code described in [Configure the SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_next_integrate_ios/mc_next_integrate_ios_configure.md). The code example shows how to enable the In-App module for the iOS SDK. ```swift func configureSdk() -> Bool { ... // InAppMessageFeatureConfiguration let iamFeatureConfiguration = InAppMessagingFeatureConfigBuilder() .setEventDelegate(self) .setURLHandlingDelegate(self) .setInAppMessageFont(name: "HelveticaNeue") .build() configBuilder = configBuilder .setInAppMessagingFeature(config: iamFeatureConfiguration) // Set the completion handler to take action when all modules initialization is completed. // Seting the completion handler is optional. let completionHandler: ((_ status: [ModuleInitStatus]) -> Void) = { [weak self] status in DispatchQueue.main.async { self?.handleSDKInitializationCompletion(status: status) } } SFMCSdk.initializeSdk(configBuilder.build(), completion: completionHandler) return true } // MARK: - SDK Initialization Completion Handler private func handleSDKInitializationCompletion(status: [ModuleInitStatus]) { var allSuccessful = true for moduleStatus in status { print("Module: \(moduleStatus.moduleName.rawValue), Status: \(moduleStatus.initStatus.rawValue)") if moduleStatus.initStatus == .success { // Handle successful initialization for each module switch moduleStatus.moduleName { case .engagement: // Handle successful initialization for Marketing cloud module case .pushFeature: // Handle successful initialization for Push Feature module case .inappMessagingFeature: // Handle successful initialization for In-App Feature module default: break } } else if moduleStatus.initStatus == .error { allSuccessful = false // module failed to initialize, check logs for more details } else if moduleStatus.initStatus == .cancelled { allSuccessful = false // module initialization was cancelled (for example due to re-confirguration triggered before init was completed) } else if moduleStatus.initStatus == .timeout { allSuccessful = false // module failed to initialize due to timeout, check logs for more details } } if allSuccessful { print("SDK initialization completed successfully") } else { print("SDK initialization completed with errors - check logs above") } } ``` ## Required Methods for Button Actions The SDK handles actions for `Notification Settings` and `Location Settings`, while actions for `Web URL` and `App URL` require that you implement [URL handling](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_next_handle_urls.md). ## Optional Methods To control aspects of message display and to get information about the in-app message display lifecycle, use the SDK’s optional delegate functionality. ### setEventDelegate To make your application a delegate of the SDK’s in-app messaging functionality, use `setEventDelegate`, as shown in these examples. This code example shows how to set the event delegate using the SDK. ``` // adhere to the InAppMessageEventDelegate protocol in your class declaration class MyViewController: UIViewController, InAppMessageEventDelegate ... // somewhere in your implementation, set your class as the delegate of the SDK for In-App Message events // this should be done early in your class’s initialization, if possible InAppMessagingFeature.requestSdk { iam in iam?.setEventDelegate(self) } ``` ### didShow and didClose The [didShow and didClose delegate methods](/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessageeventdelegate.html) help you manage your app’s view state. In-app messages are shown as the top view controller in your app’s hierarchy. Your application must be able to respond to a view appearing or disappearing. ``` func didShow(inAppMessage message: InAppMessageDetails) { // message shown } func didClose(inAppMessage message: InAppMessageDetails, action: InAppMessageCloseAction) { // message closed } ``` ### Prevent or Delay Message Display You can delay or prevent an in-app message’s display using the [shouldShow](/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessageeventdelegate.html) method. For example, you can choose to prevent an in-app message from displaying during the loading process, sign-in flow, and other situations. To prevent or delay message display, set the `shouldShow` method to return `false`. ```swift func shouldShow(inAppMessage message: InAppMessageDetails) -> Bool { // using your app's logic, can this message be shown? if (self.messageCanBeShown) { return true } else { // capture the message id in the event self.showMessageId = message.id } return false } ``` Furthermore, you can capture in-app message data and use it for displaying the specific message at a later time. For example, you can present the message after an end user has successfully signed in. The message ID is accessed directly via the InAppMessageDetails object within the delegate, and the display is triggered through the InAppMessagingFeature module. Use these methods: - `message.id` (property of InAppMessageDetails) - `showInAppMessage` ``` // if you've previously captured the messageId, you can show the In-App Message later // (for instance, you've returned false from shouldShow(inAppMessage message: InAppMessageDetails) because // your UI or application logic couldn’t be interrupted) if (self.showMessageId != nil) { InAppMessagingFeature.requestSdk { iam in iam?.showInAppMessage(messageId: self.showMessageId) } } ``` ### Configure Push Permission Authorization When a Push Primer is displayed and the user taps the permission button, the SDK triggers the standard iOS notification authorization request. To customize which permissions are requested (such as alerts, sounds, or badges), use the `setNotificationAuthorizationOptions` method during SDK initialization. **note:** If you do not explicitly configure these options, the SDK defaults to requesting `.alert`, `.sound`, and `.badge`. The code example shows how to configure push permission authorization for the iOS SDK. ``` func configureSdk() -> Bool { ... // InAppMessageFeatureConfiguration let iamFeatureConfiguration = InAppMessagingFeatureConfigBuilder() .setEventDelegate(self) .setURLHandlingDelegate(self) .setInAppMessageFont(name: "HelveticaNeue") .setNotificationAuthorizationOptions([.alert, .sound]) .build() configBuilder = configBuilder .setInAppMessagingFeature(config: iamFeatureConfiguration) ... } ``` ### Customize Display By default, in-app messages use your device’s system font. However, you can override the default font face to customize the appearance of an in-app message’s `title`, `body`, `button`, and `tertiary text` labels. **note:** You can’t change the font size because it’s defined by the design of the message. To set the display font, use the `setInAppMessageFont` method to pass the SDK a valid font name for the device’s installed fonts, or your app’s custom fonts. ``` InAppMessagingFeature.requestSdk { iam in iam?.setInAppMessageFont(name: "Zapfino") } ``` If the font is invalid, the SDK returns `false` and reverts to using the system font. # Implement Inbox Messaging on Android The Salesforce Engagement SDK for Android provides convenience methods for refreshing the app inbox and managing messages, including retrieving, reading, and deleting them. Enable inbox messaging during SDK initialization to access message properties, manage Alert + Inbox notifications, and customize message handling for your app users. Enable Inbox Messaging during the SDK initialization process. The configuration varies based on your SDK version. ::::::tabset{tabs='["10.x or higher", "8.x or 9.x", "7.x"]'} :::::tab ``` SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { engagementModuleConfig = MarketingCloudConfig.builder().apply { // Other configuration values setInboxEnabled(true) // Enable Inbox messaging, default = false }.build(applicationContext) }) { // Handle initialization status } ``` ::::: :::::tab ``` SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { pushModuleConfig = MarketingCloudConfig.builder().apply { // Other configuration values setInboxEnabled(true) // Enable Inbox messaging, default = false }.build(applicationContext) }) { // Handle initialization status } ``` ::::: :::::tab ``` MarketingCloudSdk.init(applicationContext as Application, with(MarketingCloudConfig.builder()) { // Other configuration values setInboxEnabled(true) // Enable Inbox messaging, default = false }.build(applicationContext)) { // Handle initialization status } ``` ::::: :::::: For more information about inbox message management methods, see [InboxMessageManager Method Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/index.html). ## Public Properties [Access inbox message properties](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_inbox_messages_android_public_properties.md) to retrieve and manage messages. The SDK provides convenience methods for getting all messages, unread messages, read messages, and deleted messages. Each message object contains properties like ID, subject, dates, custom keys, and message type information. ## Alert + Inbox Messages [Configure Alert + Inbox message handling](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_inbox_messages_android_alert_messages.md) to enable users to tap on inbox push notifications and get redirected to the corresponding inbox message. Control whether inbox messages are automatically marked as read when users tap notifications. ## See Also - [Enable and Use Analytics](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_analytics/mc_engagement_analytics_android_implement.md) - [Handle URLs and Custom Keys](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_handle_urls.md) # Implement Inbox Messaging on iOS The SDK provides convenience methods for refreshing the inbox and managing messages, including retrieving, reading, and deleting them. Enable inbox messaging during SDK initialization to access message properties, manage Alert + Inbox notifications, and customize message handling for your app users. The SDK supports three types of inbox messages: - **Inbox 1.0** - The original inbox message format with CloudPage URLs - **Inbox 2.0** - Enhanced inbox messages with additional fields like subtitles and messages, plus new call-to-action options including App URL, Web URL, and None (introduced in SDK version 9.0) - **Push Copy to Inbox (PCTI)** - Push notifications that also appear in the inbox To enable these inbox features during SDK initialization, use the `setInboxEnabled` method of the [MarketingCloudSdkConfigBuilder](/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/marketingcloudsdkconfigbuilder.html) class. For SDK versions 8 and earlier, show Inbox Only messages sent from Marketing Cloud Engagement in your app by using the `UITableView` data source provided by the SDK in a `UIViewController`. The `UIViewController` serves as the inbox in your app to show these messages. The SDK automatically updates the `UITableView` data source with new messages after they're downloaded. Manage row selection in your table view using the SDK's basic `UITableView` delegate. If your app requires custom behavior, implement your own `UITableView` delegate. This example demonstrates a basic inbox implementation using the SDK as the data source and delegate. ::::::tabset{tabs='["SDK v8", "SDK v7"]'} :::::tab Use this code to implement a basic inbox in version 8 of the SDK for iOS. ```swift var dataSource: InboxMessagesDataSource? var delegate: InboxMessagesDelegate? override func viewDidLoad() { super.viewDidLoad() dataSource = SFMCSdk.mp.inboxMessagesTableViewDataSourceFor(tableView: self.tableView) delegate = SFMCSdk.mp.inboxMessagesTableViewDelegateFor(tableView: self.tableView, dataSource: dataSource!) self.tableView.dataSource = dataSource self.tableView.delegate = delegate ... } ``` ::::: :::::tab Use this code to implement a basic inbox in version 7 of the SDK for iOS. ```swift var dataSource: MarketingCloudSDKInboxMessagesDataSource? var delegate: MarketingCloudSDKInboxMessagesDelegate? override func viewDidLoad() { super.viewDidLoad() dataSource = MarketingCloudSDK.sharedInstance().sfmc_inboxMessagesTableViewDataSource(for: self.tableView) delegate = MarketingCloudSDK.sharedInstance().sfmc_inboxMessagesTableViewDelegate(for: self.tableView, dataSource: dataSource!) self.tableView.dataSource = dataSource self.tableView.delegate = delegate ... } ``` ::::: :::::: For greater control over the presentation and user experience of your inbox, implement your own data source and delegate using the methods provided by the SDK. With Inbox 2.0 in SDK version 9 and later, the SDK no longer supports custom data sources and delegates for the inbox table view. These methods have been removed: - `inboxMessagesTableViewDataSourceFor(tableView:)` - `inboxMessagesTableViewDelegateFor(tableView:dataSource:)` In SDK version 9 or later, use the SDK's convenience methods to retrieve and manage inbox messages directly. See [Public Properties](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_inbox_messages_ios_public_properties.md) for available methods. For more information about inbox message management methods, see the [InboxMessages Method Reference](/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/marketingcloudsdk.html#inboxmessages). ## Public Properties [Access inbox message properties](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_inbox_messages_ios_public_properties.md) using convenience methods that retrieve all messages, unread messages, read messages, or deleted messages. Each message dictionary contains properties like ID, subject, dates, custom data, and message type that your app can use. ## Alert + Inbox Messages [Configure Alert + Inbox messages](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_inbox_messages_ios_alert_messages.md) to enable users to tap on an inbox push notification and get redirected to the corresponding inbox message. Configure automatic read marking when notifications are tapped, and refresh inbox messages when your app is in the foreground. # Implement Location Messaging on Android The Salesforce Engagement SDK for Android uses the location capabilities of your customer's device to trigger location-based notifications. The SDK caches geofence messages and displays them when a device crosses a geofence boundary. Enable geofences and beacons to deliver targeted, location-aware experiences for your app users. To successfully use this functionality, your Marketing Cloud Engagement admin must enable your account with access to MobilePush and Location Services. You must also obtain user permission for location services. ## Add Geofences [Add geofence support](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_location_messages_android_geofence_add.md) to trigger location-based notifications when users cross geofence boundaries. Configure dependencies, permissions, and SDK initialization to enable geofence messaging. ## Add Beacons [Add beacon support](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_location_messages_android_beacon_add.md) to trigger proximity-based notifications when users come near Bluetooth beacons. Configure AltBeacon dependencies, permissions, and SDK initialization to enable beacon messaging. ## Enable Beacon Debug Logging [Enable debug logging for beacons](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_location_messages_android_beacon_debug_enable.md) to troubleshoot beacon-related issues. Use AltBeacon's LogManager class to route logs through the Engagement MCLogListener interface. # Implement Location Messaging on iOS The Salesforce Engagement SDK for iOS uses location capabilities of your customer's device to trigger location-based notifications. The SDK caches geofence messages and displays them on devices when users cross a geofence boundary. Enable location features, configure beacon support, and segment location messages to deliver targeted, location-aware experiences for your app users. To successfully use this functionality, your Marketing Cloud Engagement admin must enable your account with access to MobilePush and Location Services. Starting with iOS 14, users have the option to use approximate instead of precise location. Geofences and beacons aren't triggered for users who provide approximate location permission. See _Apple Developer Documentation_: [Accuracy Authorization](https://developer.apple.com/documentation/corelocation/cllocationmanager/3600215-accuracyauthorization). Location messaging and beacon support in iOS versions 14 and later require precise location authorization. The SDK sends only precise location updates to Marketing Cloud Engagement, and ignores approximate location data. When you enable location services in the SDK configuration, you can use location messaging by calling a single method. You can enable location in your SDK configuration using the `setLocationEnabled` method of the [MarketingCloudSdkConfigBuilder](/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/marketingcloudsdkconfigbuilder.html) class. Apple requires that you add these keys to your `Info.plist` file to enable location services. - `NSLocationAlwaysUsageDescription` - `NSLocationAlwaysAndWhenInUseUsageDescription` - `NSLocationWhenInUseUsageDescription` For more information, see [Choosing the Location Services Authorization to Request](https://developer.apple.com/documentation/corelocation/choosing_the_authorization_level_for_location_services) on Apple's Developer Documentation site. ![A list of properties for the Info.plist file, showing the location-related properties enabled](https://developer.salesforce.com/media/location-messaging/location.png) **important:** The SDK requires **Always** permissions for full geofence and beacon functionality. An application doesn't receive location messages if an app user selects **When-in-use authorization**. When your application is ready to enable location features, including geofence and beacon messaging, call the SDK's `startWatchingLocation` method to start watching location. ::::::tabset{tabs='["SDK v10+", "SDK v8 or 9", "SDK v7"]'} :::::tab ``` MarketingCloudSdk.requestSdk { mc in mc?.startWatchingLocation() } ``` ::::: :::::tab ``` SFMCSdk.requestPushSdk { mp in mp.startWatchingLocation() } ``` ::::: :::::tab ``` MarketingCloudSDK.sharedInstance().sfmc_startWatchingLocation() ``` ::::: :::::: The `MarketingCloudSDK+Location.h` header file details additional methods to get information about location and control the frameworks behavior. **important:** The SDK suppresses geofence messages with no content. If you include AMPscript or a merge field in your message that returns an empty string, your app doesn't display that message to the user. ## Enable Beacon Support [Enable beacon support](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_location_messages_ios_beacon_enable.md) to range for beacons in the background and access the device's last known location. Configure your app's Info.plist to ensure beacon functionality works when your app is in the background or suspended. ## Enable Background Location Updates [Enable background location updates](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_location_messages_ios_background_enable.md) to allow the app to periodically download new regions and messages. This feature is useful for users who spend extended time within a single 5-kilometer radius, ensuring they receive updated geofence and beacon messages. ## Segment Location Messages [Segment location messages](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_location_messages_ios_segment.md) to deliver messages to a subset of your audience based on custom criteria. Implement the location delegate to evaluate whether to show a message based on user attributes, app state, or message custom keys. # Implement the SDK Manually If you don’t use SPM or CocoaPods, you can implement the SDK manually. The frameworks that you add to your project depend on which version of the SDK you use. **important:** Download these frameworks only from the linked GitHub repositories. ::::::tabset{tabs='["SDK v11", "SDK v10", "SDK v8"]'} :::::tab 1. Download the latest versions of the frameworks: - MarketingCloudSDK: https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS.git - PushFeatureSDK: https://github.com/salesforce-marketingcloud/push-feature-sdk-ios.git - SFMCSDK: https://github.com/salesforce-marketingcloud/sfmc-sdk-ios.git - AppGroupSDK: https://github.com/salesforce-marketingcloud/app-group-internal-sdk.git - InAppMessagingFeatureSDK: https://github.com/salesforce-marketingcloud/iam-feature-sdk-ios.git 2. Copy the relevant .xcframework directories into your project folder. 3. In Xcode, open your project and select the appropriate target. 4. In the general settings for the target, add the required .xcframework files to Frameworks, Libraries, and Embedded Content. 5. In Build Settings, add `-ObjC` to Other Linker Flags. ::::: :::::tab 1. Download the latest versions of the frameworks: - MarketingCloudSDK: https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS.git - PushFeatureSDK: https://github.com/salesforce-marketingcloud/push-feature-sdk-ios.git - SFMCSDK: https://github.com/salesforce-marketingcloud/sfmc-sdk-ios.git 2. Copy the relevant .xcframework directories into your project folder. 3. In Xcode, open your project and select the appropriate target. 4. In the general settings for the target, add the required .xcframework files to Frameworks, Libraries, and Embedded Content. 5. In Build Settings, add `-ObjC` to Other Linker Flags. ::::: :::::tab 1. Download the latest versions of the frameworks: - MarketingCloudSDK: https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS.git - SFMCSDK: https://github.com/salesforce-marketingcloud/sfmc-sdk-ios.git 2. Copy the relevant .xcframework directories into your project folder. 3. In Xcode, open your project and select the appropriate target. 4. In the general settings for the target, add the required .xcframework files to Frameworks, Libraries, and Embedded Content. 5. In Build Settings, add `-ObjC` to Other Linker Flags. ::::: :::::: After you install the dependencies, [configure the SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_integrate_ios_configure.md). # Implement the SDK with CocoaPods To add the SDK as a dependency in your app’s Podfile, add the pod to your Xcode project. See _Using CocoaPods_: [Adding Pods to an Xcode project](https://guides.cocoapods.org/using/using-cocoapods.html). ::::::tabset{tabs='["SDK v11", "SDK v10", "SDK v8"]'} :::::tab ```swift target 'MyApp' do pod 'MarketingCloudSDK' pod 'SFPushFeatureSDK' pod 'SFInAppMessagingFeatureSDK' end ``` ::::: :::::tab ```swift target 'MyApp' do pod 'MarketingCloudSDK' pod 'SFPushFeatureSDK' end ``` ::::: :::::tab ```swift target 'MyApp' do pod 'MarketingCloudSDK' end ``` ::::: :::::: **important:** The pods listed in these examples include the `SFMCSDK` module automatically. Don't add the module to your podfile manually. Next, open the .xcworkspace created by the install process using Xcode and start using the SDK. **important:** Don’t open .xcodeproj directly. Opening a project file instead of a workspace can lead to errors. After you install the dependencies, [configure the SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_integrate_ios_configure.md). # Implement the SDK with Swift Package Manager Implement version 8.0.0 or later of the Salesforce Engagement SDK by using Swift Package Manager (SPM). ::::::tabset{tabs='["SDK v11", "SDK v10", "SDK v8"]'} :::::tab 1. Open your project Xcode. 2. Go to **Project Settings**. 3. On the Package Dependencies tab, click **+** to add a package. 4. Enter the repository URL and add these packages: - MarketingCloudSDK: https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS.git - PushFeatureSDK: https://github.com/salesforce-marketingcloud/push-feature-sdk-ios.git - InAppMessagingFeatureSDK: https://github.com/salesforce-marketingcloud/iam-feature-sdk-ios.git 5. Review the package details and confirm to complete the installation. ::::: :::::tab 1. Open your project Xcode. 2. Go to **Project Settings**. 3. On the Package Dependencies tab, click **+** to add a package. 4. Enter the repository URL and add these packages: - MarketingCloudSDK: https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS.git - PushFeatureSDK: https://github.com/salesforce-marketingcloud/push-feature-sdk-ios.git 5. Review the package details and confirm to complete the installation. ::::: :::::tab 1. Open your project Xcode. 2. Go to **Project Settings**. 3. On the Package Dependencies tab, click **+** to add a package. 4. Enter the repository URL and add these packages: - MarketingCloudSDK: https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS.git - SFMCSDK: https://github.com/salesforce-marketingcloud/sfmc-sdk-ios.git 5. Review the package details and confirm to complete the installation. ::::: :::::: **note:** For SDK v10 and v11, the `SFMCSDK` module is included automatically as a dependency of these packages. For SDK v8, add the `SFMCSDK` package directly. After you install the dependencies, [configure the SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_integrate_ios_configure.md). # In App Messaging Feature Module ## Packages - [com.salesforce.marketingcloud.inappmessagingfeature](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-inappmessagingfeature/inappmessagingfeature_index.md) - [com.salesforce.marketingcloud.inappmessagingfeature.config](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-inappmessagingfeature-config/inappmessagingfeature-config_index.md) # In App Messaging Models Module ## Packages - [com.salesforce.marketingcloud.inappmessaging.models](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-inappmessaging-models/inappmessaging-models_index.md) # In-App Messages In-app messages let you deliver relevant, personalized content to your app users without requiring push notification permissions. These engaging full-screen, modal, or banner messages appear while users interact with your app, providing an effective way to communicate announcements, promotions, or important information. The Marketing Cloud Engagement SDK provides features to extend in-app messaging support on both Android and iOS platforms. You can register event listeners, track message lifecycle, control message display, customize fonts, and configure display settings to create a tailored experience for your app users. ## Key Features - **Event Management**: Register listeners or delegates to control message display and track lifecycle events - **Display Control**: Prevent or delay messages based on app state, such as during loading or authentication - **Lifecycle Tracking**: Monitor when messages appear or close to manage app behavior - **Visual Customization**: Customize fonts and colors to match your app's branding - **Push Permission Support**: Use Push Primer messages to educate users about push notification benefits ## Platform-Specific Implementation Choose your platform to learn how to implement in-app messaging in your mobile app: - [Implement In-App Messaging on Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_in-app_messages_android.md) - [Implement In-App Messaging on iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_in-app_messages_ios.md) ## See Also - [Push Notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_push_notifications/mc_engagement_push_notifications_android.md) - [Inbox Messages](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_inbox_messages/mc_engagement_inbox_messages.md) # In-App Messaging Use in-app messaging to deliver relevant, personalized messages to your app users, even if they haven’t enabled push notifications. In-app messages are engaging full-screen, modal, or banner messages that appear when your users use your app. To ensure that your app has the latest in-app message data when it comes to the foreground, the SDK loads in-app messages and prepares them for presentation at the top of your app’s view stack. Only one message is displayed each time the app comes into the foreground. Depending on how you configure your app, you can trigger the SDK to download in-app messages in the background. **note:** You can send in-app messages by using Journey Builder. See _Salesforce Help_: [Create an In-App Message Activity in Journey Builder](https://help.salesforce.com/articleView?id=mktg.mc_jb_configure_inapp_in_journey_builder.htm). # In-App Messaging This section provides API reference details for the In-App Messaging module in the Flutter unified plugin. ## setInAppMessageDecisionHandler Registers a handler that decides whether the SDK should display an in-app message. This handler gives the app the final say over the native `shouldShowMessage` or `shouldShow` delegate. ### Syntax ```dart IamModule.setInAppMessageDecisionHandler(handler); ``` ### Parameters | Parameter | Type | Description | | --------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `handler` | `InAppMessageDecisionHandler?` | Invoked with the full `InAppMessage` to decide whether it should display. Return or complete with `true` to display the message, `false` to suppress it. Pass `null` to clear the handler and restore default SDK behavior, where every message shows immediately. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_iam/sfmc_iam.dart'; await IamModule.requestSdk(); IamModule.setInAppMessageDecisionHandler((message) => message.id != 'blocked-id'); ``` ## showInAppMessage Displays a specific in-app message by its identifier. ### Syntax ```dart IamModule.showInAppMessage(id); ``` ### Parameters | Parameter | Type | Description | | --------- | -------- | ------------------------------------------------------------------------------------------------------------- | | `id` | `String` | The identifier of the in-app message to display. If this value is blank or null, the API rejects the request. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_iam/sfmc_iam.dart'; await IamModule.requestSdk(); await IamModule.showInAppMessage('welcome-message'); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/inappmessagingfeaturemodule/com.salesforce.marketingcloud.inappmessagingfeature/-in-app-message-manager/show-message.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/InAppMessagingFeatureSdk/1.0/Classes/InAppMessagingFeature.html#/c:@CM@InAppMessagingFeatureSDK@objc(cs)SFInAppMessagingFeature(im)showInAppMessageWithMessageId:>) ## inAppMessageEvents A broadcast stream of in-app message lifecycle events (`shouldShow`, `didShow`, `didClose`). ### Syntax ```dart IamModule.inAppMessageEvents; ``` ### Returns - `Stream` - Emits an `InAppMessageEvent` each time an in-app message's lifecycle phase changes. ### Example ```dart import 'package:sfmc_iam/sfmc_iam.dart'; await IamModule.requestSdk(); IamModule.inAppMessageEvents.listen((event) { switch (event.type) { case InAppMessageEventType.shouldShow: // About to display: consult custom rules if needed. break; case InAppMessageEventType.didShow: // Message is now on screen: record impression. break; case InAppMessageEventType.didClose: // Message dismissed: record close. break; } debugPrint('IAM ${event.type.name}: ${event.message.id}'); }); ``` ## setInAppMessageFont Sets the font used to render in-app messages. ### Syntax ```dart IamModule.setInAppMessageFont(fontName); ``` ### Parameters | Parameter | Type | Description | | ---------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `fontName` | `String?` | The font name to apply. In Android, the name is resolved with `Typeface.create`. In iOS, it's the PostScript name passed to `setInAppMessageFont`. Pass `null` to revert to the system default font. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_iam/sfmc_iam.dart'; await IamModule.requestSdk(); await IamModule.setInAppMessageFont('HelveticaNeue-Bold'); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/inappmessagingfeaturemodule/com.salesforce.marketingcloud.inappmessagingfeature/-in-app-message-manager/set-typeface.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/InAppMessagingFeatureSdk/1.0/Classes/InAppMessagingFeature.html#/c:@CM@InAppMessagingFeatureSDK@objc(cs)SFInAppMessagingFeature(im)setInAppMessageFontWithName:>) ## setStatusBarColor Sets the status bar color of the in-app message activity. Only Android apps support this capability. ### Syntax ```dart IamModule.setStatusBarColor(colorArgb); ``` ### Parameters | Parameter | Type | Description | | ----------- | ----- | ------------------------------------------------ | | `colorArgb` | `int` | A 32-bit ARGB color value, such as `0xFF0000FF`. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_iam/sfmc_iam.dart'; await IamModule.requestSdk(); await IamModule.setStatusBarColor(0xFF0000FF); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/inappmessagingfeaturemodule/com.salesforce.marketingcloud.inappmessagingfeature/-in-app-message-manager/set-status-bar-color.html) # In-App Messaging This section provides API reference details for the In-App Messaging module in React Native unified plugin. ## showInAppMessage Displays a specific in-app message by its identifier. ### Syntax ```javascript InAppMessagingSdkModule.showInAppMessage(messageId); ``` ### Parameters | Parameter | Type | Description | | ----------- | -------- | ------------------------------------------------------------------------------------------------ | | `messageId` | `string` | The in-app message ID to display. Use a valid message ID from your in-app message configuration. | ### Returns - `void` ### Example ```javascript import { IamModule } from "@sfmc/react-native-iam"; import type { IamApi } from "@sfmc/react-native-iam"; const iam: IamApi = await IamModule.requestSdk(); iam.showInAppMessage("message-id"); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/inappmessagingfeaturemodule/com.salesforce.marketingcloud.inappmessagingfeature/-in-app-message-manager/show-message.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/InAppMessagingFeatureSdk/1.0/Classes/InAppMessagingFeature.html#/c:@CM@InAppMessagingFeatureSDK@objc(cs)SFInAppMessagingFeature(im)showInAppMessageWithMessageId:>) # In-App Messaging Android Apps that use SDK Version 11 ## Overview In version 11, the In-App Messaging component was migrated to a standalone feature module. This migration involves the following key changes: - **Package Name Changes:** Updated to reflect the new modular structure. - **New Configuration Pattern:** In-App Messaging can now be configured at SDK configuration time (recommended). - **Updated Event Listener:** Added the `InAppMessageCloseAction` function parameter to the `didCloseMessage` function in the `InAppMessageManager.EventListener`. ## Configuration In-App Messaging configuration is now performed at SDK Configuration time. While this approach is recommended, previous runtime configuration options remain available through the new `InAppMessagingFeatureModule` class. **Note:** You can no longer access the `InAppMessageManager` through the Marketing Cloud SDK as it has been removed from the core library. ## How to Configure In-App Messaging in Android SDK v11 ``` kotlin SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { inAppMessagingFeatureModuleConfig = InAppMessagingFeatureConfig.builder().apply { // set configuration options for In App Messaging }.build() }) ``` ``` kotlin InAppMessagingFeature.requestSdk { inAppMessagingFeatureModule -> // set configuration options for In App Messaging } ``` For more information see, [Implement In-App Messaging on Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/implement-in-app-messaging-android.html). # In-App Messaging in Android Apps that use SDK Version 10 The processes for implementing and customizing in-app messaging have been updated in version 10 of the SDK. To upgrade your app to version 10 of the SDK, first [update the initialization code](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v10.md) -->. Then, use these code examples to update the in-app messaging code in your app. ## Implement IAM on Android Use this code example to implement in-app messaging during SDK initialization. ```kotlin SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { engagementModuleConfig = MarketingCloudConfig.builder().apply { // Other configuration options // Tell the SDK how to handle button clicks in an In-App Message setUrlHandler(UrlHandler { context, url, _ -> PendingIntent.getActivity( context, Random().nextInt(), Intent(Intent.ACTION_VIEW, url.toUri()), PendingIntent.FLAG_UPDATE_CURRENT ) }) }.build(applicationContext) }) { // TODO handle initialization status } ``` ## Optional Methods Use this code example to set the in-app message listener. ```kotlin MarketingCloudSdk.requestSdk { engagementSdk -> engagementSdk.inAppMessageManager.setInAppMessageListener(object : InAppMessageManager.EventListener { override fun shouldShowMessage(message: InAppMessage): Boolean { return if (shouldShowMessage /* Your Custom logic confirming to show in-app message */) { true } else { // Store message id for later val blockedMessageId = message.id false } } override fun didShowMessage(message: InAppMessage) = Unit override fun didCloseMessage(message: InAppMessage) = Unit }) } ``` ## Prevent or Delay Message Display Use this code example to prevent or delay the display of an in-app message. ```kotlin MarketingCloudSdk.requestSdk { engagementSdk -> engagementSdk.inAppMessageManager.showMessage(blockedMessageId) } ``` ## Customize Display Use this code example to customize the font used in an in-app message. ```kotlin MarketingCloudSdk.requestSdk { engagementSdk -> engagementSdk.inAppMessageManager.setTypeface(appFontFace) } ``` ## Set Status Bar Color Use this code example to set the status bar color of an in-app message. ```kotlin MarketingCloudSdk.requestSdk { engagementSdk -> engagementSdk.inAppMessageManager.setStatusBarColor( ContextCompat.getColor(this as Context, R.color.colorPrimary) ) } ``` # In-App Messaging in iOS Apps that use SDK Version 10 The processes for implementing and customizing in-app messaging have been updated in version 10 of the SDK. To upgrade your app to version 10 of the SDK, first [update the initialization code](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v10.md). Then, use these code examples to update the in-app messaging code in your app. ## Optional Methods To make your application a delegate of the SDK’s in-app messaging functionality, use `setEventDelegate`. This code example shows how to set the event delegate using version 10 of the SDK. ```swift // adhere to the InAppMessageEventDelegate protocol in your class declaration class MyViewController: UIViewController, InAppMessageEventDelegate ... // somewhere in your implementation, set your class as the delegate of the SDK for In-App Message events // this should be done early in your class’s initialization, if possible MarketingCloudSdk.requestSdk { mc in mc?.setEventDelegate(self) } ``` ## Delay Message Display Use this code example to prevent or delay the display of an in-app message. ```swift // If you previously captured the messageId, you can show the In-App Message // later (for example, if you returned false from sfmc_shouldShowInAppMessage() // because your UI or app logic couldn’t be interrupted). if (self.showMessageId != nil) { MarketingCloudSdk.requestSdk { mc in mc?.showInAppMessage(messageId: self.showMessageId) } } ``` ## Customize Display Use this code example to customize the font used in an in-app message. ```swift MarketingCloudSdk.requestSdk { mc in mc?.setInAppMessage(fontName: "Zapfino") } ``` # In-App Messaging in iOS Apps that use SDK Version 11 The processes for implementing and customizing in-app messaging have been updated in version 11 of the SDK. To upgrade your app to version 11 of the SDK, first [update the initialization code](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v11.md). Then, use these code examples to update the in-app messaging code in your app. ## Optional Methods To make your application a delegate of the SDK’s in-app messaging functionality, use `setEventDelegate`. This code example shows how to set the event delegate using version 11 of the SDK. ```swift // adhere to the InAppMessageEventDelegate protocol in your class declaration class MyViewController: UIViewController, InAppMessageEventDelegate ... // somewhere in your implementation, set your class as the delegate of the SDK for In-App Message events // this should be done early in your class’s initialization, if possible InAppMessagingFeature.requestSdk { iam in iam?.setEventDelegate(self) } ``` ## Prevent or Delay Message Display You can delay or prevent an in-app message’s display using the [shouldShow](/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessageeventdelegate.html) method. For example, you can choose to prevent an in-app message from displaying during the loading process, sign-in flow, and other situations. To prevent or delay message display, set the `shouldShow` method to return `false`. ```swift func shouldShow(inAppMessage message: InAppMessageDetails) -> Bool { // using your app's logic, can this message be shown? if (self.messageCanBeShown) { return true } else { // capture the message id in the event self.showMessageId = message.id } return false } ``` In version 11.0, the message ID is accessed directly via the InAppMessageDetails object within the delegate, and the display is triggered through the InAppMessagingFeature module. Use these methods: - `message.id` (property of InAppMessageDetails) - `showInAppMessage` ``` // if you've previously captured the messageId, you can show the In-App Message later // (for instance, you've returned false from shouldShow(inAppMessage message: InAppMessageDetails) because // your UI or application logic couldn’t be interrupted) if (self.showMessageId != nil) { InAppMessagingFeature.requestSdk { iam in iam?.showInAppMessage(messageId: self.showMessageId) } } ``` ## Customize Display Use this code example to customize the font used in an in-app message. ```swift InAppMessagingFeature.requestSdk { iam in iam?.setInAppMessageFont(name: "Zapfino") } ``` # InAppMessage ## Overview `InAppMessage` is a data class in the Salesforce Marketing Cloud Unified SDK that represents an in-app message configuration. It implements the Android `Parcelable` interface for efficient serialization. **Package:** `com.salesforce.marketingcloud.inappmessaging.models` **Module:** inappmessagingmodelsmodule **Version:** 1.0.0 **SDK Version:** 11.0 ## Class Declaration ```kotlin data class InAppMessage( // constructor parameters listed below ) : Parcelable ``` ## Constructor ### Parameters | Parameter | Type | Default Value | Description | | -------------------------- | --------------------------------- | ---------------------------- | -------------------------------------------------------------- | | `id` | `String` | - | Message identifier | | `priority` | `Int` | `999` | Message priority for display ordering | | `startDateUtc` | `Date?` | `null` | Message start date in UTC | | `endDateUtc` | `Date?` | `null` | Message end date in UTC | | `modifiedDateUtc` | `Date?` | `null` | Last modification date in UTC | | `displayLimit` | `Int` | `1` | Maximum number of times the message can be displayed | | `displayCount` | `Int` | `0` | Current count of how many times the message has been displayed | | `type` | `InAppMessage.Type` | - | Message type (modal, banner, fullscreen, etc.) | | `windowColor` | `String?` | `null` | Window background color | | `displayDuration` | `Long` | `-1` | Display duration in milliseconds (-1 for indefinite) | | `backgroundColor` | `String?` | - | Message background color | | `cornerRadius` | `InAppMessage.Size` | `Size.s` | Corner radius size | | `layoutOrder` | `InAppMessage.LayoutOrder` | `LayoutOrder.ImageTitleBody` | Component layout order | | `media` | `InAppMessage.Media?` | `null` | Media configuration (image/video) | | `title` | `InAppMessage.TextField?` | `null` | Title text field configuration | | `body` | `InAppMessage.TextField?` | `null` | Body text field configuration | | `tertiaryText` | `InAppMessage.TertiaryTextField?` | `null` | Tertiary text field with hyperlink support | | `closeButton` | `InAppMessage.CloseButton?` | `null` | Close button configuration | | `buttonConfiguration` | `InAppMessage.ButtonConfig` | `ButtonConfig.twoUp` | Button layout configuration | | `buttons` | `List?` | `null` | List of action buttons | | `messageDelaySec` | `Int` | `0` | Delay before displaying the message in seconds | | `displaySuppressionAction` | `List?` | `null` | List of actions that suppress message display | | `shadow` | `InAppMessage.Shadow?` | `null` | Shadow effect configuration | | `additionalMargin` | `InAppMessage.Margin?` | `null` | Additional margin spacing | | `animation` | `InAppMessage.Animation?` | `null` | Animation configuration | | `border` | `InAppMessage.Border?` | `null` | Border configuration | | `appLimitOverride` | `Boolean` | `false` | Override app-level display limits | | `source` | `Event.Producer` | - | Event producer source | ## Properties All constructor parameters are exposed as public properties with the `@JvmField` annotation, making them directly accessible from both Kotlin and Java code. ## Methods ### Data Class Methods #### component1() through component28() ```kotlin fun component1(): String // id fun component2(): Int // priority // ... through component28 ``` Component functions for destructuring the data class. #### copy() ```kotlin fun copy( id: String = this.id, priority: Int = this.priority, // ... all other parameters with defaults ): InAppMessage ``` Creates a copy of the instance with optional parameter modifications. #### equals() ```kotlin fun equals(other: Any?): Boolean ``` Compares this instance with another object for equality. #### hashCode() ```kotlin fun hashCode(): Int ``` Returns a hash code value for the object. #### toString() ```kotlin fun toString(): String ``` Returns a string representation of the object. ### Parcelable Methods #### describeContents() ```kotlin fun describeContents(): Int ``` Describe the kinds of special objects contained in this Parcelable instance. #### writeToParcel() ```kotlin fun writeToParcel(parcel: Parcel, flags: Int): Unit ``` Flatten this object into a Parcel. ### Companion Object #### CREATOR ```kotlin companion object { val CREATOR: Parcelable.Creator } ``` Used by the Android framework for parceling and unparceling `InAppMessage` instances. ## Nested Types ### Enums #### Alignment Defines component alignment options. **Values:** - `start` - Align to the start - `center` - Align to the center - `end` - Align to the end #### ButtonConfig Defines button layout configurations. **Values:** - `twoUp` - Two-button layout (default) - Additional values may be available #### ContentMode Defines media content scaling modes. **Values:** - `fill` - Fill the container (default) - `fit` - Fit within the container - Additional values may be available #### LayoutOrder Defines the order of message components. **Values:** - `ImageTitleBody` - Image, then title, then body (default) - Additional values may be available #### Size Predefined size values for various styling properties. **Values:** - `xs` - Extra small - `s` - Small (commonly used default) - `m` - Medium - `l` - Large - `xl` - Extra large - `xxl` - Extra extra large - `e2e` - Edge-to-edge (used in Media.ImageSize) #### TextAlignment Text alignment options. **Values:** - `left` - Left-aligned - `center` - Center-aligned (default) - `right` - Right-aligned #### Type Message type variants. **Values:** - `modal` - Modal dialog message - `banner` - Banner message - `fullscreen` - Fullscreen message - Additional values may be available ### Data Classes #### Animation Animation settings for the in-app message. ```kotlin data class Animation( val type: AnimationType? = null, // Animation style val duration: Int = 450 // Animation duration in milliseconds ) : Parcelable ``` #### Border Border styling configuration. ```kotlin data class Border( val width: Size = Size.s, // Border width val color: String? = null // Border color (hex or named) ) : Parcelable ``` #### Button Action button configuration. ```kotlin data class Button( val id: String, // Button identifier val index: Int = 0, // Button index for ordering val text: String, // Button text val actionType: ActionType = ActionType.close, // Action type val action: String? = null, // Action value/URL val backgroundColor: String? = null, // Background color val cornerRadius: Size = Size.s, // Corner radius val font: Font? = null, // Font configuration val border: Border? = null, // Border configuration val margin: Margin? = null, // Margin spacing val additionalMargin: Margin? = null, // Additional margin val textAlignment: TextAlignment = TextAlignment.center, // Text alignment val shadow: Shadow? = null // Shadow effect ) : Parcelable ``` #### CloseButton Close button configuration. ```kotlin data class CloseButton( val alignment: Alignment = Alignment.end, // Button alignment val iconColor: String? = null, // Icon color val backgroundColor: String? = null, // Background color val additionalMargin: Margin? = null // Additional margin ) : Parcelable ``` #### Font Font configuration. ```kotlin data class Font( val size: Size = Size.s, // Font size val color: String? = null, // Font color val style: FontStyle? = null, // Font style (bold, italic, etc.) val fontFamily: String? = null // Font family name ) : Parcelable ``` #### Margin Spacing configuration for all sides. ```kotlin data class Margin( val top: Size? = null, // Top margin val bottom: Size? = null, // Bottom margin val left: Size? = null, // Left margin val right: Size? = null // Right margin ) : Parcelable ``` #### Media Image or video media configuration. ```kotlin data class Media( val url: String, // Media URL val altText: String? = null, // Accessibility alt text val size: ImageSize = ImageSize.e2e, // Image size val cornerRadius: Size = Size.s, // Corner radius val altMedia: String? = null, // Alternative media URL val insetSize: Size? = null, // Inset size val border: Border? = null, // Border configuration val shadow: Shadow? = null, // Shadow effect val margin: Margin? = null, // Margin spacing val additionalMargin: Margin? = null, // Additional margin val aspectRatio: String = DEFAULT_ASPECT_RATIO, // Aspect ratio val contentMode: ContentMode = ContentMode.fill // Content scaling mode ) : Parcelable ``` #### Shadow Shadow effect configuration. ```kotlin data class Shadow( val length: Size? = null, // Shadow length/blur radius val color: String? = null // Shadow color ) : Parcelable ``` #### TextField Basic text field configuration. ```kotlin data class TextField( val text: String, // Text content val alignment: Alignment = Alignment.center, // Text alignment val font: Font? = null, // Font configuration val margin: Margin? = null, // Margin spacing val additionalMargin: Margin? = null // Additional margin ) : Parcelable ``` #### TertiaryTextField Text field with hyperlink support, extends TextField functionality. ```kotlin data class TertiaryTextField( val text: String, // Text content val alignment: Alignment = Alignment.center, // Text alignment val font: Font? = null, // Font configuration val margin: Margin? = null, // Margin spacing val additionalMargin: Margin? = null, // Additional margin val hyperlinks: List? = null, // List of hyperlink URLs val linkColor: String? = null // Hyperlink color ) : Parcelable ``` ## Usage Example ```kotlin // Create a simple modal in-app message val message = InAppMessage( id = "msg_12345", type = InAppMessage.Type.modal, backgroundColor = "#FFFFFF", title = InAppMessage.TextField( text = "Welcome!", font = InAppMessage.Font( size = InAppMessage.Size.l, color = "#000000" ) ), body = InAppMessage.TextField( text = "Thanks for using our app!", font = InAppMessage.Font( size = InAppMessage.Size.m, color = "#333333" ) ), buttons = listOf( InAppMessage.Button( id = "btn_1", text = "Got it!", actionType = ActionType.close, backgroundColor = "#007AFF" ) ), closeButton = InAppMessage.CloseButton( alignment = InAppMessage.Alignment.end, iconColor = "#666666" ), source = Event.Producer.SFMC ) ``` ## Notes - All properties use `@JvmField` annotation for direct Java interoperability - Color values can be specified as hex strings (e.g., "#FFFFFF") or named colors - Nullable properties allow for flexible configuration - Default values are provided for most styling properties - The class implements `Parcelable` for efficient passing between Android components - Complete enum value lists may vary; refer to source code for exhaustive options # InAppMessageAlignment `Enumeration` ## Declaration ```swift @objc(SFMCSdkInAppMessageAlignment) public enum InAppMessageAlignment : Int case unknown = -1 case beginning = 0 case center case end ``` ## Cases ### `unknown` Represents an unsupported or unrecognized alignment. ```swift case unknown = -1 ``` --- ### `beginning` ```swift case beginning = 0 ``` --- ### `center` ```swift case center ``` --- ### `end` ```swift case end ``` --- # InAppMessageAnimation `Protocol` ## Declaration ```swift @objc(SFMCSdkInAppMessageAnimation) public protocol InAppMessageAnimation var type: InAppMessageAnimationType { get } var duration: Int { get } ``` ## Cases ### `type` ```swift var type: InAppMessageAnimationType { get } ``` --- ### `duration` ```swift var duration: Int { get } ``` --- # InAppMessageAnimationType `Enumeration` ## Declaration ```swift @objc(SFMCSdkInAppMessageAnimationType) public enum InAppMessageAnimationType : Int case unknown = -1 case fade = 0 case slideTop case slideBottom case slideLeft case slideRight case none ``` ## Cases ### `unknown` Represents an unsupported or unrecognized animation type. ```swift case unknown = -1 ``` --- ### `fade` ```swift case fade = 0 ``` --- ### `slideTop` ```swift case slideTop ``` --- ### `slideBottom` ```swift case slideBottom ``` --- ### `slideLeft` ```swift case slideLeft ``` --- ### `slideRight` ```swift case slideRight ``` --- ### `none` ```swift case none ``` --- # InAppMessageBorder `Protocol` ## Declaration ```swift @objc(SFMCSdkInAppMessageBorder) public protocol InAppMessageBorder var width: InAppMessageSize { get } var color: String? { get } ``` ## Cases ### `width` ```swift var width: InAppMessageSize { get } ``` --- ### `color` ```swift var color: String? { get } ``` --- # InAppMessageButton `Protocol` ## Declaration ```swift @objc(SFMCSdkInAppMessageButton) public protocol InAppMessageButton var id: String? { get } var index: Int { get } var text: String? { get } var textAlignment: InAppMessageAlignment { get } var backgroundColor: String? { get } var cornerRadius: InAppMessageSize { get } var actionType: InAppMessageButtonActionType { get } var action: String? { get } var fontFamily: String? { get } var fontSize: InAppMessageSize { get } var fontStyle: String? { get } var fontColor: String? { get } var border: InAppMessageBorder? { get } var margin: InAppMessageSpacing? { get } var additionalMargin: InAppMessageSpacing? { get } var shadow: InAppMessageShadow? { get } ``` ## Cases ### `id` ```swift var id: String? { get } ``` --- ### `index` ```swift var index: Int { get } ``` --- ### `text` ```swift var text: String? { get } ``` --- ### `textAlignment` ```swift var textAlignment: InAppMessageAlignment { get } ``` --- ### `backgroundColor` ```swift var backgroundColor: String? { get } ``` --- ### `cornerRadius` ```swift var cornerRadius: InAppMessageSize { get } ``` --- ### `actionType` ```swift var actionType: InAppMessageButtonActionType { get } ``` --- ### `action` ```swift var action: String? { get } ``` --- ### `fontFamily` ```swift var fontFamily: String? { get } ``` --- ### `fontSize` ```swift var fontSize: InAppMessageSize { get } ``` --- ### `fontStyle` ```swift var fontStyle: String? { get } ``` --- ### `fontColor` ```swift var fontColor: String? { get } ``` --- ### `border` ```swift var border: InAppMessageBorder? { get } ``` --- ### `margin` ```swift var margin: InAppMessageSpacing? { get } ``` --- ### `additionalMargin` ```swift var additionalMargin: InAppMessageSpacing? { get } ``` --- ### `shadow` ```swift var shadow: InAppMessageShadow? { get } ``` --- # InAppMessageButtonActionType `Enumeration` ## Declaration ```swift @objc(SFMCSdkInAppMessageButtonActionType) public enum InAppMessageButtonActionType : Int case unknown = -1 case close = 0 case url case pushSettings case locationSettings case pushPermission ``` ## Cases ### `unknown` Represents an unsupported or unrecognized button action type. ```swift case unknown = -1 ``` --- ### `close` ```swift case close = 0 ``` --- ### `url` ```swift case url ``` --- ### `pushSettings` ```swift case pushSettings ``` --- ### `locationSettings` ```swift case locationSettings ``` --- ### `pushPermission` ```swift case pushPermission ``` --- # InAppMessageButtonConfiguration `Enumeration` ## Declaration ```swift @objc(SFMCSdkInAppMessageButtonConfiguration) public enum InAppMessageButtonConfiguration : Int case unknown = -1 case twoUp = 0 case stacked ``` ## Cases ### `unknown` Represents an unsupported or unrecognized button configuration. ```swift case unknown = -1 ``` --- ### `twoUp` ```swift case twoUp = 0 ``` --- ### `stacked` ```swift case stacked ``` --- # InAppMessageCloseAction **Package:** `com.salesforce.marketingcloud.inappmessagingfeature` **Module:** In App Messaging Feature Module v1.0.0 ## Overview ```kotlin data class InAppMessageCloseAction( val actionType: InAppMessageCloseAction.InAppMessageDismissReason, val id: String? ) ``` A data class that represents how an in-app message was closed, including the dismiss reason and an optional identifier. This class is used in the `didCloseMessage` callback to inform the host application about the manner in which a message was dismissed—whether through auto-dismiss, a close control, or a button tap. ### Parameters | Parameter | Type | Description | | ------------ | --------------------------- | ------------------------------------------------------------------------------- | | `actionType` | `InAppMessageDismissReason` | The reason why the message was closed | | `id` | `String?` | Optional identifier (e.g., button ID when dismissed via BUTTON); null otherwise | --- ## Constructors ### InAppMessageCloseAction ```kotlin constructor( actionType: InAppMessageCloseAction.InAppMessageDismissReason, id: String? ) ``` Creates an instance of `InAppMessageCloseAction` with the specified dismiss reason and optional ID. --- ## Properties ### actionType ```kotlin val actionType: InAppMessageCloseAction.InAppMessageDismissReason ``` The reason the in-app message was dismissed. ### id ```kotlin val id: String? ``` Optional identifier associated with the close action. Contains a button ID when the message is closed via the BUTTON dismiss reason; null for other dismiss reasons. --- ## Nested Types ### Companion ```kotlin object Companion ``` Companion object for `InAppMessageCloseAction`. ### InAppMessageDismissReason ```kotlin enum InAppMessageDismissReason : Enum ``` An enumeration representing the possible reasons an in-app message was dismissed. **Enum Values:** - `BUTTON` - Message was dismissed by tapping a button - Additional values may exist. See the enum documentation for complete list. --- ## Usage This class is typically received in the `InAppMessageManager.EventListener.didCloseMessage` callback: ```kotlin override fun didCloseMessage(closeAction: InAppMessageCloseAction) { when (closeAction.actionType) { InAppMessageDismissReason.BUTTON -> { // Handle button tap with closeAction.id } // Handle other dismiss reasons } } ``` # InAppMessageCloseAction `Class` ## Declaration ```swift @objc(SFMCSdkInAppMessageCloseAction) public class InAppMessageCloseAction : NSObject @objc public init(dismissReason: InAppMessageDismissReason, id: String?) @objc public func getDismissReason() -> InAppMessageDismissReason @objc public func getId() -> String? ``` ## Cases ### `init(dismissReason:id:)` ```swift @objc public init(dismissReason: InAppMessageDismissReason, id: String?) ``` --- ### `getDismissReason()` ```swift @objc public func getDismissReason() -> InAppMessageDismissReason ``` --- ### `getId()` ```swift @objc public func getId() -> String? ``` --- # InAppMessageCloseButton `Protocol` ## Declaration ```swift @objc(SFMCSdkInAppMessageCloseButton) public protocol InAppMessageCloseButton var alignment: InAppMessageCloseButtonAlignment { get } var iconColor: String? { get } var backgroundColor: String? { get } var margin: InAppMessageSpacing? { get } ``` ## Cases ### `alignment` ```swift var alignment: InAppMessageCloseButtonAlignment { get } ``` --- ### `iconColor` ```swift var iconColor: String? { get } ``` --- ### `backgroundColor` ```swift var backgroundColor: String? { get } ``` --- ### `margin` ```swift var margin: InAppMessageSpacing? { get } ``` --- # InAppMessageCloseButtonAlignment `Enumeration` ## Declaration ```swift @objc(SFMCSdkInAppMessageCloseButtonAlignment) public enum InAppMessageCloseButtonAlignment : Int case unknown = -1 case end = 0 ``` ## Cases ### `unknown` Represents an unsupported or unrecognized close button alignment. ```swift case unknown = -1 ``` --- ### `end` ```swift case end = 0 ``` --- # InAppMessageDetails `Protocol` ## Declaration ```swift @objc(SFMCSdkInAppMessageDetails) public protocol InAppMessageDetails var id: String { get } var type: InAppMessageType { get } var layoutOrder: InAppMessageLayoutOrder { get } var buttonConfiguration: InAppMessageButtonConfiguration { get } var title: InAppMessageText? { get } var body: InAppMessageText? { get } var tertiaryText: InAppMessageTertiaryText? { get } var media: InAppMessageMedia? { get } var buttons: [InAppMessageButton]? { get } var closeButton: InAppMessageCloseButton? { get } var backgroundColor: String? { get } var windowColor: String? { get } var cornerRadius: InAppMessageSize { get } var shadow: InAppMessageShadow? { get } var additionalMargin: InAppMessageSpacing? { get } var border: InAppMessageBorder? { get } var animation: InAppMessageAnimation? { get } var source: String? { get } var displayCount: Int { get } var displayLimit: Int { get } var displayLimitOverride: Bool { get } var startDateUtc: Date? { get } var endDateUtc: Date? { get } var modifiedDateUtc: Date? { get } var displayDuration: Int { get } var messageDelaySec: Int { get } var priority: Int { get } var displaySuppressionAction: [String]? { get } ``` ## Cases ### `id` ```swift var id: String { get } ``` --- ### `type` ```swift var type: InAppMessageType { get } ``` --- ### `layoutOrder` ```swift var layoutOrder: InAppMessageLayoutOrder { get } ``` --- ### `buttonConfiguration` ```swift var buttonConfiguration: InAppMessageButtonConfiguration { get } ``` --- ### `title` ```swift var title: InAppMessageText? { get } ``` --- ### `body` ```swift var body: InAppMessageText? { get } ``` --- ### `tertiaryText` ```swift var tertiaryText: InAppMessageTertiaryText? { get } ``` --- ### `media` ```swift var media: InAppMessageMedia? { get } ``` --- ### `buttons` ```swift var buttons: [InAppMessageButton]? { get } ``` --- ### `closeButton` ```swift var closeButton: InAppMessageCloseButton? { get } ``` --- ### `backgroundColor` ```swift var backgroundColor: String? { get } ``` --- ### `windowColor` ```swift var windowColor: String? { get } ``` --- ### `cornerRadius` ```swift var cornerRadius: InAppMessageSize { get } ``` --- ### `shadow` ```swift var shadow: InAppMessageShadow? { get } ``` --- ### `additionalMargin` ```swift var additionalMargin: InAppMessageSpacing? { get } ``` --- ### `border` ```swift var border: InAppMessageBorder? { get } ``` --- ### `animation` ```swift var animation: InAppMessageAnimation? { get } ``` --- ### `source` The SDK module that originated this in-app message. See ModuleName for possible values. ```swift var source: String? { get } ``` --- ### `displayCount` ```swift var displayCount: Int { get } ``` --- ### `displayLimit` ```swift var displayLimit: Int { get } ``` --- ### `displayLimitOverride` ```swift var displayLimitOverride: Bool { get } ``` --- ### `startDateUtc` ```swift var startDateUtc: Date? { get } ``` --- ### `endDateUtc` ```swift var endDateUtc: Date? { get } ``` --- ### `modifiedDateUtc` ```swift var modifiedDateUtc: Date? { get } ``` --- ### `displayDuration` ```swift var displayDuration: Int { get } ``` --- ### `messageDelaySec` ```swift var messageDelaySec: Int { get } ``` --- ### `priority` ```swift var priority: Int { get } ``` --- ### `displaySuppressionAction` ```swift var displaySuppressionAction: [String]? { get } ``` --- # InAppMessageDismissReason **Package:** `com.salesforce.marketingcloud.inappmessagingfeature` **Module:** In App Messaging Feature Module v1.0.0 ## Overview An enumeration representing the reason an In-App Message was dismissed. ```kotlin enum InAppMessageDismissReason : Enum ``` ## Enum Values ### AUTO ```kotlin AUTO ``` The message was automatically dismissed, such as after a timeout period. ### BUTTON ```kotlin BUTTON ``` The user dismissed the message by tapping a button within the message. ### CLOSED ```kotlin CLOSED ``` The user explicitly closed the message using a close control. ### UNKNOWN ```kotlin UNKNOWN ``` The dismiss reason could not be determined. ## Properties ### entries ```kotlin val entries: EnumEntries ``` An immutable list representation of all enum entries in declaration order. ### value ```kotlin val value: Int ``` Integer value used for analytics tracking or serialization purposes. ## Methods ### valueOf ```kotlin fun valueOf(value: String): InAppMessageCloseAction.InAppMessageDismissReason ``` Returns the enum constant matching the specified name string. The string must exactly match an enum constant identifier (no extra whitespace allowed). **Parameters:** - `value` - The name of the enum constant to retrieve **Returns:** The matching enum constant ### values ```kotlin fun values(): Array ``` Returns an array of all enum constants in declaration order. **Returns:** Array containing all enum constants # InAppMessageDismissReason `Enumeration` ## Declaration ```swift @objc(SFMCSdkInAppMessageDismissReason) public enum InAppMessageDismissReason : Int case auto = 1 case button = 2 case closed = 3 ``` ## Cases ### `auto` Auto dismiss reason ```swift case auto = 1 ``` --- ### `button` Button dismiss reason ```swift case button = 2 ``` --- ### `closed` Closed dismiss reason ```swift case closed = 3 ``` --- # InAppMessageEventDelegate `Protocol` ## Declaration ```swift @objc(SFMCSdkInAppMessageEventDelegate) public protocol InAppMessageEventDelegate @objc optional func shouldShow(inAppMessage message: InAppMessageDetails) -> Bool @objc optional func didShow(inAppMessage message: InAppMessageDetails) @objc optional func didClose(inAppMessage message: InAppMessageDetails, action: InAppMessageCloseAction) ``` ## Cases ### `shouldShow(inAppMessage:)` ```swift @objc optional func shouldShow(inAppMessage message: InAppMessageDetails) -> Bool ``` --- ### `didShow(inAppMessage:)` ```swift @objc optional func didShow(inAppMessage message: InAppMessageDetails) ``` --- ### `didClose(inAppMessage:action:)` ```swift @objc optional func didClose(inAppMessage message: InAppMessageDetails, action: InAppMessageCloseAction) ``` --- # InAppMessageImageContentMode `Enumeration` ## Declaration ```swift @objc(SFMCSdkInAppMessageImageContentMode) public enum InAppMessageImageContentMode : Int case unknown = -1 case fit = 0 case fill ``` ## Cases ### `unknown` Represents an unsupported or unrecognized image content mode. ```swift case unknown = -1 ``` --- ### `fit` ```swift case fit = 0 ``` --- ### `fill` ```swift case fill ``` --- # InAppMessageImageSize `Enumeration` ## Declaration ```swift @objc(SFMCSdkInAppMessageImageSize) public enum InAppMessageImageSize : Int case unknown = -1 case e2e = 0 case inset ``` ## Cases ### `unknown` Represents an unsupported or unrecognized image size. ```swift case unknown = -1 ``` --- ### `e2e` ```swift case e2e = 0 ``` --- ### `inset` ```swift case inset ``` --- # InAppMessageLayoutOrder `Enumeration` ## Declaration ```swift @objc(SFMCSdkInAppMessageLayoutOrder) public enum InAppMessageLayoutOrder : Int case unknown = -1 case titleImageBody = 0 case imageTitleBody ``` ## Cases ### `unknown` Represents an unsupported or unrecognized layout order. ```swift case unknown = -1 ``` --- ### `titleImageBody` ```swift case titleImageBody = 0 ``` --- ### `imageTitleBody` ```swift case imageTitleBody ``` --- # InAppMessageManager **Package:** `com.salesforce.marketingcloud.inappmessagingfeature` **Module:** In App Messaging Feature Module v1.0.0 ## Overview Public interface for managing In-App Messages. This interface provides methods for displaying messages, configuring appearance, and listening to message lifecycle events. ## Nested Types ### EventListener ```kotlin interface EventListener ``` When an object of this type is registered with the InAppMessageManager, its methods will be called to signal certain in app message events. ## Methods ### setInAppMessageListener ```kotlin abstract fun setInAppMessageListener(listener: InAppMessageManager.EventListener?) ``` Set a EventListener that will be called during In App Message life cycle events. **Parameters:** | Name | Type | Description | | -------- | ------------------------------------ | ------------------------------ | | listener | `InAppMessageManager.EventListener?` | The event listener to register | --- ### setStatusBarColor ```kotlin abstract fun setStatusBarColor(@ColorInt color: Int) ``` Set the color of the In App Message Activity status bar on Android 21 or higher. **Parameters:** | Name | Type | Description | | ----- | --------------- | ---------------------------------- | | color | `@ColorInt Int` | The color value for the status bar | --- ### setTypeface ```kotlin abstract fun setTypeface(typeface: Typeface?) ``` Set the font Typeface to be used for In app Messages. **Parameters:** | Name | Type | Description | | -------- | ----------- | ------------------------------------------------ | | typeface | `Typeface?` | The Android Typeface to apply to in-app messages | --- ### showMessage ```kotlin abstract fun showMessage(messageId: String) ``` Will display the InAppMessage with the matching id as long as certain conditions are met. **Parameters:** | Name | Type | Description | | --------- | -------- | -------------------------------- | | messageId | `String` | The ID of the message to display | # InAppMessageMedia `Protocol` ## Declaration ```swift @objc(SFMCSdkInAppMessageMedia) public protocol InAppMessageMedia var url: String? { get } var altText: String? { get } var size: InAppMessageImageSize { get } var cornerRadius: InAppMessageSize { get } var altMedia: String? { get } var insetSize: InAppMessageSize { get } var border: InAppMessageBorder? { get } var shadow: InAppMessageShadow? { get } var margin: InAppMessageSpacing? { get } var additionalMargin: InAppMessageSpacing? { get } var aspectRatio: String? { get } var contentMode: InAppMessageImageContentMode { get } ``` ## Cases ### `url` ```swift var url: String? { get } ``` --- ### `altText` ```swift var altText: String? { get } ``` --- ### `size` ```swift var size: InAppMessageImageSize { get } ``` --- ### `cornerRadius` ```swift var cornerRadius: InAppMessageSize { get } ``` --- ### `altMedia` ```swift var altMedia: String? { get } ``` --- ### `insetSize` ```swift var insetSize: InAppMessageSize { get } ``` --- ### `border` ```swift var border: InAppMessageBorder? { get } ``` --- ### `shadow` ```swift var shadow: InAppMessageShadow? { get } ``` --- ### `margin` ```swift var margin: InAppMessageSpacing? { get } ``` --- ### `additionalMargin` ```swift var additionalMargin: InAppMessageSpacing? { get } ``` --- ### `aspectRatio` ```swift var aspectRatio: String? { get } ``` --- ### `contentMode` ```swift var contentMode: InAppMessageImageContentMode { get } ``` --- # InAppMessageShadow `Protocol` ## Declaration ```swift @objc(SFMCSdkInAppMessageShadow) public protocol InAppMessageShadow var length: InAppMessageSize { get } var color: String? { get } ``` ## Cases ### `length` ```swift var length: InAppMessageSize { get } ``` --- ### `color` ```swift var color: String? { get } ``` --- # InAppMessageSize `Enumeration` ## Declaration ```swift @objc(SFMCSdkInAppMessageSize) public enum InAppMessageSize : Int case unknown = -1 case xSmall = 0 case small case medium case large case xLarge case xxLarge ``` ## Cases ### `unknown` Represents an unsupported or unrecognized size. ```swift case unknown = -1 ``` --- ### `xSmall` ```swift case xSmall = 0 ``` --- ### `small` ```swift case small ``` --- ### `medium` ```swift case medium ``` --- ### `large` ```swift case large ``` --- ### `xLarge` ```swift case xLarge ``` --- ### `xxLarge` ```swift case xxLarge ``` --- # InAppMessageSpacing `Protocol` ## Declaration ```swift @objc(SFMCSdkInAppMessageSpacing) public protocol InAppMessageSpacing var top: InAppMessageSize { get } var bottom: InAppMessageSize { get } var left: InAppMessageSize { get } var right: InAppMessageSize { get } ``` ## Cases ### `top` ```swift var top: InAppMessageSize { get } ``` --- ### `bottom` ```swift var bottom: InAppMessageSize { get } ``` --- ### `left` ```swift var left: InAppMessageSize { get } ``` --- ### `right` ```swift var right: InAppMessageSize { get } ``` --- # InAppMessageTertiaryText `Protocol` ## Declaration ```swift @objc(SFMCSdkInAppMessageTertiaryText) public protocol InAppMessageTertiaryText var text: String? { get } var alignment: InAppMessageAlignment { get } var fontFamily: String? { get } var fontSize: InAppMessageSize { get } var fontStyle: String? { get } var fontColor: String? { get } var margin: InAppMessageSpacing? { get } var additionalMargin: InAppMessageSpacing? { get } var hyperlinks: [String]? { get } var linkColor: String? { get } ``` ## Cases ### `text` ```swift var text: String? { get } ``` --- ### `alignment` ```swift var alignment: InAppMessageAlignment { get } ``` --- ### `fontFamily` ```swift var fontFamily: String? { get } ``` --- ### `fontSize` ```swift var fontSize: InAppMessageSize { get } ``` --- ### `fontStyle` ```swift var fontStyle: String? { get } ``` --- ### `fontColor` ```swift var fontColor: String? { get } ``` --- ### `margin` ```swift var margin: InAppMessageSpacing? { get } ``` --- ### `additionalMargin` ```swift var additionalMargin: InAppMessageSpacing? { get } ``` --- ### `hyperlinks` ```swift var hyperlinks: [String]? { get } ``` --- ### `linkColor` ```swift var linkColor: String? { get } ``` --- # InAppMessageText `Protocol` ## Declaration ```swift @objc(SFMCSdkInAppMessageText) public protocol InAppMessageText var text: String? { get } var alignment: InAppMessageAlignment { get } var fontFamily: String? { get } var fontSize: InAppMessageSize { get } var fontStyle: String? { get } var fontColor: String? { get } var margin: InAppMessageSpacing? { get } var additionalMargin: InAppMessageSpacing? { get } ``` ## Cases ### `text` ```swift var text: String? { get } ``` --- ### `alignment` ```swift var alignment: InAppMessageAlignment { get } ``` --- ### `fontFamily` ```swift var fontFamily: String? { get } ``` --- ### `fontSize` ```swift var fontSize: InAppMessageSize { get } ``` --- ### `fontStyle` ```swift var fontStyle: String? { get } ``` --- ### `fontColor` ```swift var fontColor: String? { get } ``` --- ### `margin` ```swift var margin: InAppMessageSpacing? { get } ``` --- ### `additionalMargin` ```swift var additionalMargin: InAppMessageSpacing? { get } ``` --- # InAppMessageType `Enumeration` ## Declaration ```swift @objc(SFMCSdkInAppMessageType) public enum InAppMessageType : Int case unknown = -1 case bannerTop = 0 case bannerBottom case fullImageFill case full case modal case pushPrimer ``` ## Cases ### `unknown` Represents an unsupported or unrecognized message type. ```swift case unknown = -1 ``` --- ### `bannerTop` ```swift case bannerTop = 0 ``` --- ### `bannerBottom` ```swift case bannerBottom ``` --- ### `fullImageFill` ```swift case fullImageFill ``` --- ### `full` ```swift case full ``` --- ### `modal` ```swift case modal ``` --- ### `pushPrimer` ```swift case pushPrimer ``` --- # InAppMessagingFeature **Package:** `com.salesforce.marketingcloud.inappmessagingfeature` **Module:** In App Messaging Feature Module v1.0.0 **SDK:** Salesforce Marketing Cloud Unified SDK 11.0.0 ## Overview ```kotlin class InAppMessagingFeature : ModuleInterface ``` The InAppMessagingFeature class provides comprehensive functionality for managing in-app messages and related features within the Salesforce Marketing Cloud SDK. **Since:** 1.0.0 ### Key Features - Displaying in-app messages triggered by marketing campaigns - Controlling message display with an event listener - Customizing message appearance with typeface and status bar color - Programmatically showing previously blocked messages ### Thread Safety This class is thread-safe and uses atomic operations for state management. All public methods can be called from any thread. ## Example Usage ```kotlin // Access the InAppMessagingFeature asynchronously InAppMessagingFeature.requestSdk { inAppMessagingFeature -> val manager = inAppMessagingFeature.getInAppMessageManager() // Set a listener to control message display manager.setInAppMessageListener(object : InAppMessageManager.EventListener { override fun shouldShowMessage(message: InAppMessage): Boolean { // Return true to display the message, false to suppress it return true } override fun didShowMessage(message: InAppMessage) { // Called when the message is displayed on screen } override fun didCloseMessage(message: InAppMessage, action: InAppMessageCloseAction) { // Called when the message is dismissed } }) } ``` ## Members ### Types #### Companion ```kotlin object Companion ``` ### Properties #### state ```kotlin open override val state: JSONObject ``` Returns the current state of the InAppMessagingFeature module as a JSONObject. ## Functions ### getConfig ```kotlin fun getConfig(): InAppMessagingFeatureConfig ``` Gets the configuration used to initialize this InAppMessagingFeature instance. **Returns:** `InAppMessagingFeatureConfig` --- ### getInAppMessageManager ```kotlin fun getInAppMessageManager(): InAppMessageManager ``` Gets the In-App Message Manager for managing in-app messages. **Returns:** `InAppMessageManager` --- ### getInitializationStatus ```kotlin fun getInitializationStatus(): InAppMessagingFeatureInitializationStatus? ``` Gets the initialization status of this InAppMessagingFeature instance. **Returns:** `InAppMessagingFeatureInitializationStatus?` --- ### isTornDown ```kotlin fun isTornDown(): Boolean ``` Checks if the InAppMessagingFeature instance is torn down. **Returns:** `Boolean` ## See Also - InAppMessagingFeatureConfig --- **Target:** androidJvm # InAppMessagingFeature `Class` This class is a Swift Interface for SFInAppMessagingFeature ## Declaration ```swift @objc(SFInAppMessagingFeature) public final class InAppMessagingFeature : NSObject, SFMCModule @objc public static func requestSdk(_ callback: @escaping (_ inappMessagingFeature: InAppMessagingFeatureApi?) -> Void) public func setEventDelegate(_ delegate: InAppMessageEventDelegate?) public func showInAppMessage(messageId: String) public func setInAppMessageFont(name: String?) -> Bool public func setURLHandlingDelegate(_ delegate: URLHandlingDelegate) ``` ## Request SDK Method ### `requestSdk(_:)` Requests the InAppMessaging Feature Module when it’s operational and safe to use. The provided callback will be invoked with the InAppMessaging Feature Module when it’s ready. All InAppMessaging feature module-related API calls should be made within this function. ```swift @objc public static func requestSdk(_ callback: @escaping (_ inappMessagingFeature: InAppMessagingFeatureApi?) -> Void) ``` --- ## InAppMessaging Methods ### `setEventDelegate(_:)` Sets the delegate responsible for receiving in-app message display lifecycle and user interactions. Use this method to provide an `InAppMessageEventDelegate` implementation to observe events such as message display, dismissal, or user interaction. Passing `nil` removes the currently assigned delegate. ```swift public func setEventDelegate(_ delegate: InAppMessageEventDelegate?) ``` --- ### `showInAppMessage(messageId:)` Displays a specific in-app message by its identifier. Use this method to manually trigger the presentation of an in-app message that corresponds to the provided `messageId` . ```swift public func showInAppMessage(messageId: String) ``` --- ### `setInAppMessageFont(name:)` Sets the custom font used for rendering in-app messages. Use this method to configure a global font by name that will be applied to in-app message content. Passing `nil` resets the font to the default. ```swift public func setInAppMessageFont(name: String?) -> Bool ``` **Returns:** `true` if the font was successfully set; otherwise `false` . --- ### `setURLHandlingDelegate(_:)` Sets the delegate responsible for handling URL interactions triggered by in-app messages. Use this method to provide a custom `URLHandlingDelegate` implementation to control how URLs (e.g., deep links or external links) are processed when a user interacts with an in-app message button action. ```swift public func setURLHandlingDelegate(_ delegate: URLHandlingDelegate) ``` --- # InAppMessagingFeatureConfig **Package:** `com.salesforce.marketingcloud.inappmessagingfeature.config` **Module:** In App Messaging Feature Module v1.0.0 ## Overview ```kotlin class InAppMessagingFeatureConfig : InAppMessagingFeatureModuleConfig ``` Configuration class for the In App Messaging Feature of the Salesforce Marketing Cloud SDK. ## Usage Examples ### Kotlin DSL ```kotlin val config = InAppMessagingFeatureConfig { eventListener = myEventListener urlHandler = myUrlHandler typeface = Typeface.DEFAULT_BOLD statusBarColor = 0xFFFF8040.toInt() } ``` ### Builder Pattern (Java-friendly) ```kotlin val config = InAppMessagingFeatureConfig.builder() .setEventListener(myEventListener) .setUrlHandler(myUrlHandler) .setTypeface(Typeface.DEFAULT_BOLD) .setStatusBarColor(0xFFFF8040.toInt()) .build() ``` ## Properties | Property | Type | Annotations | Description | | ---------------- | ------------------------------------ | ------------------------ | --------------------------------------------------------------------- | | `eventListener` | `InAppMessageManager.EventListener?` | `@JvmField` | Optional event listener for in-app message lifecycle callbacks | | `urlHandler` | `UrlHandler?` | `@JvmField` | Optional URL handler for customizing how URLs in messages are handled | | `typeface` | `Typeface?` | `@JvmField` | Optional typeface for in-app message text | | `statusBarColor` | `Int?` | `@ColorInt`, `@JvmField` | Optional status bar color for in-app messages | ## Methods ### equals ```kotlin open operator override fun equals(other: Any?): Boolean ``` Standard equality comparison. ### hashCode ```kotlin open override fun hashCode(): Int ``` Returns hash code for the configuration object. ### toBuilder ```kotlin fun toBuilder(): InAppMessagingFeatureConfig.Builder ``` Creates a new Builder with the current configuration values. ## Nested Types ### Builder ```kotlin class Builder ``` Builder class for constructing `InAppMessagingFeatureConfig` instances. ### Companion ```kotlin object Companion ``` Companion object for the configuration class. ## See Also - `InAppMessagingFeature` - `InAppMessageManager.EventListener` - `UrlHandler` # InAppMessagingFeatureConfigBuilder `Class` InAppMessagingFeatureConfigBuilder class ## Declaration ```swift @objc(SFInAppMessagingFeatureConfigBuilder) public class InAppMessagingFeatureConfigBuilder : NSObject @discardableResult @objc public func setNotificationAuthorizationOptions(_ options: UNAuthorizationOptions) -> InAppMessagingFeatureConfigBuilder @discardableResult @objc public func setEventDelegate(_ delegate: InAppMessageEventDelegate) -> InAppMessagingFeatureConfigBuilder @discardableResult @objc public func setURLHandlingDelegate(_ delegate: URLHandlingDelegate) -> InAppMessagingFeatureConfigBuilder @discardableResult @objc public func setInAppMessageFont(name: String) -> InAppMessagingFeatureConfigBuilder @discardableResult @objc public func build() -> InAppMessagingFeatureConfig ``` ## Cases ### `setNotificationAuthorizationOptions(_:)` Sets the notification authorization options used when requesting permission (e.g. for Push Primer). Default is `[.alert, .sound, .badge]` when not set. ```swift @discardableResult @objc public func setNotificationAuthorizationOptions(_ options: UNAuthorizationOptions) -> InAppMessagingFeatureConfigBuilder ``` **Returns:** The `InAppMessagingFeatureConfigBuilder` instance for method chaining. --- ### `setEventDelegate(_:)` Sets the delegate that receives in-app message display and close events. ```swift @discardableResult @objc public func setEventDelegate(_ delegate: InAppMessageEventDelegate) -> InAppMessagingFeatureConfigBuilder ``` **Returns:** The `InAppMessagingFeatureConfigBuilder` instance for method chaining. --- ### `setURLHandlingDelegate(_:)` Sets the delegate that handles URLs opened from in-app message button actions. ```swift @discardableResult @objc public func setURLHandlingDelegate(_ delegate: URLHandlingDelegate) -> InAppMessagingFeatureConfigBuilder ``` **Returns:** The `InAppMessagingFeatureConfigBuilder` instance for method chaining. --- ### `setInAppMessageFont(name:)` Sets the font used when rendering in-app messages. ```swift @discardableResult @objc public func setInAppMessageFont(name: String) -> InAppMessagingFeatureConfigBuilder ``` **Returns:** The `InAppMessagingFeatureConfigBuilder` instance for method chaining. --- ### `build()` Builds an `InAppMessagingFeatureConfig` with the current builder values. Pass the result to the SDK config when initializing the In App Messaging feature. ```swift @discardableResult @objc public func build() -> InAppMessagingFeatureConfig ``` **Returns:** An `InAppMessagingFeatureConfig` instance with the current builder settings. --- # InAppMessagingFeatureInitializationStatus **Package:** `com.salesforce.marketingcloud.inappmessagingfeature` **Module:** In App Messaging Feature Module v1.0.0 **SDK:** Salesforce Marketing Cloud Unified SDK 11.0.0 ## Overview ```kotlin class InAppMessagingFeatureInitializationStatus ``` A class that represents initialization status for the InAppMessagingFeature module. This follows the same design pattern used by the main SDK's InitializationStatus. ## Nested Types ### Status ```kotlin enum Status : Enum ``` An enumeration representing the overall result of InAppMessagingFeature module initialization. **Values:** - `SUCCESS` - Initialization completed successfully - `COMPLETED_WITH_DEGRADED_FUNCTIONALITY` - Initialization finished but with reduced capabilities ## Properties ### status ```kotlin val status: InAppMessagingFeatureInitializationStatus.Status ``` The initialization status of the InAppMessagingFeature. --- ### isUsable ```kotlin val isUsable: Boolean ``` A boolean indicating whether the module initialized sufficiently to be functional. Returns `true` when status is either `SUCCESS` or `COMPLETED_WITH_DEGRADED_FUNCTIONALITY`. --- ### initializedComponents ```kotlin val initializedComponents: List ``` A list containing names of components that were successfully initialized. Useful for debugging module initialization problems. --- ### unrecoverableException ```kotlin val unrecoverableException: Throwable? ``` Contains any unrecoverable exception encountered during initialization. Will be `null` if no such exception occurred. ## Related Classes - [InAppMessagingFeature](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagingfeature_InAppMessagingFeature.md) - The main feature class this status relates to # Inbox Messages Inbox messaging enables you to deliver persistent messages to users within your mobile app. Unlike push notifications that disappear after being dismissed, inbox messages remain available for users to view at any time, creating a dedicated space for important communications, promotions, and updates. The Marketing Cloud SDK provides comprehensive support for three types of inbox messages: - **Inbox 1.0** - The original inbox message format with CloudPage URLs - **Inbox 2.0** - Enhanced inbox messages with additional fields like subtitles and messages, plus new call-to-action options including App URL, Web URL, and None - **Push Copy to Inbox (PCTI)** - Push notifications that also appear in the inbox, ensuring users can access the message even if they miss the initial notification ## Key Features The SDK provides convenience methods for managing inbox messages, including: - Retrieving all messages, unread messages, read messages, and deleted messages - Marking messages as read or deleted - Refreshing the inbox to fetch new messages - Sorting messages by sent date - Accessing message properties like subject, dates, custom data, and media For Alert + Inbox messages, you can configure the SDK to automatically mark inbox messages as read when users tap on the corresponding push notification, creating a seamless experience across notification and inbox channels. # Inbox Messaging in Android Apps that Use SDK Version 10 The steps for implementing inbox messaging have been updated in version 10 of the SDK. To upgrade your app to version 10 of the SDK, first [update the initialization code](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v10.md) -->. Then, use this code example to update the inbox messaging code in your app. ```kotlin SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { engagementModuleConfig = MarketingCloudConfig.builder().apply { // Other configuration values setInboxEnabled(true) // Enable Inbox messaging, default = false }.build(applicationContext) }) { // TODO handle initialization status } ``` # InboxMessage **Package:** `com.salesforce.marketingcloud.messages.inbox` **Type:** Data Class (Kotlin) **SDK Version:** 11.0.0 ## Description The `InboxMessage` class is a data class from the Salesforce Marketing Cloud Unified SDK that represents an inbox message within the marketing cloud messaging system. It encapsulates all the properties and metadata associated with messages stored in the Marketing Cloud inbox. ## Class Declaration ```kotlin data class InboxMessage( val id: String, requestId: String? = null, messageHash: String? = null, val subject: String? = null, val title: String? = null, val alert: String? = null, val sound: String? = null, val media: InboxMessage.Media? = null, val startDateUtc: Date? = null, val endDateUtc: Date? = null, val sendDateUtc: Date? = null, val url: String?, val custom: String? = null, val customKeys: Map? = null, val subtitle: String? = null, val inboxMessage: String? = null, val inboxSubtitle: String? = null, var notificationMessage: NotificationMessage? = null, viewCount: Int = 0, val messageType: Int?, var deleted: Boolean = false ) ``` ## Constructor ### Primary Constructor The class has a single primary constructor with the following parameters: | Parameter | Type | Default | Description | | --------------------- | ---------------------- | -------- | --------------------------------- | | `id` | `String` | Required | Unique identifier for the message | | `requestId` | `String?` | `null` | Optional request identifier | | `messageHash` | `String?` | `null` | Optional message hash | | `subject` | `String?` | `null` | Message subject | | `title` | `String?` | `null` | Message title | | `alert` | `String?` | `null` | Alert text | | `sound` | `String?` | `null` | Sound identifier | | `media` | `InboxMessage.Media?` | `null` | Associated media content | | `startDateUtc` | `Date?` | `null` | Message start date (UTC) | | `endDateUtc` | `Date?` | `null` | Message end date (UTC) | | `sendDateUtc` | `Date?` | `null` | Message send date (UTC) | | `url` | `String?` | Required | Associated URL | | `custom` | `String?` | `null` | Custom data string | | `customKeys` | `Map?` | `null` | Custom key-value pairs | | `subtitle` | `String?` | `null` | Message subtitle | | `inboxMessage` | `String?` | `null` | Inbox-specific message content | | `inboxSubtitle` | `String?` | `null` | Inbox-specific subtitle | | `notificationMessage` | `NotificationMessage?` | `null` | Associated notification message | | `viewCount` | `Int` | `0` | Number of times viewed | | `messageType` | `Int?` | Required | Type identifier for the message | | `deleted` | `Boolean` | `false` | Deletion status flag | ## Properties All properties are annotated with `@JvmField` for Java interoperability. ### Immutable Properties (val) #### `id: String` Unique message identifier. #### `subject: String?` Message subject text. #### `title: String?` Message title. #### `alert: String?` Alert text for the message. #### `sound: String?` Sound identifier associated with the message. #### `media: InboxMessage.Media?` Media content associated with the message. #### `startDateUtc: Date?` Message start date in UTC. #### `endDateUtc: Date?` Message end date in UTC. #### `sendDateUtc: Date?` Message send date in UTC. #### `url: String?` Associated URL for the message. #### `custom: String?` Custom data string. #### `customKeys: Map?` Custom key-value pairs for additional metadata. #### `subtitle: String?` Message subtitle. #### `inboxMessage: String?` Inbox-specific message content. #### `inboxSubtitle: String?` Inbox-specific subtitle. #### `messageType: Int?` Type identifier for the message. ### Mutable Properties (var) #### `notificationMessage: NotificationMessage?` Associated notification message object. #### `deleted: Boolean` Deletion status flag (default: `false`). #### `read: Boolean` Read status of the message (derived property). ## Methods As a Kotlin data class, `InboxMessage` automatically provides the following methods: ### `copy()` Creates a copy of the message with optionally modified properties. ```kotlin fun copy( id: String = this.id, requestId: String? = this.requestId, messageHash: String? = this.messageHash, // ... all other parameters ): InboxMessage ``` ### `equals(other: Any?): Boolean` Compares this message with another object for equality. ### `hashCode(): Int` Generates a hash code for the message. ### `toString(): String` Returns a string representation of the message. ### Component Functions Component functions for destructuring declarations (e.g., `component1()`, `component2()`, etc.). ## Nested Types ### InboxMessageType ```kotlin enum InboxMessageType : Enum ``` Represents the type of an inbox message. ### Media ```kotlin data class Media ``` Represents media content associated with an inbox message. ## Related Classes - **`NotificationMessage`** (`com.salesforce.marketingcloud.notifications`) - Associated notification message type ## See Also - [Marketing Cloud Android SDK Documentation](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/) - [Inbox Messaging Guide](https://developer.salesforce.com/docs/marketing/marketing-cloud/guide/inbox-messages.html) # InboxMessageManager **Package:** `com.salesforce.marketingcloud.messages.inbox` **SDK Version:** 11.0.0 ## Overview The `InboxMessageManager` interface provides functionality for managing inbox messages in the Salesforce Marketing Cloud SDK. --- ## Nested Types ### InboxRefreshListener ```kotlin interface InboxRefreshListener ``` Listener interface for inbox refresh operations. ### InboxResponseListener ```kotlin interface InboxResponseListener ``` Listener interface for inbox response events. --- ## Methods ### deleteMessage ```kotlin abstract fun deleteMessage(message: InboxMessage) abstract fun deleteMessage(messageId: String) ``` Marks an `InboxMessage` as deleted in local storage. **Parameters:** - `message` - The InboxMessage to delete - `messageId` - The ID of the message to delete --- ### disableInbox ```kotlin abstract fun disableInbox() ``` This method provides the capability to disable the InboxMessage feature on the current device using the SDK. --- ### enableInbox ```kotlin abstract fun enableInbox() ``` Enables the InboxMessage feature on the current device. --- ### getDeletedMessageCount ```kotlin abstract fun getDeletedMessageCount(): Int ``` Get the number of deleted Inbox Messages regardless of their read status. **Returns:** Count of deleted messages --- ### getDeletedMessages ```kotlin abstract fun getDeletedMessages(): List ``` Gets a `List` of Active, Deleted Inbox Messages for use with your own adapter. **Returns:** List of deleted InboxMessage objects --- ### getMessageCount ```kotlin abstract fun getMessageCount(): Int ``` Gets the total message count. **Returns:** Total message count --- ### getMessages ```kotlin abstract fun getMessages(): List ``` Gets a `List` of Active, Read & Unread, not Deleted Inbox Messages for use with your own adapter. **Returns:** List of active InboxMessage objects --- ### getReadMessageCount ```kotlin abstract fun getReadMessageCount(): Int ``` Get the number of read, not deleted Inbox Messages. **Returns:** Count of read messages --- ### getReadMessages ```kotlin abstract fun getReadMessages(): List ``` Gets a `List` of Active, Read, not Deleted Inbox Messages for use with your own adapter. **Returns:** List of read InboxMessage objects --- ### getUnreadMessageCount ```kotlin abstract fun getUnreadMessageCount(): Int ``` Get the number of unread, not deleted Inbox Messages. **Returns:** Count of unread messages --- ### getUnreadMessages ```kotlin abstract fun getUnreadMessages(): List ``` Gets a `List` of Active, Unread, not Deleted Inbox Messages for use with your own adapter. **Returns:** List of unread InboxMessage objects --- ### isInboxEnabled ```kotlin abstract fun isInboxEnabled(): Boolean ``` Checks if the inbox feature is enabled. **Returns:** Boolean indicating if inbox is enabled --- ### markAllMessagesDeleted ```kotlin abstract fun markAllMessagesDeleted() ``` Marks all active `InboxMessages` as deleted. --- ### markAllMessagesRead ```kotlin abstract fun markAllMessagesRead() ``` Marks all active, unread `InboxMessages` as read. --- ### refreshInbox ```kotlin abstract fun refreshInbox(listener: InboxRefreshListener?) ``` Requests an updated list of Inbox Messages from the Marketing Cloud Servers. **Parameters:** - `listener` - Optional listener for refresh completion --- ### registerInboxResponseListener ```kotlin abstract fun registerInboxResponseListener(listener: InboxResponseListener) ``` Call this method to be notified of Inbox events within the Marketing Cloud SDK. **Parameters:** - `listener` - The InboxResponseListener to register --- ### setMessageRead ```kotlin abstract fun setMessageRead(message: InboxMessage) abstract fun setMessageRead(messageId: String) ``` Marks an `InboxMessage` as read in local storage. **Parameters:** - `message` - The InboxMessage to mark as read - `messageId` - The ID of the message to mark as read --- ### unregisterInboxResponseListener ```kotlin abstract fun unregisterInboxResponseListener(listener: InboxResponseListener) ``` Unregister your `InboxResponseListener` listener. **Parameters:** - `listener` - The InboxResponseListener to unregister # InitializationListener ## Package `com.salesforce.marketingcloud.pushfeature` ## Module Information - **Module**: Push Feature Module - **Version**: 2.0.0 - **SDK Version**: 11.0.0 - **Platform**: Android JVM ## Description A functional interface that listens for the completion of PushFeature initialization. This interface provides a callback mechanism to be notified when the PushFeature module has finished its initialization process. ## Interface Declaration ```kotlin fun interface InitializationListener ``` ## Type Functional Interface (Kotlin) As a functional interface, `InitializationListener` can be implemented using lambda expressions, making it convenient for single-method callbacks. ## Methods ### complete ```kotlin abstract fun complete(status: PushFeatureInitializationStatus) ``` Called when PushFeature initialization is complete. **Parameters:** - `status` - `PushFeatureInitializationStatus` - The initialization status result indicating whether initialization succeeded or failed **Returns:** - `void` (Unit in Kotlin) ## Usage Example Since this is a functional interface, it can be implemented using a lambda: ```kotlin val listener = InitializationListener { status -> // Handle initialization completion when (status) { // Handle different status cases } } ``` Or as a traditional interface implementation: ```kotlin val listener = object : InitializationListener { override fun complete(status: PushFeatureInitializationStatus) { // Handle initialization completion } } ``` ## Related Types - `PushFeatureInitializationStatus` - Represents the result of the initialization process ## Source [View on GitHub Pages](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature/-initialization-listener/index.html) # InitializationState **Package:** `com.salesforce.marketingcloud.sfmcsdk` **Version:** 11.0.0 **Platform:** androidJvm ## Description The `InitializationState` enum represents the current initialization state of the Salesforce Marketing Cloud (SFMC) SDK. This enum allows developers to track and respond to different phases of the SDK's initialization lifecycle. ## Enum Values ### NONE SDK has not started initialization. ### INITIALIZING SDK is currently in the process of initializing. ### READY SDK has completed initialization successfully and is ready for use. ### ERROR SDK initialization failed due to an error. ## Properties ### entries Returns an immutable list representation of all enum entries in declaration order. ```kotlin val entries: EnumEntries ``` ## Methods ### valueOf Returns the enum constant matching the specified name. The string must exactly match an enum constant identifier (no whitespace allowed). ```kotlin fun valueOf(value: String): InitializationState ``` **Parameters:** - `value` - String name of the enum constant **Returns:** - `InitializationState` - The enum constant with the specified name ### values Returns an array of all enum constants in declaration order. ```kotlin fun values(): Array ``` **Returns:** - `Array` - Array containing all enum constants ## Usage Example ```kotlin // Check SDK initialization state val state = SFMCSdk.getInitializationState() when (state) { InitializationState.NONE -> { // SDK not started } InitializationState.INITIALIZING -> { // SDK is initializing } InitializationState.READY -> { // SDK is ready to use } InitializationState.ERROR -> { // Handle initialization error } } ``` # InitializationStatus ## Package `com.salesforce.marketingcloud` ## Description A class that represents the initialization status of the MarketingCloudSdk. --- ## Nested Types ### Status ```kotlin enum Status : Enum ``` Enumeration representing the overall outcome of the SDK's initialization. **Values:** - `SUCCESS` - SDK initialized successfully - `COMPLETED_WITH_DEGRADED_FUNCTIONALITY` - SDK initialized but with reduced functionality - `FAILED` - SDK initialization failed --- ## Properties ### status ```kotlin @JvmField val status: InitializationStatus.Status ``` The initialization status of the SDK. ### isUsable ```kotlin @JvmField val isUsable: Boolean ``` Whether the SDK initialized sufficiently to be usable. Returns `true` when status is `SUCCESS` or `COMPLETED_WITH_DEGRADED_FUNCTIONALITY`. ### initializedComponents ```kotlin @JvmField val initializedComponents: List ``` List of component names that were initialized. Useful for debugging initialization issues. ### encryptionChanged ```kotlin @JvmField val encryptionChanged: Boolean ``` Whether the encryption key changed since the last `init` call. When `true`, all previously stored data has been cleared. ### storageError ```kotlin @JvmField val storageError: Boolean ``` Whether an error occurred initializing SDK storage. When `true`, the SDK cannot store information and status will be `FAILED`. ### playServicesStatus ```kotlin @JvmField val playServicesStatus: Int ``` The availability status returned by `GoogleApiAvailability`. ### playServicesMessage ```kotlin @JvmField val playServicesMessage: String? ``` The error message from `playServicesStatus`, if any. ### sslProviderEnablementError ```kotlin @JvmField val sslProviderEnablementError: Boolean ``` Whether an error occurred calling `ProviderInstaller.installIfNeeded()` to ensure required SSL providers are available. ### locationsError ```kotlin @JvmField val locationsError: Boolean ``` Whether an error occurred initializing the location manager (when geofencing or proximity are enabled). ### messagingPermissionError ```kotlin @JvmField val messagingPermissionError: Boolean ``` Whether region messaging couldn't be enabled due to missing `ACCESS_FINE_LOCATION` or `ACCESS_BACKGROUND_LOCATION` permissions. ### proximityError ```kotlin @JvmField val proximityError: Boolean ``` Whether an error occurred initializing the proximity manager. Check `getSdkState()` for details. ### unrecoverableException ```kotlin @JvmField val unrecoverableException: Throwable? ``` Any unrecoverable exception encountered during initialization. --- ## Version 11.0.0 # InitializationStatus **Package:** `com.salesforce.marketingcloud.sfmcsdk` **SDK Version:** 11.0.0 **Platform:** androidJvm --- ## Overview An interface representing the initialization status of the SDK. ## Description The init status interface. --- ## Inheritors - `SFMCSdkInitializationStatus` --- ## Members ### Types #### Companion ```kotlin object Companion ``` --- ### Properties #### status ```kotlin abstract val status: Int ``` The status of the SDK's initialization result. # Initialize the SDK Initialize the SDK during the execution of the `onCreate` method for your [Application](https://developer.android.com/reference/android/app/Application) class. Initialization requires configuration data for your Marketing Cloud Engagement application. Before you initialize the SDK, [configure your app in Marketing Cloud Engagement](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_mce_configure.md) and obtain the `App ID`, `Access Token`, `App Endpoint`, and `MID` values. ::::::tabset{tabs='["v10+", "v8 and 9", "v7"]'} :::::tab For SDK version 10 or higher, use this code. ```java class MyApplication : Application() { override fun onCreate() { super.onCreate() // Initialize logging _before_ initializing the SDK to avoid losing valuable debugging information. if(BuildConfig.DEBUG) { SFMCSdk.setLogging(LogLevel.DEBUG, LogListener.AndroidLogger()) MarketingCloudSdk.setLogLevel(MCLogListener.VERBOSE) MarketingCloudSdk.setLogListener(MCLogListener.AndroidLogListener()) } SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { engagementModuleConfig = MarketingCloudConfig.builder().apply { setApplicationId("{mc_application_id}") setAccessToken("{mc_access_token}") setMarketingCloudServerUrl("{marketing_cloud_url}") // Other configuration options }.build(applicationContext) }) { initStatus -> // Handle initialization status } } } ``` ::::: :::::tab For version 8 or 9 of the SDK, use `SFMCSdk` to initialize the `MarketingCloudSdk`. ```java class MyApplication : Application() { override fun onCreate() { super.onCreate() // Initialize logging _before_ initializing the SDK to avoid losing valuable debugging information. if(BuildConfig.DEBUG) { SFMCSdk.setLogging(LogLevel.DEBUG, LogListener.AndroidLogger()) MarketingCloudSdk.setLogLevel(MCLogListener.VERBOSE) MarketingCloudSdk.setLogListener(MCLogListener.AndroidLogListener()) } SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { pushModuleConfig = MarketingCloudConfig.builder().apply { setApplicationId("{mc_application_id}") setAccessToken("{mc_access_token}") setSenderId("{fcm_sender_id}") setMarketingCloudServerUrl("{marketing_cloud_url}") setNotificationCustomizationOptions( NotificationCustomizationOptions.create(R.drawable.ic_notification_icon) ) // Other configuration options }.build(applicationContext) }) { initStatus -> // TODO handle initialization status } } } ``` ::::: :::::tab If you use version 7 of the SDK, use this code. ```java class MyApplication : Application() { override fun onCreate() { super.onCreate() // Initialize logging _before_ initializing the SDK to avoid losing valuable debugging information. if(BuildConfig.DEBUG) { MarketingCloudSdk.setLogLevel(MCLogListener.VERBOSE) MarketingCloudSdk.setLogListener(MCLogListener.AndroidLogListener()) } MarketingCloudSdk.init(applicationContext as Application, MarketingCloudConfig.builder().apply { setApplicationId("{mc_application_id}") setAccessToken("{mc_access_token}") setSenderId("{fcm_sender_id}") setMarketingCloudServerUrl("{marketing_cloud_url}") setMid("{mid}") setNotificationCustomizationOptions( NotificationCustomizationOptions.create(R.drawable.ic_notification_icon) ) // Other configuration options }.build(applicationContext)) { status -> // TODO handle initialization status } } } ``` ::::: :::::: To ensure that the SDK can send messages while the app is in the background, call the SDK’s `configure` method and initialize the `pushModuleConfig` from your app’s `onCreate` method. ## See Also - [Customizing Push Notifications in Android Apps](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_push_notifications/mc_engagement_push_notifications_android_customize.md) - [Troubleshoot Initialization and Registration](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_troubleshooting/mc_engagement_troubleshooting_android_initialization_errors.md) # Install and configure Install and configure the unified Flutter plugin for your app. ## Install a Product Package Install the product package that matches your implementation. To use the plugin with Marketing Cloud Engagement, use `sfmc_marketingcloudsdk`: ``` flutter pub add sfmc_marketingcloudsdk ``` To use the plugin with Marketing Cloud Next, use `sfmc_mobileappmessaging`: ``` flutter pub add sfmc_mobileappmessaging ``` ## Add Optional Feature Packages Both `sfmc_marketingcloudsdk` and `sfmc_mobileappmessaging` depend on `sfmc_core`. When you install one of these packages, the system resolves `sfmc_core` automatically. Install optional feature packages only when your app requires them. ``` flutter pub add sfmc_push flutter pub add sfmc_iam ``` ## Initialize SDK Access in Flutter Use each module's `requestSdk()` API to initialize the native SDK and access typed SDK operations. If you make a subsequent call to `requestSdk()`, the SDK doesn't perform any action. ``` import 'package:sfmc_core/sfmc_core.dart'; import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; // Initialize core await SFMCSdkModule.requestSdk(); await SFMCSdkModule.setProfileId('user-123'); await SFMCSdkModule.setAttribute('plan', 'pro'); await SFMCSdkModule.track( CustomEvent(name: 'purchase', attributes: {'amount': '49.99'}), ); // Use the engagement product await MarketingCloudSdk.requestSdk(); final unread = await MarketingCloudSdk.getUnreadMessages(); if (unread.isNotEmpty) { await MarketingCloudSdk.markMessageRead(unread[0].id!); } ``` See each package's README for full API documentation with links to native SDK docs. ## Platform Configuration After you install the base components, complete the platform-specific setup steps. - [Configure Flutter for Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/configure-flutter-android.md) - [Configure Flutter for iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/configure-flutter-ios.md) # Install and Configure the Unified React Native Plugin Install and configure the React Native unified plugin for your app. ## Install a Product Package Install the product package that matches your implementation. To install Marketing Cloud Engagement, use `@sfmc/react-native-marketingcloudsdk`: ``` npm install @sfmc/react-native-marketingcloudsdk ``` ``` yarn add @sfmc/react-native-marketingcloudsdk ``` To install Mobile App Messaging, use `@sfmc/react-native-mobileappmessaging`: ``` npm install @sfmc/react-native-mobileappmessaging ``` ``` yarn add @sfmc/react-native-mobileappmessaging ``` ## Add Optional Feature Packages Both `marketingcloudsdk` and `mobileappmessaging` depend on `sfmc-core`. When you install one of these packages, the system installs `sfmc-core` automatically. Install optional feature packages only when your app requires them. ``` yarn add @sfmc/react-native-push @sfmc/react-native-iam ``` ## Initialize SDK Access in React Native Use each module's `requestSdk()` API to access typed SDK operations. ``` import { SFMCSdkModule } from '@sfmc/react-native-sfmc-core'; const coreSdk = await SFMCSdkModule.requestSdk(); ``` ## Platform Configuration After base installation, complete platform setup: - [Configure React Native for Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/configure-react-native-android.md) - [Configure React Native for iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/configure-react-native-ios.md) # Integrate Einstein Recommendations and Collect API Einstein Recommendations analytics uses a unique identifier to attribute collected analytics to a specific user. By default, the SDK uses the Contact Key as this identifier, also known as the Predictive Intelligence Identifier (PIID). Your app can explicitly set this value. For configuration information, see [`setPiIdentifier`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.analytics/-analytics-manager/set-pi-identifier.html) and [`setUseLegacyPiIdentifier`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud/-marketing-cloud-config/use-legacy-pi-identifier.html). **important:** If the PIID is unset or `null`, and the SDK is set to use the Legacy PIID, it uses the Contact Key instead. Set or clear the PIID to control which user receives attribution for collected analytics. Use the analytics manager to manage the identifier. ::::::tabset{tabs='["SDK v10", "SDK v8", "SDK v7"]'} :::::tab For SDK version 10, use this example. ```java MarketingCloudSdk.requestSdk { engagementSdk -> val analyticsManager = engagementSdk.analyticsManager // Set the PI ID analyticsManager.piIdentifier = "developer@salesforce.com" // Clear the PI ID analyticsManager.piIdentifier = null } ``` ::::: :::::tab For SDK version 8, use this example. ```java SFMCSdk.requestSdk { sdk -> sdk.mp { val analyticsManager = it.analyticsManager // Set the PI ID analyticsManager.piIdentifier = "developer@salesforce.com" // Clear the PI ID analyticsManager.piIdentifier = null } } ``` ::::: :::::tab For SDK version 7, use this example. ```java MarketingCloudSdk.requestSdk { val analyticsManager = it.analyticsManager // Set the PI ID analyticsManager.piIdentifier = "developer@salesforce.com" // Clear the PI ID analyticsManager.piIdentifier = null } ``` ::::: :::::: ## Integration Methods Use these methods to integrate your mobile app with Einstein Recommendations. To use these methods, you must have an existing [Einstein Recommendations](https://help.salesforce.com/articleView?id=mktg.mc_pb_personalization_builder.htm) deployment, and you must enable the `PiAnalytics` option when you configure your SDK. ### Track Cart [Track the contents of an in-app shopping cart](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_analytics_android_recommendations_integrate_cart_track.md) to send cart data to Einstein Recommendations. Use this method to capture items, quantities, and prices as users build their carts. ### Track Conversion [Track purchases made through your mobile app](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_analytics_android_recommendations_integrate_conversion_track.md) to record order details including shipping, discounts, and cart contents. This data helps Einstein Recommendations understand purchase patterns. ### Track Page Views [Implement page-view analytics](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_analytics_android_recommendations_integrate_views_track.md) to track which items and pages users view in your app. This information helps Einstein Recommendations provide better product suggestions. ### Track Inbox Message Opens [Track inbox message opens](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_analytics_android_recommendations_integrate_opens_track.md) to send open analytic values to Marketing Cloud Engagement. The SDK automatically provides analytics for message downloads. --- Rights of ALBERT EINSTEIN are used with the permission of The Hebrew University of Jerusalem. Represented exclusively by Greenlight. # Integrate Einstein Recommendations and Collect API Einstein Recommendations uses a unique identifier called the `PIID` to attribute analytics to specific users. By default, the SDK uses the contact key as the PIID. You can explicitly set this value in your app. The SDK includes a configuration option called `useLegacyPiIdentifier`. When enabled, this option replaces an absent or empty PIID with the contact key. When disabled, the SDK doesn't replace an absent or empty PIID. Configure the SDK with `pianalytics` and `useLegacyPiIdentifier` as described in [Configure the SDK for iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_integrate_ios/mc_engagement_integrate_ios_configure.md). **important:** To ensure future compatibility, we recommend that you explicitly set the PIID. Set or clear the PIID to control which user receives attribution for collected analytics. ::::::tabset{tabs='["SDK v10+", "SDK v8", "SDK v7"]'} :::::tab Use this code example with SDK version 10 or later. ```swift MarketingCloudSdk.requestSdk { mc in // Example: Setting and clearing pi identifier. // Setting the pi identifier mc?.setPiIdentifier("example@email.com") // Clearing the pi identifier mc?.setPiIdentifier(nil) } ``` ::::: :::::tab Use this code example with SDK version 8. ```swift SFMCSdk.requestPushSdk { mp in // Example: Setting and clearing pi identifier. // Setting the pi identifier mp.setPiIdentifier("example@email.com") // Clearing the pi identifier mp.setPiIdentifier(nil) } ``` ::::: :::::tab Use this code example with SDK version 7. ```swift // Example: Setting and clearing pi identifier. // Setting the pi identifier MarketingCloudSDK.sharedInstance().sfmc_setPiIdentifier("example@email.com") // Clearing the pi identifier MarketingCloudSDK.sharedInstance().sfmc_setPiIdentifier(nil) ``` ::::: :::::: ## Integration Methods Integrate your mobile app with Einstein Recommendations using these methods. You must have an existing Einstein Recommendations deployment and enable the `pianalytics` option when you configure the SDK. ### Track Cart [Track the contents of an in-app shopping cart](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_analytics_ios_recommendations_integrate_cart_track.md) to send cart data to Einstein Recommendations. Use this method to capture items, quantities, and prices as users build their carts. ### Track Conversion [Track purchases made through your mobile app](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_analytics_ios_recommendations_integrate_conversion_track.md) to record order details including shipping, discounts, and cart contents. This data helps Einstein Recommendations understand purchase patterns. ### Track Page Views [Implement page-view analytics](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_analytics_ios_recommendations_integrate_views_track.md) to track which items and pages users view in your app. This information helps Einstein Recommendations provide better product suggestions. --- Rights of ALBERT EINSTEIN are used with the permission of The Hebrew University of Jerusalem. Represented exclusively by Greenlight. # Integrate the Cordova Plugin with Capacitor or Ionic Apps Use the Cordova Plugin to integrate the Engagement SDK into Ionic and Capacitor applications. For detailed installation and setup instructions, see [Marketing Cloud Cordova Plugin](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_development_frameworks_cordova.md). ## Modify Configurations To integrate Capacitor or Ionic apps with the SDK, configure the Cordova plugin by modifying your application’s configuration file. ### Ionic Configuration For Ionic apps, modify the `capacitor.config.ts` file and add preferences under `cordova`, as shown in this example. ```typescript const config: CapacitorConfig = { appId: "io.ionic.starter", // The ID of your app appName: "ionicapp", // The name of your app webDir: "build", bundledWebRuntime: false, cordova: { preferences: { // Marketing Cloud Engagement configuration "com.salesforce.marketingcloud.app_id": "{Engagement application id}", "com.salesforce.marketingcloud.access_token": "{Engagement access token}", "com.salesforce.marketingcloud.tenant_specific_endpoint": "{URL retrieved from Engagement administration page}", "com.salesforce.marketingcloud.analytics": "{true|false}", "salesforce.marketingcloud.delay_registration_until_contact_key_is_set": "{true|false}", "com.salesforce.marketingcloud.notification_small_icon": "ic_launcher_foreground", }, }, }; ``` ### Capacitor Configuration For Capacitor apps, modify the `capacitor.config.json` file and add preferences under `cordova`, as shown in this example. ```json { "appId": "com.example.app", // The ID of your app "appName": "testSFMC", // The name of your app "bundledWebRuntime": false, "webDir": "dist", "plugins": { "SplashScreen": { "launchShowDuration": 0 } }, "cordova": { "preferences": { // Marketing Cloud Engagement configuration "com.salesforce.marketingcloud.app_id": "{App ID}", "com.salesforce.marketingcloud.access_token": "{Access token}", "com.salesforce.marketingcloud.tenant_specific_endpoint": "{Tenant-specific endpoint URL}", "com.salesforce.marketingcloud.analytics": "{true|false}", "salesforce.marketingcloud.delay_registration_until_contact_key_is_set": "{true|false}", "com.salesforce.marketingcloud.notification_small_icon": "ic_launcher_foreground" } } } ``` **important:** Complete these steps each time you add the platform to your Capacitor app. ## Android Setup Copy the `google-services.json` file into the `YOUR_APP/android/app/` directory. ## iOS Setup 1. Enable push notifications in the **Capabilities** settings for your target in Xcode by clicking **+ Capability** and then selecting **Push Notifications**. ![Enabling Push on iOS Apps](https://developer.salesforce.com/media/overview/enable-push-ios-apps.png) 2. Enable iOS push notifications by adding this code to `AppDelegate`. ```swift // SDK imports // The SFMCSDK module is included in the dependency packages for the SDK. Don't install it // separately or list it in your podfile. import SFMCSDK import MarketingCloudSDK ``` **note:** The SFMCSDK module is included in the dependency packages for the SDK. Don't install it separately or list it in your podfile. Also add this code to the end of the `AppDelegate.swift` file. ```swift //SFMCSDK PushNotification extension AppDelegate { // REQUIRED IMPLEMENTATION func application( _ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data ) { SFMCSdk.mp.setDeviceToken(deviceToken) } // REQUIRED IMPLEMENTATION func application( _ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error ) { print(error) } // REQUIRED IMPLEMENTATION /** This delegate method offers an opportunity for applications with the "remote-notification" background mode to fetch appropriate new data in response to an incoming remote notification. You should call the fetchCompletionHandler as soon as you’re finished performing that operation, so the system can accurately estimate its power and data cost. This method is invoked even if the application was launched or resumed because of the remote notification. The respective delegate methods will be invoked first. Note that this behavior is in contrast to application:didReceiveRemoteNotification:, which is not called in those cases, and which will not be invoked if this method is implemented. **/ func application( _ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void ) { SFMCSdk.mp.setNotificationUserInfo(userInfo) completionHandler(.newData) } } ``` ## Usage with TypeScript If you use TypeScript with your app, declare the plugin before you call the APIs, as shown in this example. ```typescript //Declare the plugin (for typescript) declare let MCCordovaPlugin: any; declare let SFMCEvent: any; //Call plugin APIs MCCordovaPlugin.enableLogging(); MCCordovaPlugin.enablePush(); //Other APIs... ``` ## See Also - [Cordova Plugin API Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_development_frameworks_cordova_ref.md) # Integrate the iOS Extension SDK The iOS Extension SDK for Marketing Cloud Next adds support for rich notifications, push delivery tracking, and carousel templates to your iOS app. Use the extension SDK to enable these advanced push notification features. The extension SDK works with the Mobile App Messaging SDK through Service Extensions and Content Extensions. These extensions run separately from your main app and handle notification delivery events and rich media content. ## Prerequisites Before you integrate the iOS Extension SDK, complete these requirements: - [Integrate the Mobile App Messaging SDK for iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_next_integrate_ios/mc_next_integrate_ios.md) in your main app - Add Service and Content Extension targets to your Xcode project ## Integration Steps Follow these steps to integrate the iOS Extension SDK: 1. [Configure the Service Extension](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_integrate_ios_extension_configure_service.md) to set up notification delivery tracking. 2. [Configure the Content Extension](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_integrate_ios_extension_configure_content.md) to enable rich media notifications. 3. [Enable App Groups](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_integrate_ios_extension_enable_app_groups.md) to allow communication between the extensions and your app. 4. [Configure Carousel Click Actions](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_integrate_ios_extension_handle_carousel.md) to respond when a user taps on a carousel image. ## See Also - [iOS Extension SDK releases](https://github.com/salesforce-marketingcloud/extension-sdk-ios/releases) - _Apple Developer Documentation_: [UNNotificationServiceExtension](https://developer.apple.com/documentation/usernotifications/unnotificationserviceextension) - _Apple Developer Documentation_: [UNNotificationContentExtension](https://developer.apple.com/documentation/usernotificationsui/unnotificationcontentextension) # Integrate the iOS SDK Integrate the Mobile App Messaging SDK into your iOS app to enable push notifications, in-app messages, and other messaging features. ## Prerequisites Before you integrate the SDK, [configure Apple Push Notification service (APNs) obtain obtain the necessary security credentials](https://developer.salesforce.com/docs/marketing/before-you-begin/engagement_sdk_guides_before_you_begin_prereqs.md#configure-apple-push-notification-service-for-ios). ## Install SDK Dependencies Choose an installation method based on your project setup: - [Install with CocoaPods](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_integrate_ios_cocoapods.md) - [Install with Swift Package Manager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_integrate_ios_spm.md) - [Install Manually](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_integrate_ios_manual.md) ## Configure the SDK After you install the SDK dependencies, [configure the iOS SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_integrate_ios_configure.md) in your app. ## Next Steps After you integrate and configure the SDK, add support for rich notifications and delivery tracking by [integrating the iOS Extension SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_next_integrate_ios_extension/mc_next_integrate_ios_extension.md). # Integrate the Mobile App Messaging SDK with your Android App To use mobile app messaging features in your app, integrate the Mobile App Messaging SDK and its dependencies into your app. ## Add the Dependencies Update the `settings.gradle` file for your app to include the required dependencies for the SDK. **note:** Replace `{currentVersion}` in this example with the latest SDK version number from the [change log](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_next_changelog.md#android). ```java dependencyResolutionManagement { repositories { maven ("https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/repository") // other repositories } } dependencies { implementation 'com.salesforce.marketingcloud:mobileappmessagingsdk:{currentVersion}' } ``` ## Initialize the SDK Initialize the SDK during the execution of the `onCreate` method for your [Application](https://developer.android.com/reference/android/app/Application) class. This code example shows how to initialize the SDK. ```java class SDKTestApp : Application() { override fun onCreate() { super.onCreate() if(BuildConfig.DEBUG){ // Debug logging for all modules enabled for debug builds SFMCSdk.setLogging(LogLevel.DEBUG, LogListener.AndroidLogger()) // Enable debug logging just for MAM module SFMCSdk.setLogging(LogLevel.DEBUG, LogListener.AndroidLogger(), ModuleLogger.MAM) } SFMCSdk.configure(this, SFMCSdkModuleConfig.build { this.mamModuleConfig = MobileAppMessagingConfig.builder() .moduleApplicationId("YOUR_APP_ID") .tenantId("YOUR_TENANT_ID") .accessToken("YOUR_ACCESS_TOKEN") .endpointUrl("ENDPOINT_URL") .build() }){ initStatus -> // Handle initialization status } } } ``` If you don’t call the SDK’s `configure` method and initialize the `mamModuleConfig` from your app’s `onCreate` method, the SDK can’t send notifications to the app while it’s in the background. # Integrate the MobilePush Android SDK Integrate the Salesforce Engagement SDK for Android and its dependencies into your app. The integration involves adding the SDK repository within **dependencyResolutionManagement** in `settings.gradle`, and the `marketingcloudsdk` dependency in your app’s module-level `build.gradle` file, as shown in this example. To use the latest SDK version, replace `{currentVersion}` in this code sample with the latest version number available on the [SDK Releases page](https://github.com/salesforce-marketingcloud/MarketingCloudSDK-Android/releases). ```java dependencyResolutionManagement { repositories { maven { url "https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/repository" } // other repositories } } dependencies { implementation 'com.salesforce.marketingcloud:marketingcloudsdk:{currentVersion}' } ``` The SDK doesn’t declare the Google Play Services Location or AltBeacon libraries as required dependencies for Android apps. If your application requires these features, [enable them](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_location_messages/mc_engagement_location_messages_android.md). # Integrate the Salesforce Engagement SDK Extension for iOS The iOS Extension SDK extends the capabilities of your push notifications by enabling these features: - **Push delivery tracking**: Monitor when notifications reach user devices - **Rich media support**: Display images and videos in push notifications - **Carousel template**: Present multiple pieces of content users can swipe through - **Custom notification UI**: Create interactive notification experiences ## Prerequisites Complete these prerequisites before you install the iOS SDK Extension: - Install Xcode 12 or later - Create an Apple Developer account with the ability to create app extensions - [Integrate version 9 or later of the SDK into your iOS app](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_integrate_ios/mc_engagement_integrate_ios.md) ## Integration Steps Follow these steps to integrate the iOS Extension SDK into your app: 1. [Configure the Service Extension](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_integrate_ios_extension_configure_service.md) — Set up the Notification Service Extension to handle push delivery events and rich media 2. [Configure the Content Extension](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_integrate_ios_extension_configure_content.md) — Set up the Notification Content Extension to show carousel templates 3. [Enable App Groups](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_integrate_ios_extension_enable_app_groups.md) — Configure app groups to share data between your app and its extensions 4. [Handle Carousel Click Actions](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_integrate_ios_extension_handle_carousel.md) — Process user interactions with carousel notifications in your main app # Integrate the SDK for iOS Integrate the Salesforce Engagement SDK into your iOS app to enable push notifications and user engagement features. ## Prerequisites Before you integrate the SDK, complete these prerequisites: - Install Xcode 12 or later - [Configure your app in Marketing Cloud Engagement](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_mce_configure.md) and obtain the `App ID`, `Access Token`, `App Endpoint`, and `MID` values ## Integration Steps Follow these steps to integrate the SDK into your iOS app. 1. Install the dependencies for the SDK. Choose one of these methods for managing the dependencies: - [Install with CocoaPods](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/engagement_sdk_guide_integrate_ios_cocoapods.md) - [Install with Swift Package Manager](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/engagement_sdk_guide_integrate_ios_spm.md) - [Install Manually](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/engagement_sdk_guide_integrate_ios_manual.md) 2. [Configure the SDK in your app](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_integrate_ios_configure.md). ## Additional Configuration After you complete the basic integration, configure these additional features: - Add a [privacy manifest](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/engagement_sdk_guide_integrate_ios_privacy_manifest.md) to your app to comply with the requirements of the App Store. - If your app uses [iOS Data Protection](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/engagement_sdk_guide_integrate_ios_data_protection.md), understand how it affects the SDK. # Integrate with Other Platforms If you build your app with a development platform such as React Native, you can integrate the Engagement SDK with that framework. - To integrate the SDK with the React Native framework, see [React Native Unified Plugin Setup](/docs/marketing/mobile-unified-sdk/guide/unified-react-native-setup.html). # IntentProvider **Package:** `com.salesforce.marketingcloud.pushfeature.push` **Module:** Push Feature Module v2.0.0 **SDK:** Salesforce Marketing Cloud Unified SDK 11.0.0 ## Overview ```kotlin open class IntentProvider( context: Context, message: NotificationMessage ) ``` A class that provides intent handling functionality for push notifications in the Salesforce Marketing Cloud SDK. ## Constructor ### IntentProvider ```kotlin constructor( context: Context, message: NotificationMessage ) ``` **Parameters:** - `context`: Android Context object - `message`: NotificationMessage containing push notification data ## Nested Types ### Companion ```kotlin object Companion ``` Companion object for the IntentProvider class. ## Methods ### getActionPendingIntent ```kotlin fun getActionPendingIntent( actions: Array?, analyticsType: String, clickedId: String, title: String? ): PendingIntent? ``` Creates a PendingIntent for notification actions. **Parameters:** - `actions`: Array of Action objects defining notification actions (nullable) - `analyticsType`: String identifying the analytics type - `clickedId`: String identifier for the clicked element - `title`: String title for the action (nullable) **Returns:** - `PendingIntent?`: A PendingIntent object or null **Description:** Generates a PendingIntent for the passed actions ## Platform - **Target:** androidJvm # InvalidCompressionException ## Package `com.salesforce.marketingcloud.pushmodels.exceptions` ## Description An exception class that is thrown when push notification data contains invalid compression. This class extends `PushException`. ## Inheritance ```kotlin class InvalidCompressionException : PushException ``` ## Constructors ### InvalidCompressionException ```kotlin constructor(message: String) ``` Creates a new `InvalidCompressionException` with the specified error message. **Parameters:** - `message`: `String` - The error message describing the invalid compression issue ## Module Information - **Module**: Push Models Module v1.0.2 - **SDK**: Salesforce Marketing Cloud Unified SDK - **Target**: androidJvm ## Source [View on GitHub Pages](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushmodelsmodule/com.salesforce.marketingcloud.pushmodels.exceptions/-invalid-compression-exception/index.html) # InvalidJsonException ## Package `com.salesforce.marketingcloud.pushmodels.exceptions` ## Description An exception class thrown when push notification JSON has invalid structure or syntax. ## Class Declaration ```kotlin class InvalidJsonException(message: String) : PushException ``` ## Inheritance - Extends: `PushException` ## Constructors ### InvalidJsonException ```kotlin constructor(message: String) ``` Creates a new `InvalidJsonException` with the specified error message. **Parameters:** - `message`: `String` - The detail message describing the invalid JSON error # iOS Data Protection The Salesforce Engagement SDK requires access to files on the iOS device file system. Some iOS Data Protection modes can prevent the SDK from accessing the needed files at certain times. During normal operation, the SDK requires access to files while running in the foreground and while running in the background. If the SDK can’t access these files because it’s prohibited by the iOS Data Protection mode, the SDK logs an error. By default, the SDK sets the file protection type to `NSFileProtectionCompleteUntilFirstUserAuthentication`. With this file protection type, files are stored in an encrypted format on disk and can’t be read from or written to until the user unlocks the device for the first time. In version 8.0.9 or later of the SDK, the SDK retains the default protection type (`NSFileProtectionCompleteUntilFirstUserAuthentication`). It also provides the capability to override the file protection type within the consuming application. Specify a different file protection type, such as `NSFileProtectionComplete` and `NSFileProtectionCompleteUnlessOpen`, if your application requires it. ## SDK Behavior by Protection Level iOS Data Protection affects the SDK as described in this table. | iOS Data Protection Level | SDK Behavior | | ---------------------------------------- | ----------------------------------------------------------------- | | No protection | SDK works in the foreground and background | | Complete until first user authentication | SDK works in the foreground and background after the first unlock | | Complete unless open | SDK works in the foreground and background after the first unlock | | Complete | SDK works only in the foreground after the device is unlocked | ## Override the File Protection Type The following example shows how you can override the file protection type. ```swift SFMCSdk.setFileProtectionType(fileProtectionType: .completeUntilFirstUserAuthentication) ``` For an additional example of overriding the file protection type, see the [learning application](https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS/blob/spm/examples/LearningApp/LearningApp/AppDelegate.swift#L58). ## Handle Configuration Issues If you configure iOS data protection such that the file system isn’t accessible during the SDK configuration call, the SDK retries the call for up to 5 seconds. This retry period allows time for a user to unlock the device and make the file system accessible. If the user doesn’t unlock the device within 5 seconds, an error object is returned describing the error, and the configuration call fails, returning `false`. In this case, the SDK isn’t configured. Don’t attempt to access SDK methods until the `configure` method returns `true`. The `error` object returns the error code `configureDatabaseAccessError`. ## Handle Foreground and Background Operation Issues Some features of the SDK require access to the file system when the app transitions to the foreground or to the background. Foreground operations include retrieving messages for inbox messaging, location messaging, and sending analytic information back to Marketing Cloud Engagement. Background operations include sending analytic information to Marketing Cloud Engagement. If you enable any of these features via configuration, select an appropriate iOS Data Protection mode. **note:** If the `FileProtectionType` is `NSFileProtectionComplete` and the application goes to the background, `NSSQLiteErrorDomain` errors can appear in logs. # iOS Data Protection iOS Data Protection restricts when the Salesforce Engagement SDK can access files on the device, which can prevent the SDK from running correctly in the foreground or background. This table describes how iOS Data Protection impacts the SDK. | iOS Data Protection Level | SDK Behavior | | ---------------------------------------- | ----------------------------------------------------------------- | | No protection | SDK works in the foreground and background | | Complete until first user authentication | SDK works in the foreground and background after the first unlock | | Complete unless open | SDK works in the foreground and background after the first unlock | | Complete | SDK works only in the foreground after the device is unlocked | Some iOS Data Protection modes can prevent the SDK from accessing the needed files at certain times. During normal operation, the SDK must have access to files while running in the foreground and in the background. If the SDK can’t access these files due to an iOS Data Protection mode, the operation fails and the SDK logs an error. By default, the SDK sets the file protection type to `NSFileProtectionCompleteUntilFirstUserAuthentication`. With this file protection type, files are stored in an encrypted format on disk and can’t be read from or written to until the user unlocks the device for the first time. As of version 8.0.9, the SDK continues to retain the default protection type (`NSFileProtectionCompleteUntilFirstUserAuthentication`). However, it also provides the capability to override the file protection type within the consuming application. You can choose different file protection types, such as `NSFileProtectionComplete` and `NSFileProtectionCompleteUnlessOpen`, based on your specific needs. **note:** `NSSQLiteErrorDomain` errors can appear in logs if the `FileProtectionType` is `NSFileProtectionComplete` and the application goes to the background. ## Override FileProtectionType The following example shows how you can override the file protection type. ``` SFMCSdk.setFileProtectionType(fileProtectionType: .completeUntilFirstUserAuthentication) ``` For an additional example of overriding the file protection type, see the [learning application](https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS/blob/spm/examples/LearningApp/LearningApp/AppDelegate.swift#L58). ## Configuration Issues If you configure iOS data protection such that the file system isn’t accessible during the SDK configuration call, the SDK retries the call for up to 5 seconds. This retry period allows time for a user to unlock the device and make the file system accessible. If the user doesn’t unlock the device within 5 seconds, an error object is returned describing the error, and the configuration call fails, returning `false`. In this case, the SDK isn’t configured, and no access to SDK methods must be attempted until the `configure` method returns `true`. The `error` object returns the error code `configureDatabaseAccessError`. ## Foreground and Background Operation Issues Certain features of the SDK require access to the file system as the app transitions to the foreground or background. Foreground operations include retrieving messages from Engagement for inbox messaging, location messaging, and sending analytic information back to Engagement. Background operations include sending analytic information back to Engagement. If any of these features are enabled via configuration, then an appropriate iOS Data Protection mode must be selected for them to work correctly. # isAnalyticsEnabled Checks if analytics are enabled in the native MobilePush SDK. ## Syntax `MCCordovaPlugin.isAnalyticsEnabled(successCallback, [errorCallback])` ## Kind Static method of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | ----------------- | ---------- | ----------- | | `successCallback` | `function` | | | `errorCallback` | `function` | | # isAnalyticsEnabled Checks if analytics tracking is enabled for the SDK. ## Syntax ```dart Future isAnalyticsEnabled() ``` ## Returns - `Future` - Returns `true` if analytics is enabled, `false` if disabled. ## Example ```dart bool isEnabled = await SfmcSdk.isAnalyticsEnabled(); if (isEnabled) { print('Analytics is enabled'); } else { print('Analytics is disabled'); } ``` ## Related Methods - [setAnalyticsEnabled()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_setAnalyticsEnabled.md) # isAnalyticsEnabled Checks if analytics is enabled in the MobilePush SDK. ## Syntax ```javascript MCReactModule.isAnalyticsEnabled() ⇒ Promise. ``` ## Returns - `Promise.` - A promise to the boolean representation of whether analytics is enabled. ## Example ```javascript import { MCReactModule } from "react-native-marketingcloudsdk"; const checkAnalyticsStatus = async () => { try { const isEnabled = await MCReactModule.isAnalyticsEnabled(); console.log("Analytics enabled:", isEnabled); } catch (error) { console.error("Error checking analytics status:", error); } }; ``` ## See Also - [Runtime Toggles](/docs/marketing/mobilepush/guide/runtime-toggles.html) ## Related Methods - [setAnalyticsEnabled()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_setAnalyticsEnabled.md) # isPiAnalyticsEnabled Checks whether Predictive Intelligence (PI) analytics are enabled in the native MobilePush SDK. ## Syntax `MCCordovaPlugin.isAnalyticsEnabled(successCallback, [errorCallback])` ## Kind Static method of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | ----------------- | ---------- | ----------- | | `successCallback` | `function` | | | `errorCallback` | `function` | | # isPiAnalyticsEnabled Checks if PI (Predictive Intelligence) analytics tracking is enabled for the SDK. ## Syntax ```dart Future isPiAnalyticsEnabled() ``` ## Returns - `Future` - Returns `true` if PI analytics is enabled, `false` if disabled. ## Example ```dart bool isEnabled = await SfmcSdk.isPiAnalyticsEnabled(); if (isEnabled) { print('PI Analytics is enabled'); } else { print('PI Analytics is disabled'); } ``` ## Related Methods - [setPiAnalyticsEnabled()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_setPiAnalyticsEnabled.md) # isPiAnalyticsEnabled Checks if PI analytics is enabled in the MobilePush SDK. ## Syntax ```javascript MCReactModule.isPiAnalyticsEnabled() ⇒ Promise. ``` ## Returns - `Promise.` - A promise to the boolean representation of whether PI analytics is enabled. ## Example ```javascript import { MCReactModule } from "react-native-marketingcloudsdk"; const checkPiAnalyticsStatus = async () => { try { const isEnabled = await MCReactModule.isPiAnalyticsEnabled(); console.log("PI Analytics enabled:", isEnabled); } catch (error) { console.error("Error checking PI analytics status:", error); } }; ``` ## See Also - [Runtime Toggles](/docs/marketing/mobilepush/guide/runtime-toggles.html) ## Related Methods - [setPiAnalyticsEnabled()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_setPiAnalyticsEnabled.md) # isPushEnabled The current state of the `pushEnabled` flag in the native MobilePush SDK. ## Syntax `MCCordovaPlugin.isPushEnabled(successCallback, [errorCallback])` ## Kind Static method of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | ------------------------- | ---------- | ---------------------------------- | | `successCallback` | `function` | | | `successCallback.enabled` | `boolean` | Indicates whether push is enabled. | | `errorCallback` | `function` | | # isPushEnabled Checks if push notifications are enabled for the device. ## Syntax ```dart Future isPushEnabled() ``` ## Returns - `Future` - Returns `true` if push notifications are enabled, `false` if disabled, or `null` if the status cannot be determined. ## Example ```dart bool? isEnabled = await SfmcSdk.isPushEnabled(); if (isEnabled == true) { print('Push notifications are enabled'); } else if (isEnabled == false) { print('Push notifications are disabled'); } else { print('Push notification status unknown'); } ``` ## Related Methods - [enablePush()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_enablePush.md) - [disablePush()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_disablePush.md) # isPushEnabled The current state of the `pushEnabled` flag in the MobilePush SDK. ## Syntax ```javascript MCReactModule.isPushEnabled() ⇒ Promise. ``` ## Returns - `Promise.` - A promise to the boolean representation of whether push is enabled. ## Example ```javascript import { MCReactModule } from "react-native-marketingcloudsdk"; const checkPushStatus = async () => { try { const isEnabled = await MCReactModule.isPushEnabled(); console.log("Push enabled:", isEnabled); } catch (error) { console.error("Error checking push status:", error); } }; ``` ## See Also - [enablePush() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_enablePush.md) - [disablePush() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_disablePush.md) # Keychain Crash **important:** This troubleshooting guidance applies only to MobilePush SDK for iOS versions 8.0.13 and earlier. Fatal Keychain Access exceptions occur if an application with an active SDK integration tries to access Keychain on a locked device secured with Face ID or passcode-based authentication. iOS Data Protection modes prevent the SDK from accessing these files. These sections describe common Keychain Access exceptions and provide guidance on resolving them. - [Common `errSecInteractionNotAllowed` Exceptions](#common-errsecinteractionnotallowed-exceptions) - [Unknown status code (-34018)](#unknown-status-code--34018) ## Common `errSecInteractionNotAllowed` Exceptions These are common occurrences of the `errSecInteractionNotAllowed` exception: - `Fatal Exception: com.salesforce.security.keychainException dictionaryItemFromKeychain: Error attempting to look up keychain item: errSecInteractionNotAllowed` - `Fatal Exception: com.salesforce.security.keychainException setObject:forKey:: Error saving value to the keychain: errSecInteractionNotAllowed.` - `Fatal Exception: com.salesforce.security.keychainException writeToKeychain: Error adding keychain item: errSecInteractionNotAllowed.` To resolve `errSecInteractionNotAllowed` exceptions, follow these steps. - Upgrade to SDK for iOS version 8.0.8 or later and Marketing Cloud SDK version 1.0.6 or later. - Before initializing the SDK, set the `setKeychainAccessErrorsAreFatal` method to `false`. ```swift SFMCSdk.setKeychainAccessErrorsAreFatal(errorsAreFatal: false) ``` Setting this property to `false` logs the exception to the console instead of causing the app to crash. ## Unknown Status Code (-34018) You can encounter an error message that indicates a keychain access issue along with an unknown status code `(-34018)`. ``` Terminating app due to uncaught exception 'com.salesforce.security.keychainException', reason: 'dictionaryItemFromKeychain: Error attempting to look up keychain item: Unknown status code (-34018)' ``` To resolve this issue, enable **Keychain Sharing** in the **Signing & Capabilities** pane in Xcode. When you enable Keychain Sharing, you don’t need to add identifiers specific to the SDK. ## Related Items For an example of an ideal SDK implementation on iOS, see the [iOS LearningApp](https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS/tree/spm/examples/LearningApp). Not all the code used in the LearningApp is required. Depending on your app, you can decide which parts to implement and which to ignore. # LatLon **Package:** `com.salesforce.marketingcloud.location` **Version:** 11.0.0 ## Description A data class representing geographical coordinates that implements `Parcelable` for Android. ```kotlin data class LatLon : Parcelable ``` ## Properties ### latitude ```kotlin @JvmField val latitude: Double ``` The latitude coordinate value. ### longitude ```kotlin @JvmField val longitude: Double ``` The longitude coordinate value. ## Functions ### latitude() ```kotlin fun latitude(): Double ``` Returns the latitude coordinate. **Returns:** `Double` - The latitude value ### longitude() ```kotlin fun longitude(): Double ``` Returns the longitude coordinate. **Returns:** `Double` - The longitude value # LatLon A data class representing geographical coordinates (latitude and longitude). ## Package ``` com.salesforce.marketingcloud.pushmodels.location ``` ## Declaration ```kotlin data class LatLon : Parcelable ``` ## Overview The `LatLon` class is a Kotlin data class that represents geographical coordinates using latitude and longitude values. It implements Android's `Parcelable` interface, allowing instances to be efficiently passed between Android components. ## Module Information - **SDK**: Salesforce Marketing Cloud Unified SDK - **Module**: Push Models Module - **Module Version**: 1.0.2 - **SDK Version**: 11.0.0 - **Platform**: androidJvm ## Properties ### latitude ```kotlin @JvmField val latitude: Double ``` The latitude coordinate value. ### longitude ```kotlin @JvmField val longitude: Double ``` The longitude coordinate value. ## Methods ### latitude() ```kotlin fun latitude(): Double ``` Returns the latitude coordinate. **Returns:** The latitude value as a `Double`. ### longitude() ```kotlin fun longitude(): Double ``` Returns the longitude coordinate. **Returns:** The longitude value as a `Double`. ## Nested Types ### Companion ```kotlin object Companion ``` Companion object for the `LatLon` class. ## Inheritance - Implements: `android.os.Parcelable` ## Notes - As a Kotlin data class, `LatLon` automatically provides the following methods: - `equals()` - `hashCode()` - `toString()` - `copy()` - The `@JvmField` annotation exposes the properties as public fields to Java code, enabling direct field access from Java. - The `Parcelable` implementation allows instances to be passed between Android components (Activities, Fragments, Services) efficiently. # LineItem **Package:** `com.salesforce.marketingcloud.sfmcsdk.components.events` **Version:** 11.0.0 ## Description A data class representing line items for Cart and Order events in the Salesforce Marketing Cloud Unified SDK. Line items describe purchasable catalog objects with quantity, pricing, and additional attributes. ## Class Declaration ```kotlin data class LineItem @JvmOverloads constructor( val catalogObjectType: String, val catalogObjectId: String, val quantity: Int, var price: Double? = null, var currency: String? = null, var attributes: Map = mapOf() ) ``` ## Constructor ### Primary Constructor | Parameter | Type | Required | Default | Description | | ------------------- | ------------------ | -------- | --------- | ---------------------------------------- | | `catalogObjectType` | `String` | Yes | - | Type name for the catalog object | | `catalogObjectId` | `String` | Yes | - | Unique identifier for the catalog object | | `quantity` | `Int` | Yes | - | Number of items in this line item | | `price` | `Double?` | No | `null` | Price of the catalog object | | `currency` | `String?` | No | `null` | Currency code for the price | | `attributes` | `Map` | No | `mapOf()` | User-supplied attribute values | ## Properties ### catalogObjectType ```kotlin val catalogObjectType: String ``` A type name representing the referenced catalog object. ### catalogObjectId ```kotlin val catalogObjectId: String ``` A unique identifier for the catalog object. ### quantity ```kotlin val quantity: Int ``` The count of catalog objects in this line item. ### price ```kotlin var price: Double? ``` The price of the referenced catalog object (mutable, nullable). ### currency ```kotlin var currency: String? ``` The currency code for the price field (mutable, nullable). ### attributes ```kotlin var attributes: Map ``` A map of custom user-supplied values (mutable). # Listen for Events Control message display and get information about the in-app message display lifecycle by using the in-app messaging [EventListener](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/inappmessagingfeaturemodule/com.salesforce.marketingcloud.inappmessagingfeature/-in-app-message-manager/-event-listener/index.html). After the SDK initializes, register your in-app message [EventListener](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/inappmessagingfeaturemodule/com.salesforce.marketingcloud.inappmessagingfeature/-in-app-message-manager/-event-listener/index.html) with [InAppMessageManager](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/inappmessagingfeaturemodule/com.salesforce.marketingcloud.inappmessagingfeature/-in-app-message-manager/index.html). ::::::tabset{tabs='["SDK v11", "SDK v10", "SDK v8", "SDK v7"]'} :::::tab Use this code to register an event listener in version 11 of the SDK for Android. ```java // Set at configuration time SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { inAppMessagingFeatureModuleConfig = InAppMessagingFeatureConfig.builder().apply { setEventListener(object : InAppMessageManager.EventListener { override fun shouldShowMessage(message: InAppMessage): Boolean { return if (shouldShowMessage /* Your Custom logic confirming to show in-app message */) { true } else { // Store message id for later val blockedMessageId = message.id false } } override fun didShowMessage(message: InAppMessage) = Unit override fun didCloseMessage(message: InAppMessage, action: InAppMessageCloseAction) = Unit }) }.build() }) // Or set at anytime after configuration InAppMessagingFeature.requestSdk { inAppMessagingFeatureModule -> inAppMessagingFeatureModule.getInAppMessageManager().setInAppMessageListener(...) } ``` ::::: :::::tab Use this code to register an event listener in version 10 of the SDK for Android. ```java MarketingCloudSdk.requestSdk { engagementSdk -> engagementSdk.inAppMessageManager.setInAppMessageListener(object : InAppMessageManager.EventListener { override fun shouldShowMessage(message: InAppMessage): Boolean { return if (shouldShowMessage /* Your Custom logic confirming to show in-app message */) { true } else { // Store message id for later val blockedMessageId = message.id false } } override fun didShowMessage(message: InAppMessage) = Unit override fun didCloseMessage(message: InAppMessage) = Unit }) } ``` ::::: :::::tab Use this code to register an event listener in version 8 of the SDK for Android. ```java SFMCSdk.requestSdk { sdk -> sdk.mp { it.inAppMessageManager.setInAppMessageListener(object : InAppMessageManager.EventListener { override fun shouldShowMessage(message: InAppMessage): Boolean { return if (shouldShowMessage /* Your Custom logic confirming to show in-app message */) { true } else { // Store message id for later val blockedMessageId = message.id false } } override fun didShowMessage(message: InAppMessage) = Unit override fun didCloseMessage(message: InAppMessage) = Unit }) } } ``` ::::: :::::tab Use this code to register an event listener in version 7 of the SDK for Android. ```java MarketingCloudSdk.requestSdk { sdk -> sdk.inAppMessageManager.setInAppMessageListener(object : InAppMessageManager.EventListener { override fun shouldShowMessage(message: InAppMessage): Boolean { return if (shouldShowMessage /* Your Custom logic confirming to show in-app message */) { true } else { // Store message id for later val blockedMessageId = message.id() false } } override fun didShowMessage(message: InAppMessage) = Unit override fun didCloseMessage(message: InAppMessage) = Unit }) } ``` ::::: :::::: # Location Messages Location messaging enables you to deliver targeted notifications to users based on their physical location. Using geofences and Bluetooth beacons, you can trigger messages when users enter specific geographic areas or come near beacon devices, creating contextual and personalized mobile experiences. The Marketing Cloud SDK supports two types of location-based messaging: - **Geofence Messaging** - Trigger notifications when users cross virtual boundaries around geographic locations - **Beacon Messaging** - Trigger notifications when users come within proximity of Bluetooth beacon devices ## Key Features The SDK provides location messaging capabilities that include: - Caching geofence and beacon messages for offline delivery - Background location monitoring for geofence triggers - Proximity detection for beacon-based messaging - Message segmentation to show location messages to specific user subsets - Background refresh of location regions and messages - Debug logging for troubleshooting location features Location messaging requires user permission for location services and, for beacon messaging, Bluetooth permissions. Your Marketing Cloud Engagement admin must also enable your account with access to MobilePush and Location Services. ## Platform-Specific Implementation [Implement location messaging on iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_location_messages_ios.md) to enable geofence and beacon features, configure background location updates, and segment location messages based on user attributes or app state. [Implement location messaging on Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_location_messages_android.md) to add geofence and beacon support with the required dependencies, permissions, and SDK configuration for location-based notifications. # Location Messaging in Android Apps that Use SDK Version 10 The steps for implementing location messaging have changed in version 10 of the SDK. To upgrade your app to version 10 of the SDK, first [update the initialization code](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v10.md) -->. Then, use these code examples to update the location messaging code in your app. ## Enable Geofence Messaging During SDK Initialization Use this code example to enable geofence messaging during SDK initialization. ```kotlin SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { engagementModuleConfig = MarketingCloudConfig.builder().apply { // Other configuration values setGeofencingEnabled(true) // Enable Geofence messaging, default = false }.build(applicationContext) }) { // TODO handle initialization status } ``` ## Toggle Geofence Messaging at Runtime Use this code example to toggle geofence messaging at runtime. ```kotlin MarketingCloudSdk.requestSdk { //enable it.regionMessageManager.enableGeofenceMessaging() //disable it.regionMessageManager.disableGeofenceMessaging() } ``` # Location Messaging in iOS Apps that use SDK Version 10 The steps for implementing location messaging have changed in version 10 of the SDK. To upgrade your app to version 10 of the SDK, first [update the initialization code](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v10.md). Then, use these code examples to update the location messaging code in your app. ## Enable Location Tracking Use this code example to enable location tracking. This step is required to send geofence and beacon messages to your app. ```swift MarketingCloudSdk.requestSdk { mc in mc?.startWatchingLocation() } ``` ## Get Device Location This code example shows how to get the device’s last known location using version 10 of the SDK. ```swift MarketingCloudSdk.requestSdk { mc in let location = mc?.lastKnownLocation() } ``` ## Background Location Updates Implement the handler for background location updates in your application delegate class. This code example shows how to implement the handler using version 10 of the SDK. ```swift MarketingCloudSdk.requestSdk { mc in let location = mc?.lastKnownLocation() } ``` ## Segment Location Messages This code example shows how to implement location message segmentation using version 10 of the SDK. ```swift // Adopt the protocol in your app’s class, which implements the // sfmc_shouldShowLocationMessage:forRegion: method class AppDelegate: UIResponder, UIApplicationDelegate, LocationDelegate ... // After configuring the SDK, set the location delegate to the class that // implements the sfmc_shouldShowLocationMessage:forRegion: method MarketingCloudSdk.requestSdk { mc in mc?.setLocationDelegate(self) } // Implement the method to evaluate app logic to determine if a message should // be shown. This example uses MobilePush attributes and message custom keys to // implement simple matching logic. Your implementation will vary according to // your unique needs. func sfmc_shouldShowLocationMessage( _ message: [AnyHashable : Any], forRegion region: [AnyHashable : Any] ) -> Bool { var shouldShow = false var attributesLoyaltyLevel = "" // Get a MobilePush contact attribute previously set by your app from the SDK // In this example, "loyaltyLevel" indicates a customer contact value that // your app uses. var attributes: [AnyHashable : Any]? = nil MarketingCloudSdk.requestSdk { mc in attributes = mc?.attributes() } if attributes?.index(forKey: "loyaltyLevel") != nil { attributesLoyaltyLevel = attributes!["loyaltyLevel"] as! String } // get the custom key’s for this MobilePush Location message if (message["keys"] != nil) { let customKeys = message["keys"] as! [AnyHashable : Any] // get the "loyaltyLevel" custom key’s value let messageLoyaltyLevel = customKeys["loyaltyLevel"] as! String // in this example, if the customer contact attribute is set to "gold" // AND the message’s custom key is "gold", return true - this message // is valid to show for this customer // the SDK will display the location message, as the critera passed if (attributesLoyaltyLevel == "gold" && messageLoyaltyLevel == "gold") { shouldShow = true } } return shouldShow } ``` # LocationDelegate `Protocol` ## Declaration ```swift @objc(SFMCSdkLocationDelegate) public protocol LocationDelegate @objc func sfmc_shouldShowLocationMessage(_ message: [AnyHashable : Any], forRegion region: [AnyHashable : Any]) -> Bool ``` ## Cases ### `sfmc_shouldShowLocationMessage(_:forRegion:)` ```swift @objc func sfmc_shouldShowLocationMessage(_ message: [AnyHashable : Any], forRegion region: [AnyHashable : Any]) -> Bool ``` --- # Log SDK State Information To view information about the operational state of the SDK, use the `getSDKState()` method, as shown in these examples. ::::::tabset{tabs='["SDK v8+", "SDK v7"]'} :::::tab ```swift print("SDK State = (SFMCSdk.state())") ``` ::::: :::::tab ```swift print("SDK State = (MarketingCloudSDK.sharedInstance().sfmc_getSDKState()) ?? "SDK State is nil")") ``` ::::: :::::: The SDK outputs a status object, as shown in this example. ``` SDK State = { "Analytics Details" = { ETAnalyticsEnabled = 1; PIAnalyticsEnabled = 1; PiIdentifier = "Not Set"; useLegacyPiIdentifier = 1; }; "Inbox Details" = { "Count of All Inbox Messages in DB" = 0; "Count of Read Inbox Messages in DB" = 0; "Count of Unread Inbox Messages in DB" = 0; "Current Inbox Messages" = None; }; "Location General Information" = { "Beacon Monitoring Details" = { "Count of Proximity Messages in DB" = 0; "Proximity messages in local DB" = None; "Ranging for Beacons with UUID" = "(null)"; }; "Geo-fence Monitoring Details" = { "Count of Geo-fence Messages in DB" = 0; "Currently Monitoring Regions" = { }; "Geo-fence Entry messages in DB" = None; "Geo-fence Exit messages in DB" = None; "Regions in DB" = None; }; "Location Details" = { "Last Known Location" = { latitude = "0.0"; longitude = "0.0"; }; "Location Entitlement in place" = true; "User Location Authorization Status" = 0; "Watching Location" = 0; }; }; "MarketingCloudSDK General Information" = { "Application Name" = "SDKExplorer_Dev"; "Application Version" = "Version 216.0.0 (Build 2976)"; "Device Details" = { "Daylight Savings Time Active" = 0; "Device Locale" = "en_US"; "Device Reported Timezone" = "-18000"; DeviceId = "00000000-0000-0000-0000-000000000000"; "Hardware Description" = "iPhone9,4"; "OS Version" = "12.1.2"; "Platform Name" = iOS; }; "MarketingCloudSDK Configuration Details" = { "Current Configuration" = { accesstoken = 000000000000000000000000; appid = "00000000-0000-0000-0000-000000000000"; etanalytics = 1; inbox = 1; location = 1; name = "DEV"; pianalytics = 1; uselegacypiidentifier = 1; }; }; "MarketingCloudSDK Version" = "6.1.1.0"; "MarketingCloudSDKLocationDelegate" = "Not set"; "MarketingCloudSDKURLHandlingDelegate" = ""; "Push Information" = { "Developer has Push Enabled" = Yes; "Device Token" = 0000000000000000000000000000000000000000000000000000000000000000; "User has Push Enabled" = Yes; }; "Registration Details" = { "Current Registration" = { "app_version" = "216.0.0"; "device_token" = 0000000000000000000000000000000000000000000000000000000000000000; "deviceid" = "00000000-0000-0000-0000-000000000000"; "dst" = 0; "etappid" = "00000000-0000-0000-0000-000000000000"; "hwid" = "iPhone9,4"; "locale" = "en_US"; "location_enabled" = 0; "platform" = iOS; "platform_version" = "12.1.2"; "proximity_enabled" = 0; "push_enabled" = true; "sdk_version" = "6.1.1.0"; "tags" = ( ALL, DEBUG, iPhone ); timezone = "-18000"; }; "Date of Last Successful Registration" = None; "Last Successfully Sent Registration" = None; }; }; "Notifications Details" = { "Last Notification Received" = None; }; "Privacy Settings" = { "Privacy Mode" = SFMCPrivacyModeNotBlocked; }; "Retry Alarms Active" = ( MarketingCloudSDKControlChannel, SFMCRegistration ); } ``` # LogLevel **Package:** `com.salesforce.marketingcloud.sfmcsdk.components.logging` **Type:** `enum class` ## Description An enumeration defining log levels ordered from most to least permissive. Messages below the configured level are not logged. > "Some Android specific logging levels removed to create parity with iOS." ## Enum Values - **DEBUG** - Debug level - most verbose logging - **WARN** - Warning level - for potential issues - **ERROR** - Error level - for actual errors - **NONE** - No logging ## Properties ### entries ```kotlin val entries: EnumEntries ``` Returns a representation of an immutable list of all enum entries, in the order they're declared. ## Functions ### valueOf ```kotlin fun valueOf(value: String): LogLevel ``` Returns the enum constant of this type with the specified name. The string must match exactly an identifier used to declare an enum constant in this type. (Extraneous whitespace characters are not permitted.) ### values ```kotlin fun values(): Array ``` Returns an array containing the constants of this enum type, in the order they're declared. # LogLevel `Enumeration` Represents different logging levels for the extension SDK ## Declaration ```swift @objc(SFMCExtensionSdkLogLevel) public enum LogLevel : Int case debug case warn case error case fault case none ``` ## Cases ### `debug` Debug log level ```swift case debug ``` --- ### `warn` Warning log level ```swift case warn ``` --- ### `error` Error log level ```swift case error ``` --- ### `fault` Fault log level ```swift case fault ``` --- ### `none` Disabled log level ```swift case none ``` --- # LogListener Interface ## Package ```kotlin com.salesforce.marketingcloud.sfmcsdk.components.logging ``` ## Description Interface for receiving log messages. Implement this interface to handle log messages in a custom way. ## Platform **Target:** `androidJvm` --- ## Interface Definition ```kotlin interface LogListener ``` --- ## Functions ### out ```kotlin abstract fun out( level: LogLevel, tag: String, message: String, throwable: Throwable? ) ``` Called when a log message is generated. #### Parameters | Parameter | Type | Description | | ----------- | ------------ | --------------------------------------------- | | `level` | `LogLevel` | The severity level of the log message | | `tag` | `String` | A string identifier for the log source | | `message` | `String` | The log message content | | `throwable` | `Throwable?` | An optional exception associated with the log | --- ## Inheritors ### AndroidLogger ```kotlin open class AndroidLogger : LogListener ``` Default Android log listener that writes to LogCat. This is the default implementation used by the SDK. --- ## Usage Example To implement a custom log listener: ```kotlin class CustomLogListener : LogListener { override fun out( level: LogLevel, tag: String, message: String, throwable: Throwable? ) { // Custom logging implementation // e.g., write to file, send to remote server, etc. } } ``` # LogOutputter `Class` Defines how logs are being outputted. ## Declaration ```swift @objc(SFMCSdkLogOutputter) open class LogOutputter : NSObject @objc open func out(level: LogLevel, subsystem: String, category: LoggerCategory, message: String) ``` ## Cases ### `out(level:subsystem:category:message:)` Captures logs using the native unified logging system (log level must be defined as OSLogType) ```swift @objc open func out(level: LogLevel, subsystem: String, category: LoggerCategory, message: String) ``` --- # logSdkState Instructs the native SDK to log the SDK state to the native logging system (Logcat for Android and Xcode or Console for iOS). If you contact Salesforce Support for help, you must provide a copy of the SDK state logs. **note:** This method is available in MobilePush SDK version 6.3.1 and later. ## Syntax `MCCordovaPlugin.logSdkState([successCallback], [errorCallback])` ## Kind Static method of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | ----------------- | ---------- | ----------- | | `successCallback` | `function` | | | `errorCallback` | `function` | | # logSdkState Logs the current state of the SDK for debugging purposes. ## Syntax ```dart Future logSdkState() ``` ## Returns - `Future` - Completes when the SDK state has been logged. ## Example ```dart try { await SfmcSdk.logSdkState(); print('SDK state logged to console'); } catch (e) { print('Failed to log SDK state: $e'); } ``` ## Notes - This method is useful for debugging and troubleshooting SDK issues. - The logged information includes device registration status, contact key, attributes, and tags. ## Related Methods - [enableLogging()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_enableLogging.md) - [disableLogging()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_disableLogging.md) # logSdkState Instructs the native SDK to log the SDK state to the native logging system (Logcat for Android and Xcode or Console for iOS). The Engagement Support team requests for the SDK state logs during support calls as they can help diagnose most issues. ## Syntax ```javascript MCReactModule.logSdkState(); ``` ## Returns - `void` - No return value. ## Example ```javascript import { MCReactModule } from "react-native-marketingcloudsdk"; const logCurrentSDKState = () => { try { MCReactModule.logSdkState(); console.log("SDK state logged to native logging system"); } catch (error) { console.error("Error logging SDK state:", error); } }; ``` ## See Also - [enableLogging() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_enableLogging.md) - [disableLogging() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_disableLogging.md) # MAM Core Module (Mobile App Messaging) Mobile App Messaging SDK for registration, analytics, and in-app messages ## API Reference ### [Classes](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/mam-core_classes_index.md) 2 classes # Manage Tags Use the Salesforce Engagement SDK to add or remove tags. Tags can’t be empty or `null`. The SDK trims whitespace from the beginning and end of the tag. ::::::tabset{tabs='["Android v10+", "iOS v10+", "Android v8", "iOS v8"]'} :::::tab This code example shows how to add or remove tags in the SDK for Android version 10 or later. ```java MarketingCloudSdk.requestSdk { engagementSdk -> // GIVEN val tagsToAdd: List = getTagsToAdd() val tagsToRemove: List = getTagsToRemove() engagementSdk.registrationManager.edit().run { // Adding Tags addTags("tag1") addTags("tag2", "tag3") addTags(tagsToAdd) // Removing Tags removeTags("tag1") removeTags("tag2", "tag3") removeTags(tagsToRemove) clearTags() // Commit changes commit() } // Getting Tags val tags = engagementSdk.registrationManager.tags } ``` ::::: :::::tab This code example shows how to add or remove tags in the SDK for iOS version 10 or later. ```swift MarketingCloudSdk.requestSdk { mc in // Add a tag mc?.addTag("Hiking Supplies") // Remove a tag mc?.removeTag("Boating Gear") // Get all tags let tags = mc?.tags() } ``` ::::: :::::tab This code example shows how to add or remove tags in the SDK for Android version 8. ```java SFMCSdk.requestSdk { sdk -> // GIVEN val tagsToAdd: List = getTagsToAdd() val tagsToRemove: List = getTagsToRemove() sdk.mp { it.registrationManager.edit().run { // Adding Tags addTags("tag1", "tag2", "tag3") addTags(tagsToAdd) // Removing Tags removeTags("tag1", "tag2") removeTags(tagsToRemove) clearTags() // Commit changes commit() } // Getting Tags val tags = it.registrationManager.tags } } ``` ::::: :::::tab This code example shows how to add or remove tags on earlier versions of the SDK for iOS. ```swift SFMCSdk.requestPushSdk { mp in // Add a tag mp.addTag("Hiking Supplies") // Remove a tag mp.removeTag("Boating Gear") // Get all tags let tags = mp.tags() } ``` ::::: :::::: # markAllMessagesDeleted Marks all inbox messages as deleted. ## Syntax ```dart Future markAllMessagesDeleted() ``` ## Returns - `Future` - Completes when all messages have been marked as deleted. ## Example ```dart try { await SfmcSdk.markAllMessagesDeleted(); print('All messages marked as deleted'); } catch (e) { print('Failed to mark all messages as deleted: $e'); } ``` ## Related Methods - [deleteMessage()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_deleteMessage.md) - [markAllMessagesRead()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_markAllMessagesRead.md) # markAllMessagesRead Marks all inbox messages as read. ## Syntax ```dart Future markAllMessagesRead() ``` ## Returns - `Future` - Completes when all messages have been marked as read. ## Example ```dart try { await SfmcSdk.markAllMessagesRead(); print('All messages marked as read'); } catch (e) { print('Failed to mark all messages as read: $e'); } ``` ## Related Methods - [setMessageRead()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_setMessageRead.md) - [markAllMessagesDeleted()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_markAllMessagesDeleted.md) # Marketing Cloud Engagement SDK This section provides API reference details for the Marketing Cloud Engagement SDK module in the Flutter unified plugin. ## refreshInbox Requests an updated list of inbox messages from the Marketing Cloud servers. ### Syntax ```dart MarketingCloudSdk.refreshInbox(); ``` ### Returns - `Future` - Indicates whether the refresh request succeeded. ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); final refreshed = await MarketingCloudSdk.refreshInbox(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/refresh-inbox.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)refreshMessages>) ## getAllMessages Retrieves all active inbox messages, including read and unread messages. Doesn't retrieve deleted inbox messages. ### Syntax ```dart MarketingCloudSdk.getAllMessages(); ``` ### Returns - `Future>` - A future that completes with the list of inbox messages. ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); final messages = await MarketingCloudSdk.getAllMessages(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/get-messages.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)getAllMessages>) ## getUnreadMessages Retrieves all active, unread inbox messages. Doesn't retrieve deleted inbox messages. ### Syntax ```dart MarketingCloudSdk.getUnreadMessages(); ``` ### Returns - `Future>` - A future that completes with the list of unread inbox messages. ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); final messages = await MarketingCloudSdk.getUnreadMessages(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/get-unread-messages.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)getUnreadMessages>) ## getReadMessages Retrieves all active, read inbox messages. Doesn't retrieve unread inbox messages. ### Syntax ```dart MarketingCloudSdk.getReadMessages(); ``` ### Returns - `Future>` - A future that completes with the list of read inbox messages. ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); final messages = await MarketingCloudSdk.getReadMessages(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/get-read-messages.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)getReadMessages>) ## getDeletedMessages Retrieves all active, deleted inbox messages. ### Syntax ```dart MarketingCloudSdk.getDeletedMessages(); ``` ### Returns - `Future>` - A future that completes with the list of deleted inbox messages. ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); final messages = await MarketingCloudSdk.getDeletedMessages(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/get-deleted-messages.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)getDeletedMessages>) ## getMessageCount Retrieves the total number of inbox messages, excluding deleted messages. ### Syntax ```dart MarketingCloudSdk.getMessageCount(); ``` ### Returns - `Future` - A future that completes with the total inbox message count. ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); final count = await MarketingCloudSdk.getMessageCount(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/get-message-count.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)getAllMessagesCount>) ## getUnreadMessageCount Retrieves the total number of unread inbox messages, excluding deleted messages. ### Syntax ```dart MarketingCloudSdk.getUnreadMessageCount(); ``` ### Returns - `Future` - A future that completes with the unread inbox message count. ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); final count = await MarketingCloudSdk.getUnreadMessageCount(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/get-unread-message-count.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)getUnreadMessagesCount>) ## getReadMessageCount Retrieves the total number of read inbox messages, excluding deleted messages. ### Syntax ```dart MarketingCloudSdk.getReadMessageCount(); ``` ### Returns - `Future` - A future that completes with the read inbox message count. ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); final count = await MarketingCloudSdk.getReadMessageCount(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/get-read-message-count.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)getReadMessagesCount>) ## getDeletedMessageCount Retrieves the total number of deleted inbox messages. ### Syntax ```dart MarketingCloudSdk.getDeletedMessageCount(); ``` ### Returns - `Future` - A future that completes with the deleted inbox message count. ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); final count = await MarketingCloudSdk.getDeletedMessageCount(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/get-deleted-message-count.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)getDeletedMessagesCount>) ## markMessageRead Marks an inbox message as read in local storage. ### Syntax ```dart MarketingCloudSdk.markMessageRead(id); ``` ### Parameters | Parameter | Type | Description | | --------- | -------- | -------------------------------------------- | | `id` | `String` | The ID of the inbox message to mark as read. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); await MarketingCloudSdk.markMessageRead('message-id-123'); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/set-message-read.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)markMessageWithIdReadWithMessageId:>) ## markMessageDeleted Marks an inbox message as deleted in local storage. ### Syntax ```dart MarketingCloudSdk.markMessageDeleted(id); ``` ### Parameters | Parameter | Type | Description | | --------- | -------- | ----------------------------------------------- | | `id` | `String` | The ID of the inbox message to mark as deleted. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); await MarketingCloudSdk.markMessageDeleted('message-id-123'); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/delete-message.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)markMessageWithIdDeletedWithMessageId:>) ## markAllMessagesRead Marks all active, unread inbox messages as read. ### Syntax ```dart MarketingCloudSdk.markAllMessagesRead(); ``` ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); await MarketingCloudSdk.markAllMessagesRead(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/mark-all-messages-read.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)markAllMessagesRead>) ## markAllMessagesDeleted Marks all active inbox messages as deleted. ### Syntax ```dart MarketingCloudSdk.markAllMessagesDeleted(); ``` ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); await MarketingCloudSdk.markAllMessagesDeleted(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/mark-all-messages-deleted.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)markAllMessagesDeleted>) ## trackInboxMessageOpened Tracks the opening of an inbox message for analytics. ### Syntax ```dart MarketingCloudSdk.trackInboxMessageOpened(id); ``` ### Parameters | Parameter | Type | Description | | --------- | -------- | -------------------------------------------- | | `id` | `String` | The ID of the inbox message that was opened. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); await MarketingCloudSdk.trackInboxMessageOpened('message-id-123'); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.analytics/-analytics-manager/track-inbox-open-event.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)trackMessageOpened:>) ## addTag Adds a tag to the list of tags in the registration. ### Syntax ```dart MarketingCloudSdk.addTag(tag); ``` ### Parameters | Parameter | Type | Description | | --------- | -------- | --------------- | | `tag` | `String` | The tag to add. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); await MarketingCloudSdk.addTag('vip-customer'); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.registration/-registration-manager/-editor/add-tag.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)addTag:>) ## addTags Adds multiple tags to the list of tags in the registration. ### Syntax ```dart MarketingCloudSdk.addTags(tags); ``` ### Parameters | Parameter | Type | Description | | --------- | -------------- | ------------------------ | | `tags` | `List` | The list of tags to add. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); await MarketingCloudSdk.addTags(['vip-customer', 'newsletter-subscriber']); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.registration/-registration-manager/-editor/add-tags.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)addTags:>) ## removeTag Removes a tag from the list of tags in the registration. ### Syntax ```dart MarketingCloudSdk.removeTag(tag); ``` ### Parameters | Parameter | Type | Description | | --------- | -------- | ------------------ | | `tag` | `String` | The tag to remove. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); await MarketingCloudSdk.removeTag('vip-customer'); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.registration/-registration-manager/-editor/remove-tag.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)removeTag:>) ## removeTags Removes multiple tags from the list of tags in the registration. ### Syntax ```dart MarketingCloudSdk.removeTags(tags); ``` ### Parameters | Parameter | Type | Description | | --------- | -------------- | --------------------------- | | `tags` | `List` | The list of tags to remove. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); await MarketingCloudSdk.removeTags(['vip-customer', 'newsletter-subscriber']); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.registration/-registration-manager/-editor/remove-tags.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)removeTag:>) ## getTags Returns the tags currently set on the device. ### Syntax ```dart MarketingCloudSdk.getTags(); ``` ### Returns - `Future?>` - A future that completes with the list of tags currently set on the device. ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); final tags = await MarketingCloudSdk.getTags(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.registration/-registration-manager/get-tags.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)tags>) ## getAttributes Returns a map of attributes set in the registration. This method is deprecated. Use `SFMCSdkModule.getAttributes` from `sfmc_core` instead. `SFMCSdkModule.getAttributes` coerces null attribute values to an empty string (`''`) rather than the literal string `"null"`. ### Syntax ```dart MarketingCloudSdk.getAttributes(); ``` ### Returns - `Future?>` - A future that completes with the map of attributes set in the registration. ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); final attributes = await MarketingCloudSdk.getAttributes(); ``` ## getDeviceId Returns the device ID that Marketing Cloud uses to send push messages to the device. ### Syntax ```dart MarketingCloudSdk.getDeviceId(); ``` ### Returns - `Future` - A future that completes with the device ID. ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); final deviceId = await MarketingCloudSdk.getDeviceId(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.registration/-registration-manager/get-device-id.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)deviceIdentifier>) ## getContactKey Returns the contact key for the device. This method is deprecated. Use `SFMCSdkModule.getProfileId` from `sfmc_core` instead. ### Syntax ```dart MarketingCloudSdk.getContactKey(); ``` ### Returns - `Future` - A future that completes with the contact key currently set on the device. ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); final contactKey = await MarketingCloudSdk.getContactKey(); ``` ## setSignedString Sets the signed string for device/contact authentication. The signed string is typically a JWT used to authenticate the device or contact, and this feature must be enabled on the Marketing Cloud account. ### Syntax ```dart MarketingCloudSdk.setSignedString(signedString); ``` ### Parameters | Parameter | Type | Description | | -------------- | --------- | --------------------------------------------------------- | | `signedString` | `String?` | The signed string to set. Pass `null` to clear the value. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); await MarketingCloudSdk.setSignedString('eyJhbGciOiJIUzI1NiJ9...'); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.registration/-registration-manager/-editor/set-signed-string.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)setSignedString:>) ## getSignedString Returns the signed string for the device. The signed string is usually a JWT used to authenticate the device or contact. If no signed string is set, this method returns `null`. ### Syntax ```dart MarketingCloudSdk.getSignedString(); ``` ### Returns - `Future` - A future that completes with the signed string, or `null` if no signed string is set. ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); final signedString = await MarketingCloudSdk.getSignedString(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.registration/-registration-manager/get-signed-string.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)signedString>) ## enablePiAnalytics Enables Predictive Intelligence analytics in the Marketing Cloud SDK. ### Syntax ```dart MarketingCloudSdk.enablePiAnalytics(); ``` ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); await MarketingCloudSdk.enablePiAnalytics(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.analytics/-analytics-manager/enable-pi-analytics.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)setPiAnalyticsEnabled:>) ## disablePiAnalytics Disables Predictive Intelligence analytics in the Marketing Cloud SDK. ### Syntax ```dart MarketingCloudSdk.disablePiAnalytics(); ``` ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); await MarketingCloudSdk.disablePiAnalytics(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.analytics/-analytics-manager/disable-pi-analytics.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)setPiAnalyticsEnabled:>) ## isPiAnalyticsEnabled Checks if Predictive Intelligence analytics is enabled. ### Syntax ```dart MarketingCloudSdk.isPiAnalyticsEnabled(); ``` ### Returns - `Future` - Indicates whether Predictive Intelligence analytics is enabled. ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); final enabled = await MarketingCloudSdk.isPiAnalyticsEnabled(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.analytics/-analytics-manager/are-pi-analytics-enabled.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)isPiAnalyticsEnabled>) ## enableAnalytics Enables analytics in the Marketing Cloud SDK. ### Syntax ```dart MarketingCloudSdk.enableAnalytics(); ``` ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); await MarketingCloudSdk.enableAnalytics(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.analytics/-analytics-manager/enable-analytics.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)setAnalyticsEnabled:>) ## disableAnalytics Disables analytics in the Marketing Cloud SDK. ### Syntax ```dart MarketingCloudSdk.disableAnalytics(); ``` ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); await MarketingCloudSdk.disableAnalytics(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.analytics/-analytics-manager/disable-analytics.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)setAnalyticsEnabled:>) ## isAnalyticsEnabled Checks if analytics is enabled in the Marketing Cloud SDK. ### Syntax ```dart MarketingCloudSdk.isAnalyticsEnabled(); ``` ### Returns - `Future` - Indicates whether analytics is enabled. ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); final enabled = await MarketingCloudSdk.isAnalyticsEnabled(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.analytics/-analytics-manager/are-analytics-enabled.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)isAnalyticsEnabled>) ## enableLogging Enables verbose logging within the native Marketing Cloud SDK. ### Syntax ```dart MarketingCloudSdk.enableLogging(); ``` ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); await MarketingCloudSdk.enableLogging(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.logging/-log-level/index.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)setDebugLoggingEnabled:>) ## disableLogging Disables verbose logging within the native Marketing Cloud SDK. ### Syntax ```dart MarketingCloudSdk.disableLogging(); ``` ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); await MarketingCloudSdk.disableLogging(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.logging/-log-level/index.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)setDebugLoggingEnabled:>) ## setRegistrationCallback Registers a callback to receive registration change events from the SDK. ### Syntax ```dart MarketingCloudSdk.setRegistrationCallback(); ``` ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); await MarketingCloudSdk.setRegistrationCallback(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.registration/-registration-manager/register-for-registration-events.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)setRegistrationCallback:>) ## unsetRegistrationCallback Unregisters the registration change callback. ### Syntax ```dart MarketingCloudSdk.unsetRegistrationCallback(); ``` ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); await MarketingCloudSdk.unsetRegistrationCallback(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.registration/-registration-manager/unregister-for-registration-events.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)unsetRegistrationCallback>) ## registrationEvents A broadcast stream of registration events. Emits a map that contains registration data when the registration changes. ### Syntax ```dart MarketingCloudSdk.registrationEvents; ``` ### Returns - `Stream>` - A broadcast stream that emits a map of registration data when the registration changes. ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); MarketingCloudSdk.registrationEvents.listen((event) { print('Registration changed: $event'); }); ``` ## registerInboxResponseListener Registers a listener for inbox message changes. ### Syntax ```dart MarketingCloudSdk.registerInboxResponseListener(listener); ``` ### Parameters | Parameter | Type | Description | | ---------- | ----------------------- | --------------------------------------------------- | | `listener` | `InboxResponseListener` | The callback invoked when an inbox message changes. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); void onInboxChanged(List messages) { print('Inbox changed: ${messages.length} messages'); } await MarketingCloudSdk.registerInboxResponseListener(onInboxChanged); ``` ## unregisterInboxResponseListener Unregisters a previously registered inbox response listener. ### Syntax ```dart MarketingCloudSdk.unregisterInboxResponseListener(listener); ``` ### Parameters | Parameter | Type | Description | | ---------- | ----------------------- | ----------------------- | | `listener` | `InboxResponseListener` | The callback to remove. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); void onInboxChanged(List messages) { print('Inbox changed: ${messages.length} messages'); } await MarketingCloudSdk.registerInboxResponseListener(onInboxChanged); await MarketingCloudSdk.unregisterInboxResponseListener(onInboxChanged); ``` ## enableLocation Enables the location (geofence) feature at runtime. In iOS apps, flips the developer override on `MarketingCloudSdk`. In Android apps, enables geofence messaging using `RegionMessageManager`. Request the required OS location permissions before you call this method. ### Syntax ```dart MarketingCloudSdk.enableLocation(); ``` ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); await MarketingCloudSdk.enableLocation(); final enabled = await MarketingCloudSdk.isLocationEnabled(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages/-region-message-manager/enable-geofence-messaging.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)setLocationEnabled:>) ## disableLocation Disables the location (geofence) feature at runtime. In iOS apps, flips the developer override on `MarketingCloudSdk`. In Android apps, disables geofence messaging using `RegionMessageManager`. ### Syntax ```dart MarketingCloudSdk.disableLocation(); ``` ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); await MarketingCloudSdk.disableLocation(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages/-region-message-manager/disable-geofence-messaging.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)setLocationEnabled:>) ## isLocationEnabled Reports whether the location, or the geofence feature, is enabled. ### Syntax ```dart MarketingCloudSdk.isLocationEnabled(); ``` ### Returns - `Future` - Indicates whether the location (geofence) feature is enabled. ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); final enabled = await MarketingCloudSdk.isLocationEnabled(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages/-region-message-manager/is-geofence-messaging-enabled.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)isLocationEnabled>) ## startWatchingLocation In iOS apps, starts tracking the coordinates of an app user. In Android apps, geofence transitions are driven by `enableLocation` and `disableLocation`. ### Syntax ```dart MarketingCloudSdk.startWatchingLocation(); ``` ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); await MarketingCloudSdk.startWatchingLocation(); ``` ### See Also - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)startWatchingLocation>) ## stopWatchingLocation In iOS apps, stops tracking the app user's location. ### Syntax ```dart MarketingCloudSdk.stopWatchingLocation(); ``` ### Returns - `Future` ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); await MarketingCloudSdk.stopWatchingLocation(); ``` ### See Also - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)stopWatchingLocation>) ## isWatchingLocation In iOS apps, reports whether the SDK actively watches the app user's location. In Android apps, always returns `false`. ### Syntax ```dart MarketingCloudSdk.isWatchingLocation(); ``` ### Returns - `Future` - Indicates whether the SDK is actively watching the app user's location. ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); final watching = await MarketingCloudSdk.isWatchingLocation(); ``` ### See Also - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)watchingLocation>) ## getLastKnownLocation Returns the last known device location as reported by the native SDK. iOS returns a raw `[String: String]` dictionary, which usually includes `latitude` and `longitude` keys. Returns `null` when the app hasn't captured any data. Always returns `null` in Android apps. ### Syntax ```dart MarketingCloudSdk.getLastKnownLocation(); ``` ### Returns - `Future?>` - A future that completes with the last known location, or `null` if unavailable. ### Example ```dart import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; await MarketingCloudSdk.requestSdk(); final location = await MarketingCloudSdk.getLastKnownLocation(); if (location != null) { final lat = location['latitude']; final lng = location['longitude']; debugPrint('Last known: $lat, $lng'); } ``` ### See Also - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)lastKnownLocation>) ## enableProximityMessaging In Android apps, enables proximity (beacon) messaging and requires `ACCESS_FINE_LOCATION` and `ACCESS_BACKGROUND_LOCATION`. ### Syntax ```dart MarketingCloudSdk.enableProximityMessaging(); ``` ### Returns - `Future` # Marketing Cloud Engagement SDK This section provides API reference details for the Marketing Cloud Engagement SDK module in React Native unified plugin. ## refreshInbox Requests an updated list of inbox messages from the Marketing Cloud servers. ### Syntax ```javascript MarketingCloudEngagementSdkModule.refreshInbox(); ``` ### Returns - `Promise` - Indicates whether the refresh request succeeded. ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); await mc.refreshInbox(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/refresh-inbox.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)refreshMessages>) ## getAllMessages Retrieves active inbox messages, including read and unread messages that are not deleted. ### Syntax ```javascript MarketingCloudEngagementSdkModule.getAllMessages(); ``` ### Returns - `Promise` - A promise that resolves to the array of inbox messages. ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi, InboxMessage } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); const allMsgs: InboxMessage[] = await mc.getAllMessages(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/get-messages.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)getAllMessages>) ## getUnreadMessages Retrieves active unread inbox messages that are not deleted. ### Syntax ```javascript MarketingCloudEngagementSdkModule.getUnreadMessages(); ``` ### Returns - `Promise` - A promise that resolves to unread inbox messages. ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi, InboxMessage } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); const unreadMsgs: InboxMessage[] = await mc.getUnreadMessages(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/get-unread-messages.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)getUnreadMessages>) ## getReadMessages Retrieves active read inbox messages that are not deleted. ### Syntax ```javascript MarketingCloudEngagementSdkModule.getReadMessages(); ``` ### Returns - `Promise` - A promise that resolves to read inbox messages. ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi, InboxMessage } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); const readMsgs: InboxMessage[] = await mc.getReadMessages(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/get-read-messages.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)getReadMessages>) ## getDeletedMessages Retrieves active deleted inbox messages. ### Syntax ```javascript MarketingCloudEngagementSdkModule.getDeletedMessages(); ``` ### Returns - `Promise` - A promise that resolves to deleted inbox messages. ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi, InboxMessage } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); const deletedMsgs: InboxMessage[] = await mc.getDeletedMessages(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/get-deleted-messages.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)getDeletedMessages>) ## getMessageCount Retrieves the total number of inbox messages that are not deleted. ### Syntax ```javascript MarketingCloudEngagementSdkModule.getMessageCount(); ``` ### Returns - `Promise` - A promise that resolves to the message count. ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); const totalCount = await mc.getMessageCount(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/get-message-count.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)getAllMessagesCount>) ## getUnreadMessageCount Retrieves the total number of unread inbox messages that are not deleted. ### Syntax ```javascript MarketingCloudEngagementSdkModule.getUnreadMessageCount(); ``` ### Returns - `Promise` - A promise that resolves to the unread message count. ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); const unreadCount = await mc.getUnreadMessageCount(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/get-unread-message-count.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)getUnreadMessagesCount>) ## getReadMessageCount Retrieves the total number of read inbox messages that are not deleted. ### Syntax ```javascript MarketingCloudEngagementSdkModule.getReadMessageCount(); ``` ### Returns - `Promise` - A promise that resolves to the read message count. ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); const readCount = await mc.getReadMessageCount(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/get-read-message-count.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)getReadMessagesCount>) ## getDeletedMessageCount Retrieves the total number of deleted inbox messages. ### Syntax ```javascript MarketingCloudEngagementSdkModule.getDeletedMessageCount(); ``` ### Returns - `Promise` - A promise that resolves to the deleted message count. ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); const deletedCount = await mc.getDeletedMessageCount(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/get-deleted-message-count.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)getDeletedMessagesCount>) ## markMessageRead Marks an inbox message as read in local storage. ### Syntax ```javascript MarketingCloudEngagementSdkModule.markMessageRead(messageId); ``` ### Parameters | Parameter | Type | Description | | ----------- | -------- | ------------------------------------- | | `messageId` | `string` | The inbox message ID to mark as read. | ### Returns - `void` ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); mc.markMessageRead("message-id"); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/set-message-read.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)markMessageWithIdReadWithMessageId:>) ## markMessageDeleted Marks an inbox message as deleted in local storage. ### Syntax ```javascript MarketingCloudEngagementSdkModule.markMessageDeleted(messageId); ``` ### Parameters | Parameter | Type | Description | | ----------- | -------- | ---------------------------------------- | | `messageId` | `string` | The inbox message ID to mark as deleted. | ### Returns - `void` ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); mc.markMessageDeleted("message-id"); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/delete-message.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)markMessageWithIdDeletedWithMessageId:>) ## markAllMessagesRead Marks all active unread inbox messages as read. ### Syntax ```javascript MarketingCloudEngagementSdkModule.markAllMessagesRead(); ``` ### Returns - `void` ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); mc.markAllMessagesRead(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/mark-all-messages-read.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)markAllMessagesRead>) ## markAllMessagesDeleted Marks all active inbox messages as deleted. ### Syntax ```javascript MarketingCloudEngagementSdkModule.markAllMessagesDeleted(); ``` ### Returns - `void` ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); mc.markAllMessagesDeleted(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/mark-all-messages-deleted.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)markAllMessagesDeleted>) ## trackInboxMessageOpened Tracks an inbox message-open event for analytics. ### Syntax ```javascript MarketingCloudEngagementSdkModule.trackInboxMessageOpened(message); ``` ### Parameters | Parameter | Type | Description | | --------- | -------------- | -------------------------------------------------------------------------------------------- | | `message` | `InboxMessage` | The inbox message to track as opened. Include the message object returned by the inbox APIs. | ### Returns - `void` ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi, InboxMessage } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); const message: InboxMessage = { id: "message-id", read: false, deleted: false }; mc.trackInboxMessageOpened(message); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.analytics/-analytics-manager/track-inbox-open-event.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)trackMessageOpened:>) ## addTag Adds a tag to the registration tag list. ### Syntax ```javascript MarketingCloudEngagementSdkModule.addTag(tag); ``` ### Parameters | Parameter | Type | Description | | --------- | -------- | -------------------------------------------------------------------------------------------------------- | | `tag` | `string` | The tag to add to the registration tag list. Use a meaningful segmentation value, such as `beta-tester`. | ### Returns - `void` ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); mc.addTag("beta-tester"); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.registration/-registration-manager/-editor/add-tag.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)addTag:>) ## addTags Adds multiple tags to the registration tag list. ### Syntax ```javascript MarketingCloudEngagementSdkModule.addTags(tags); ``` ### Parameters | Parameter | Type | Description | | --------- | ---------- | -------------------------------------------------------------------------------------------- | | `tags` | `string[]` | The tags to add to the registration tag list. Each array value is a segmentation tag string. | ### Returns - `void` ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); mc.addTags(["beta-tester", "vip-user"]); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.registration/-registration-manager/-editor/add-tags.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)addTags:>) ## removeTag Removes a tag from the registration tag list. ### Syntax ```javascript MarketingCloudEngagementSdkModule.removeTag(tag); ``` ### Parameters | Parameter | Type | Description | | --------- | -------- | ------------------------------------------------------------------------------------------------ | | `tag` | `string` | The tag to remove from the registration tag list. Use the exact tag value that is currently set. | ### Returns - `void` ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); mc.removeTag("beta-tester"); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.registration/-registration-manager/-editor/remove-tag.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)removeTag:>) ## removeTags Removes multiple tags from the registration tag list. ### Syntax ```javascript MarketingCloudEngagementSdkModule.removeTags(tags); ``` ### Parameters | Parameter | Type | Description | | --------- | ---------- | --------------------------------------------------------------------------------------------------- | | `tags` | `string[]` | The tags to remove from the registration tag list. Each array value must match a currently set tag. | ### Returns - `void` ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); mc.removeTags(["beta-tester", "vip-user"]); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.registration/-registration-manager/-editor/remove-tags.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)removeTag:>) ## getTags Returns the tags currently set on the device. ### Syntax ```javascript MarketingCloudEngagementSdkModule.getTags(); ``` ### Returns - `Promise` - A promise that resolves to tags currently set in the native SDK. ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); const tags = await mc.getTags(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.registration/-registration-manager/get-tags.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)tags>) ## getAttributes Returns all attributes currently set in the device registration profile. ### Syntax ```javascript MarketingCloudEngagementSdkModule.getAttributes(); ``` ### Parameters None. ### Returns - `Promise` - Object containing all attributes. ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); const attributes = await mc.getAttributes(); ``` ## enablePiAnalytics Enables Predictive Intelligence analytics in the Marketing Cloud SDK. ### Syntax ```javascript MarketingCloudEngagementSdkModule.enablePiAnalytics(); ``` ### Returns - `void` ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); mc.enablePiAnalytics(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.analytics/-analytics-manager/enable-pi-analytics.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)setPiAnalyticsEnabled:>) ## disablePiAnalytics Disables Predictive Intelligence analytics in the Marketing Cloud SDK. ### Syntax ```javascript MarketingCloudEngagementSdkModule.disablePiAnalytics(); ``` ### Returns - `void` ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); mc.disablePiAnalytics(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.analytics/-analytics-manager/disable-pi-analytics.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)setPiAnalyticsEnabled:>) ## isPiAnalyticsEnabled Checks whether Predictive Intelligence analytics is enabled. ### Syntax ```javascript MarketingCloudEngagementSdkModule.isPiAnalyticsEnabled(); ``` ### Returns - `Promise` - A promise that resolves to whether PI analytics is enabled. ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); const piEnabled = await mc.isPiAnalyticsEnabled(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.analytics/-analytics-manager/are-pi-analytics-enabled.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)isPiAnalyticsEnabled>) ## enableAnalytics Enables analytics in the Marketing Cloud SDK. ### Syntax ```javascript MarketingCloudEngagementSdkModule.enableAnalytics(); ``` ### Returns - `void` ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); mc.enableAnalytics(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.analytics/-analytics-manager/enable-analytics.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)setAnalyticsEnabled:>) ## disableAnalytics Disables analytics in the Marketing Cloud SDK. ### Syntax ```javascript MarketingCloudEngagementSdkModule.disableAnalytics(); ``` ### Returns - `void` ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); mc.disableAnalytics(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.analytics/-analytics-manager/disable-analytics.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)setAnalyticsEnabled:>) ## isAnalyticsEnabled Checks whether analytics is enabled in the Marketing Cloud SDK. ### Syntax ```javascript MarketingCloudEngagementSdkModule.isAnalyticsEnabled(); ``` ### Returns - `Promise` - A promise that resolves to whether analytics is enabled. ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); const analyticsEnabled = await mc.isAnalyticsEnabled(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.analytics/-analytics-manager/are-analytics-enabled.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)isAnalyticsEnabled>) ## getDeviceId Returns the device ID that Marketing Cloud uses for push messaging. ### Syntax ```javascript MarketingCloudEngagementSdkModule.getDeviceId(); ``` ### Returns - `Promise` - A promise that resolves to the device ID, or `null`. ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); const deviceId = await mc.getDeviceId(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.registration/-registration-manager/get-device-id.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)deviceIdentifier>) ## getContactKey Returns the contact key currently set for the device user. ### Syntax ```javascript MarketingCloudEngagementSdkModule.getContactKey(); ``` ### Parameters None. ### Returns - `Promise` - Contact key, or `null`. ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); const contactKey = await mc.getContactKey(); ``` ## enableLogging Enables verbose logging in the native Marketing Cloud SDK. ### Syntax ```javascript MarketingCloudEngagementSdkModule.enableLogging(); ``` ### Returns - `void` ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); mc.enableLogging(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.logging/-log-level/index.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)setDebugLoggingEnabled:>) ## disableLogging Disables verbose logging in the native Marketing Cloud SDK. ### Syntax ```javascript MarketingCloudEngagementSdkModule.disableLogging(); ``` ### Returns - `void` ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); mc.disableLogging(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.logging/-log-level/index.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)setDebugLoggingEnabled:>) ## setRegistrationCallback Registers a callback to receive registration change events from the SDK. ### Syntax ```javascript MarketingCloudEngagementSdkModule.setRegistrationCallback(); ``` ### Returns - `void` ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); mc.setRegistrationCallback(); const sub = MarketingCloudSdkModule.getEmitter().addListener( "sfmc_mc_registration", (registration) => { console.log("MC registration changed:", registration); }, ); sub.remove(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.registration/-registration-manager/register-for-registration-events.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)setRegistrationCallback:>) ## unsetRegistrationCallback Unregisters the registration change callback. ### Syntax ```javascript MarketingCloudEngagementSdkModule.unsetRegistrationCallback(); ``` ### Returns - `void` ### Example ```javascript import { MarketingCloudSdkModule } from "@sfmc/react-native-marketingcloudsdk"; import type { MCApi } from "@sfmc/react-native-marketingcloudsdk"; const mc: MCApi = await MarketingCloudSdkModule.requestSdk(); mc.unsetRegistrationCallback(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.registration/-registration-manager/unregister-for-registration-events.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MarketingCloudSdk/11.0/Classes/MarketingCloudSdk.html#/c:@CM@MarketingCloudSDK@objc(cs)SFMarketingCloudSdk(im)unsetRegistrationCallback>) # Marketing Cloud Mobile App Messaging SDK This section provides API reference details for the Marketing Cloud Next (Mobile App Messaging) SDK module in the Flutter unified plugin. ## getDeviceId Returns the device ID that Marketing Cloud Next uses to identify the device. ### Syntax ```dart MobileAppMessaging.getDeviceId(); ``` ### Returns - `Future` - A future that resolves with the device ID, or `null`. ### Example ```dart import 'package:sfmc_mobileappmessaging/sfmc_mobileappmessaging.dart'; await MobileAppMessaging.requestSdk(); final deviceId = await MobileAppMessaging.getDeviceId(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/mobileappmessaging/com.salesforce.marketingcloud.mobileappmessaging.registration/-registration-manager/get-device-id.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MAMSdk/2.0/Classes/MobileAppMessaging.html#/c:@CM@MobileAppMessagingSDK@objc(cs)SFMobileAppMessaging(im)deviceIdentifier>) ## enableAnalytics Enables analytics for Marketing Cloud Next. ### Syntax ```dart MobileAppMessaging.enableAnalytics(); ``` ### Returns - `Future` ### Example ```dart import 'package:sfmc_mobileappmessaging/sfmc_mobileappmessaging.dart'; await MobileAppMessaging.requestSdk(); await MobileAppMessaging.enableAnalytics(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/mobileappmessaging/com.salesforce.marketingcloud.mobileappmessaging.analytics/-analytics-manager/enable-analytics.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MAMSdk/2.0/Classes/MobileAppMessaging.html#/c:@CM@MobileAppMessagingSDK@objc(cs)SFMobileAppMessaging(im)setAnalyticsEnabled:>) ## disableAnalytics Disables analytics for Marketing Cloud Next. ### Syntax ```dart MobileAppMessaging.disableAnalytics(); ``` ### Returns - `Future` ### Example ```dart import 'package:sfmc_mobileappmessaging/sfmc_mobileappmessaging.dart'; await MobileAppMessaging.requestSdk(); await MobileAppMessaging.disableAnalytics(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/mobileappmessaging/com.salesforce.marketingcloud.mobileappmessaging.analytics/-analytics-manager/disable-analytics.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MAMSdk/2.0/Classes/MobileAppMessaging.html#/c:@CM@MobileAppMessagingSDK@objc(cs)SFMobileAppMessaging(im)setAnalyticsEnabled:>) ## isAnalyticsEnabled Checks whether analytics is enabled for Marketing Cloud Next. ### Syntax ```dart MobileAppMessaging.isAnalyticsEnabled(); ``` ### Returns - `Future` - A future that resolves with whether analytics is enabled. ### Example ```dart import 'package:sfmc_mobileappmessaging/sfmc_mobileappmessaging.dart'; await MobileAppMessaging.requestSdk(); final enabled = await MobileAppMessaging.isAnalyticsEnabled(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/mobileappmessaging/com.salesforce.marketingcloud.mobileappmessaging.analytics/-analytics-manager/are-analytics-enabled.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MAMSdk/2.0/Classes/MobileAppMessaging.html#/c:@CM@MobileAppMessagingSDK@objc(cs)SFMobileAppMessaging(im)isAnalyticsEnabled>) ## setRegistrationCallback Registers a callback to receive registration change events from the SDK. ### Syntax ```dart MobileAppMessaging.setRegistrationCallback(); ``` ### Returns - `Future` ### Example ```dart import 'package:sfmc_mobileappmessaging/sfmc_mobileappmessaging.dart'; await MobileAppMessaging.requestSdk(); await MobileAppMessaging.setRegistrationCallback(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/mobileappmessaging/com.salesforce.marketingcloud.mobileappmessaging.registration/-registration-manager/register-for-registration-events.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MAMSdk/2.0/Classes/MobileAppMessaging.html#/c:@CM@MobileAppMessagingSDK@objc(cs)SFMobileAppMessaging(im)setRegistrationCallback:>) ## unsetRegistrationCallback Unregisters the registration change callback. ### Syntax ```dart MobileAppMessaging.unsetRegistrationCallback(); ``` ### Returns - `Future` ### Example ```dart import 'package:sfmc_mobileappmessaging/sfmc_mobileappmessaging.dart'; await MobileAppMessaging.requestSdk(); await MobileAppMessaging.unsetRegistrationCallback(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/mobileappmessaging/com.salesforce.marketingcloud.mobileappmessaging.registration/-registration-manager/unregister-for-registration-events.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MAMSdk/2.0/Classes/MobileAppMessaging.html#/c:@CM@MobileAppMessagingSDK@objc(cs)SFMobileAppMessaging(im)unsetRegistrationCallback>) ## registrationEvents A broadcast stream of registration events. Emits a map of registration data when the registration changes. ### Syntax ```dart MobileAppMessaging.registrationEvents; ``` ### Returns - `Stream>` - A broadcast stream that emits a map of registration data on every registration change. ### Example ```dart import 'package:sfmc_mobileappmessaging/sfmc_mobileappmessaging.dart'; await MobileAppMessaging.requestSdk(); MobileAppMessaging.registrationEvents.listen((event) { print('Registration changed: $event'); }); ``` # Marketing Cloud Mobile App Messaging SDK This section provides API reference details for the Marketing Cloud Mobile App Messaging SDK module in React Native unified plugin. ## getDeviceId Returns the device ID that Mobile App Messaging uses to identify the device. ### Syntax ```javascript MobileAppMessagingSdkModule.getDeviceId(); ``` ### Returns - `Promise` - A promise that resolves to the device ID, or `null`. ### Example ```javascript import { MobileAppMessagingModule } from "@sfmc/react-native-mobileappmessaging"; import type { MAMApi } from "@sfmc/react-native-mobileappmessaging"; const mam: MAMApi = await MobileAppMessagingModule.requestSdk(); const deviceId = await mam.getDeviceId(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/mobileappmessaging/com.salesforce.marketingcloud.mobileappmessaging.registration/-registration-manager/get-device-id.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MAMSdk/2.0/Classes/MobileAppMessaging.html#/c:@CM@MobileAppMessagingSDK@objc(cs)SFMobileAppMessaging(im)deviceIdentifier>) ## enableAnalytics Enables analytics in the Mobile App Messaging SDK. ### Syntax ```javascript MobileAppMessagingSdkModule.enableAnalytics(); ``` ### Returns - `void` ### Example ```javascript import { MobileAppMessagingModule } from "@sfmc/react-native-mobileappmessaging"; import type { MAMApi } from "@sfmc/react-native-mobileappmessaging"; const mam: MAMApi = await MobileAppMessagingModule.requestSdk(); mam.enableAnalytics(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/mobileappmessaging/com.salesforce.marketingcloud.mobileappmessaging.analytics/-analytics-manager/enable-analytics.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MAMSdk/2.0/Classes/MobileAppMessaging.html#/c:@CM@MobileAppMessagingSDK@objc(cs)SFMobileAppMessaging(im)setAnalyticsEnabled:>) ## disableAnalytics Disables analytics in the Mobile App Messaging SDK. ### Syntax ```javascript MobileAppMessagingSdkModule.disableAnalytics(); ``` ### Returns - `void` ### Example ```javascript import { MobileAppMessagingModule } from "@sfmc/react-native-mobileappmessaging"; import type { MAMApi } from "@sfmc/react-native-mobileappmessaging"; const mam: MAMApi = await MobileAppMessagingModule.requestSdk(); mam.disableAnalytics(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/mobileappmessaging/com.salesforce.marketingcloud.mobileappmessaging.analytics/-analytics-manager/disable-analytics.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MAMSdk/2.0/Classes/MobileAppMessaging.html#/c:@CM@MobileAppMessagingSDK@objc(cs)SFMobileAppMessaging(im)setAnalyticsEnabled:>) ## isAnalyticsEnabled Checks whether analytics is enabled in the Mobile App Messaging SDK. ### Syntax ```javascript MobileAppMessagingSdkModule.isAnalyticsEnabled(); ``` ### Returns - `Promise` - A promise that resolves to whether analytics is enabled. ### Example ```javascript import { MobileAppMessagingModule } from "@sfmc/react-native-mobileappmessaging"; import type { MAMApi } from "@sfmc/react-native-mobileappmessaging"; const mam: MAMApi = await MobileAppMessagingModule.requestSdk(); const enabled = await mam.isAnalyticsEnabled(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/mobileappmessaging/com.salesforce.marketingcloud.mobileappmessaging.analytics/-analytics-manager/are-analytics-enabled.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MAMSdk/2.0/Classes/MobileAppMessaging.html#/c:@CM@MobileAppMessagingSDK@objc(cs)SFMobileAppMessaging(im)isAnalyticsEnabled>) ## setRegistrationCallback Registers a callback to receive registration change events from the SDK. ### Syntax ```javascript MobileAppMessagingSdkModule.setRegistrationCallback(); ``` ### Returns - `void` ### Example ```javascript import { MobileAppMessagingModule } from "@sfmc/react-native-mobileappmessaging"; import type { MAMApi } from "@sfmc/react-native-mobileappmessaging"; const mam: MAMApi = await MobileAppMessagingModule.requestSdk(); mam.setRegistrationCallback(); const sub = MobileAppMessagingModule.getEmitter().addListener( "sfmc_mam_registration", (registration) => { console.log("MAM registration changed:", registration); }, ); sub.remove(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/mobileappmessaging/com.salesforce.marketingcloud.mobileappmessaging.registration/-registration-manager/register-for-registration-events.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MAMSdk/2.0/Classes/MobileAppMessaging.html#/c:@CM@MobileAppMessagingSDK@objc(cs)SFMobileAppMessaging(im)setRegistrationCallback:>) ## unsetRegistrationCallback Unregisters the registration change callback. ### Syntax ```javascript MobileAppMessagingSdkModule.unsetRegistrationCallback(); ``` ### Returns - `void` ### Example ```javascript import { MobileAppMessagingModule } from "@sfmc/react-native-mobileappmessaging"; import type { MAMApi } from "@sfmc/react-native-mobileappmessaging"; const mam: MAMApi = await MobileAppMessagingModule.requestSdk(); mam.unsetRegistrationCallback(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/mobileappmessaging/com.salesforce.marketingcloud.mobileappmessaging.registration/-registration-manager/unregister-for-registration-events.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/MAMSdk/2.0/Classes/MobileAppMessaging.html#/c:@CM@MobileAppMessagingSDK@objc(cs)SFMobileAppMessaging(im)unsetRegistrationCallback>) # Marketing Cloud SDK ## Packages - [com.salesforce.marketingcloud](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud/_index.md) - [com.salesforce.marketingcloud.analytics](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-analytics/analytics_index.md) - [com.salesforce.marketingcloud.location](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-location/location_index.md) - [com.salesforce.marketingcloud.messages](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-messages/messages_index.md) - [com.salesforce.marketingcloud.messages.geofence](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-messages-geofence/messages-geofence_index.md) - [com.salesforce.marketingcloud.messages.inbox](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-messages-inbox/messages-inbox_index.md) - [com.salesforce.marketingcloud.messages.proximity](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-messages-proximity/messages-proximity_index.md) - [com.salesforce.marketingcloud.notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-notifications/notifications_index.md) - [com.salesforce.marketingcloud.proximity](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-proximity/proximity_index.md) - [com.salesforce.marketingcloud.registration](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-registration/registration_index.md) # MarketingCloudConfig **Package:** `com.salesforce.marketingcloud` **Type:** `data class` **Extends:** `EngagementModuleConfig` ## Overview The `MarketingCloudConfig` class is a data configuration class for the Salesforce Marketing Cloud Unified SDK. It contains all configuration parameters needed to initialize and customize the Marketing Cloud SDK functionality. ## Class Declaration ```kotlin data class MarketingCloudConfig : EngagementModuleConfig ``` ## Properties ### Required Configuration | Property | Type | Description | | ------------------------- | -------- | --------------------------------------------------- | | `accessToken` | `String` | Authentication token for Marketing Cloud API access | | `applicationId` | `String` | Unique identifier for the application | | `marketingCloudServerUrl` | `String` | The Marketing Cloud server URL endpoint | ### Optional Configuration | Property | Type | Description | | ------------------------------------------- | -------------------------------------------- | ------------------------------------------------------------- | | `mid` | `String?` | Marketing Cloud Member ID (nullable) | | `analyticsEnabled` | `Boolean` | Enables or disables analytics tracking | | `piAnalyticsEnabled` | `Boolean` | Enables or disables Predictive Intelligence analytics | | `inboxEnabled` | `Boolean` | Enables or disables inbox messaging functionality | | `geofencingEnabled` | `Boolean` | Enables or disables geofencing features | | `proximityEnabled` | `Boolean` | Enables or disables proximity/beacon messaging | | `delayRegistrationUntilContactKeyIsSet` | `Boolean` | Delays device registration until contact key is provided | | `markMessageReadOnInboxNotificationOpen` | `Boolean` | Auto-marks inbox messages as read when notification is opened | | `useLegacyPiIdentifier` | `Boolean` | Uses legacy identifier format for Predictive Intelligence | | `urlHandler` | `UrlHandler?` | Custom handler for URL processing (nullable) | | `proximityNotificationCustomizationOptions` | `ProximityNotificationCustomizationOptions?` | Customization options for proximity notifications (nullable) | All properties are annotated with `@JvmField` for Java interoperability. ## Nested Types ### Builder ```kotlin class Builder ``` Builder pattern implementation for constructing `MarketingCloudConfig` instances. ### Companion ```kotlin object Companion ``` Companion object for static utility methods and constants. ## Methods ### toBuilder() ```kotlin fun toBuilder(): MarketingCloudConfig.Builder ``` Converts the current configuration instance back into a Builder for modification. **Returns:** A new `Builder` instance populated with current configuration values ## Usage This configuration class is typically instantiated using the Builder pattern: ```kotlin val config = MarketingCloudConfig.Builder() .setAccessToken("your-access-token") .setApplicationId("your-app-id") .setMarketingCloudServerUrl("https://your-server.com") .setAnalyticsEnabled(true) .build() ``` The configuration object is then passed to the Marketing Cloud SDK during initialization. # MarketingCloudSdk ## Overview **Package:** `com.salesforce.marketingcloud` **Interfaces:** `ControlChannel.ControlChannelListener`, `ModuleInterface` The main SDK class for Salesforce Marketing Cloud Unified SDK. This class provides the primary interface for initializing and interacting with the Marketing Cloud SDK. --- ## Nested Types ### InitializationListener ```kotlin interface InitializationListener ``` An interface that provides an `InitializationStatus` when SDK initialization completes. ### WhenReadyListener ```kotlin interface WhenReadyListener ``` An interface that provides a valid `MarketingCloudSdk` instance when ready. --- ## Properties ### analyticsManager ```kotlin @NonNull open val analyticsManager: AnalyticsManager ``` Provides access to the analytics management functionality. --- ### instance ```kotlin @Nullable open val instance: MarketingCloudSdk ``` Returns the current SDK instance, or null if not initialized. --- ### isInitializing ```kotlin open val isInitializing: Boolean ``` Indicates whether the SDK is currently in the initialization process. --- ### isReady ```kotlin open val isReady: Boolean ``` Indicates whether the SDK has completed initialization and is ready to use. --- ## Methods ### init ```kotlin @MainThread open fun init( @NonNull context: Context, @NonNull config: MarketingCloudConfig, @Nullable listener: InitializationListener ) ``` Initializes the SDK with the provided configuration. Must be called from the main thread. **Parameters:** - `context` - Android application context - `config` - Marketing Cloud configuration object - `listener` - Optional callback for initialization completion --- ### requestSdk ```kotlin open fun requestSdk(@NonNull listener: WhenReadyListener) ``` Asynchronous request for an SDK instance. **Parameters:** - `listener` - Callback that receives the SDK instance when ready ```kotlin open fun requestSdk( @Nullable looper: Looper, @NonNull listener: WhenReadyListener ) ``` Asynchronous request for an SDK instance with custom looper. **Parameters:** - `looper` - Custom looper for callback execution - `listener` - Callback that receives the SDK instance when ready --- ### unregisterWhenReadyListener ```kotlin open fun unregisterWhenReadyListener(@NonNull listener: WhenReadyListener) ``` Prevents a `WhenReadyListener` from receiving the SDK instance. **Parameters:** - `listener` - The listener to unregister --- ### getMarketingCloudConfig ```kotlin @NonNull open fun getMarketingCloudConfig(): MarketingCloudConfig ``` **Returns:** The `MarketingCloudConfig` instance used to initialize the SDK. --- ### getInitializationStatus ```kotlin @NonNull open fun getInitializationStatus(): InitializationStatus ``` **Returns:** The current initialization status of the SDK. --- ### getRegistrationManager ```kotlin @NonNull open fun getRegistrationManager(): RegistrationManager ``` **Returns:** The registration manager for device registration operations. --- ### getInboxMessageManager ```kotlin @NonNull open fun getInboxMessageManager(): InboxMessageManager ``` **Returns:** The inbox message manager for handling inbox messages. --- ### getRegionMessageManager ```kotlin @NonNull open fun getRegionMessageManager(): RegionMessageManager ``` **Returns:** The region message manager for location-based messaging. --- ### getSdkState ```kotlin @NonNull open fun getSdkState(): JSONObject ``` **Returns:** A JSON object containing the current state of the SDK. --- ### getSdkVersionName ```kotlin @NonNull open fun getSdkVersionName(): String ``` **Returns:** The version name of the SDK as a string. --- ### getSdkVersionCode ```kotlin open fun getSdkVersionCode(): Int ``` **Returns:** The version code of the SDK as an integer. --- ### setLogLevel ```kotlin open fun setLogLevel(level: Int) ``` Sets the logging level for the SDK. **Parameters:** - `level` - The desired log level --- ### getLogLevel ```kotlin open fun getLogLevel(): Int ``` **Returns:** The current log level. --- ### setLogListener ```kotlin open fun setLogListener(@Nullable logListener: MCLogListener) ``` Sets a custom log listener for SDK logging events. **Parameters:** - `logListener` - Optional custom log listener implementation # MarketingCloudSdk `Class` This class is a Swift Interface for SFMarketingCloudSdk ## Declaration ```swift @objc(SFMarketingCloudSdk) public final class MarketingCloudSdk : NSObject, SFMCModule, Publisher @objc public static func requestSdk(_ callback: @escaping (_ marketingCloudSdk: MarketingCloudSdkInterface?) -> Void) @objc public static func metadata() -> [String : Any] public func refresh(fetchCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)?) -> Bool public func setDebugLoggingEnabled(_ enabled: Bool) @objc public static func getLogger() -> ModuleLogger public func contactKey() -> String? public func addTag(_ tag: String) -> Bool public func addTags(_ tags: [Any]) -> Set? public func removeTag(_ tag: String) -> Bool public func tags() -> Set? public func attributes() -> [AnyHashable : Any]? public func accessToken() -> String? public func deviceIdentifier() -> String? public func setSignedString(_ signedString: String?) -> Bool public func signedString() -> String? public func setRegistrationCallback(_ registrationCallback: @escaping (Dictionary) -> Void) public func unsetRegistrationCallback() public func setAnalyticsEnabled(_ analyticsEnabled: Bool) public func isAnalyticsEnabled() -> Bool public func setPiAnalyticsEnabled(_ analyticsEnabled: Bool) public func isPiAnalyticsEnabled() -> Bool public func isLocationEnabled() -> Bool public func setLocationEnabled(_ locationEnabled: Bool) public func isInboxEnabled() -> Bool public func setInboxEnabled(_ inboxEnabled: Bool) public func getAllMessages() -> [Any]? public func getUnreadMessages() -> [Any]? public func getReadMessages() -> [Any]? public func getDeletedMessages() -> [Any]? public func getAllMessagesCount() -> UInt public func getUnreadMessagesCount() -> UInt public func getReadMessagesCount() -> UInt public func getDeletedMessagesCount() -> UInt public func markMessageRead(_ messageDictionary: [AnyHashable : Any]) -> Bool public func markMessageDeleted(_ messageDictionary: [AnyHashable : Any]) -> Bool public func markMessageWithIdRead(messageId: String) -> Bool public func markMessageWithIdDeleted(messageId: String) -> Bool public func markAllMessagesRead() -> Bool public func markAllMessagesDeleted() -> Bool public func refreshMessages() -> Bool public func setPiIdentifier(_ identifier: String?) -> Bool public func piIdentifier() -> String? public func trackMessageOpened(_ inboxMessage: [AnyHashable : Any]) public func trackPageView(url: String, title: String?, item: String?, search: String?) public func trackCartContents(_ cartDictionary: [AnyHashable : Any]) public func trackCartConversion(_ orderDictionary: [AnyHashable : Any]) public func cartItemDictionary(price: NSNumber, quantity: NSNumber, item: String, uniqueId: String?) -> [AnyHashable : Any]? public func cartDictionary(cartItem: [Any]) -> [AnyHashable : Any]? public func orderDictionary(orderNumber: String, shipping: NSNumber, discount: NSNumber, cart: [AnyHashable : Any]) -> [AnyHashable : Any]? public func setLocationDelegate(_ delegate: LocationDelegate?) public func regionFrom(dictionary: [AnyHashable : Any]) -> CLRegion? public func locationEnabled() -> Bool public func startWatchingLocation() public func stopWatchingLocation() public func watchingLocation() -> Bool public func lastKnownLocation() -> [String : String]? ``` ## Request SDK Method ### `requestSdk(_:)` Requests the MarketingCloudSdk Module when it’s operational and safe to use. The provided callback will be invoked with the MarketingCloudSdk Module when it’s ready. All MarketingCloudSdk module-related API calls should be made within this function. ```swift @objc public static func requestSdk(_ callback: @escaping (_ marketingCloudSdk: MarketingCloudSdkInterface?) -> Void) ``` --- ## Push Methods ### `metadata()` This method is to get the SDK metadata ```swift @objc public static func metadata() -> [String : Any] ``` --- ### `refresh(fetchCompletionHandler:)` Ask MarketingCloudSDK to update its data. MarketingCloudSDK will throttle attempts based on the time since the last time this was called. ```swift public func refresh(fetchCompletionHandler completionHandler: ((UIBackgroundFetchResult) -> Void)?) -> Bool ``` --- ## Logging Methods ### `setDebugLoggingEnabled(_:)` Enable/Disable extra debug logging from the SDK. ```swift public func setDebugLoggingEnabled(_ enabled: Bool) ``` --- ### `getLogger()` Unified Logger initialized for ‘MarketingCloudSdk’ Module Usage Example: MarketingCloudSdk.shared.getLogger().d(category: .event, message: “Message”) ```swift @objc public static func getLogger() -> ModuleLogger ``` --- ## Registration Methods ### `contactKey()` ```swift public func contactKey() -> String? ``` **Returns:** Contact key String that is set in the application. --- ### `addTag(_:)` Adds the provided Tag (NSString) to the set of unique tags. ```swift public func addTag(_ tag: String) -> Bool ``` **Returns:** YES if added successfully. --- ### `addTags(_:)` Adds the provided array of Tags (NSString) to the set of unique tags. Will trim leading and trailing whitespace. Cannot be nil or blank. ```swift public func addTags(_ tags: [Any]) -> Set? ``` **Returns:** Set of tags added, as strings, or nil if something failed. --- ### `removeTag(_:)` Removes the provided Tag (NSString) from the list of tags. ```swift public func removeTag(_ tag: String) -> Bool ``` **Returns:** YES if removed successfully. --- ### `tags()` Returns the list of tags for this device. ```swift public func tags() -> Set? ``` **Returns:** All tags associated, as strings. --- ### `attributes()` Returns a read-only copy of the Attributes dictionary as it is right now. ```swift public func attributes() -> [AnyHashable : Any]? ``` --- ### `accessToken()` Returns the Salesforce application accessToken. ```swift public func accessToken() -> String? ``` --- ### `deviceIdentifier()` Returns the unique device identifier that Salesforce will use to identify the device. ```swift public func deviceIdentifier() -> String? ``` --- ### `setSignedString(_:)` Add a signedString security token for registration security ```swift public func setSignedString(_ signedString: String?) -> Bool ``` --- ### `signedString()` Returns the value of last stored signedString security token ```swift public func signedString() -> String? ``` --- ### `setRegistrationCallback(_:)` Register a callback that will be notified when Registration related events happen @see: https://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/sdk-implementation/user-data.html @param registrationCallback closure to be provided when registration event occurs ```swift public func setRegistrationCallback(_ registrationCallback: @escaping (Dictionary) -> Void) ``` --- ### `unsetRegistrationCallback()` Removes the registration callback @see: https://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/sdk-implementation/user-data.html ```swift public func unsetRegistrationCallback() ``` --- ## Feature Toggle Methods ### `setAnalyticsEnabled(_:)` Developer override to set the state of analytics enablement to YES/NO. If set to NO, the SDK will stop tracking analytics and also purges all the analytics stored locally. This value takes precedence over the config setting which is passed during the SDK initialization. ```swift public func setAnalyticsEnabled(_ analyticsEnabled: Bool) ``` --- ### `isAnalyticsEnabled()` The current state of the Analytics enablement override ```swift public func isAnalyticsEnabled() -> Bool ``` --- ### `setPiAnalyticsEnabled(_:)` Developer override to set the state of PI analytics enablement to YES/NO. If set to NO, the SDK will stop tracking PI analytics and also purges all the analytics stored locally. This value takes precedence over the config setting which is passed during the SDK initialization. ```swift public func setPiAnalyticsEnabled(_ analyticsEnabled: Bool) ``` --- ### `isPiAnalyticsEnabled()` The current state of the PI Analytics enablement override ```swift public func isPiAnalyticsEnabled() -> Bool ``` --- ### `isLocationEnabled()` The current state of the Location enablement override ```swift public func isLocationEnabled() -> Bool ``` --- ### `setLocationEnabled(_:)` Developer override to set the state of Location enablement to YES/NO. If set to NO, the SDK will stop monitoring location and Location services are not available for the consuming application. This value takes precedence over the config setting which is passed during the SDK initialization. ```swift public func setLocationEnabled(_ locationEnabled: Bool) ``` --- ### `isInboxEnabled()` The current state of the Inbox enablement override ```swift public func isInboxEnabled() -> Bool ``` --- ### `setInboxEnabled(_:)` Developer override to set the state of Inbox enablement to YES/NO. If set to NO, Inbox feature will be disabled. This value takes precedence over the config setting which is passed during the SDK initialization. ```swift public func setInboxEnabled(_ inboxEnabled: Bool) ``` --- ## InboxMessages ### `getAllMessages()` Returns an array of all messages that includes read, unread , deleted messages Public properties in inbox message dictionary ```swift public func getAllMessages() -> [Any]? ``` **Returns:** an Array of Dictionary containing all messages (read, unread and deleted) --- ### `getUnreadMessages()` Returns an array of unread messages Public properties in inbox message dictionary ```swift public func getUnreadMessages() -> [Any]? ``` --- ### `getReadMessages()` Returns an array of read messages Public properties in inbox message dictionary ```swift public func getReadMessages() -> [Any]? ``` --- ### `getDeletedMessages()` Returns an array of deleted messages Public properties in inbox message dictionary ```swift public func getDeletedMessages() -> [Any]? ``` --- ### `getAllMessagesCount()` Returns all messages count ```swift public func getAllMessagesCount() -> UInt ``` --- ### `getUnreadMessagesCount()` Returns unread messages count ```swift public func getUnreadMessagesCount() -> UInt ``` --- ### `getReadMessagesCount()` Returns read messages count ```swift public func getReadMessagesCount() -> UInt ``` --- ### `getDeletedMessagesCount()` Returns deleted messages count ```swift public func getDeletedMessagesCount() -> UInt ``` --- ### `markMessageRead(_:)` Mark the unread messages as read ```swift public func markMessageRead(_ messageDictionary: [AnyHashable : Any]) -> Bool ``` --- ### `markMessageDeleted(_:)` Mark the messages as deleted ```swift public func markMessageDeleted(_ messageDictionary: [AnyHashable : Any]) -> Bool ``` --- ### `markMessageWithIdRead(messageId:)` Mark the message with specific messageId as read ```swift public func markMessageWithIdRead(messageId: String) -> Bool ``` --- ### `markMessageWithIdDeleted(messageId:)` Mark the message with specific messageId as deleted ```swift public func markMessageWithIdDeleted(messageId: String) -> Bool ``` --- ### `markAllMessagesRead()` Mark all the messages with specific messageId as read ```swift public func markAllMessagesRead() -> Bool ``` --- ### `markAllMessagesDeleted()` Mark all the messages with specific messageId as deleted ```swift public func markAllMessagesDeleted() -> Bool ``` --- ### `refreshMessages()` Fetches and refreshes messages from server Reload and refresh Inbox messages from the Marketing Cloud server. Note: The underlying request to the server will be throttled such that it will execute at most every 60 seconds. If the method has been called less than 60 seconds after the preceeding method call, NO will be returned and the request will not be made. If NO is returned, best practice is that any UI used to reflect the refresh operation is updated (pull to refresh indicators, loading spinners, etc.). DDoS Protection The SDK has several built in mechanisms to protect Marketing Cloud servers and services. For message GET routes, we allow at most one manual refresh request per minute. This prevents bad application implementations or mobile app users from calling refresh over and over when there will be no new data available. Within the SDK and it’s logging, this presents a 429 - Too Many Requests log statement. Throttling To protect the workload and ensure optimal performance, the Inbox Message routes may throttle incoming requests. This throttling is based on adaptive logic, which operates as a percentage of traffic depending on the current load. The system is designed to automatically determine when throttling is necessary or when it can be reduced. During periods of traffic throttling, some customer requests may receive a 429 - Too Many Requests response. This will log a 429 response within the SDK. The Marketing Cloud has considerable server-side logic to monitor and adjust this throttling mechanism. This method will cause notifications to be posted to NSNotificationCenter: SFMCInboxMessagesRefreshCompleteNotification: posted when the refresh process has completed SFMCInboxMessagesNewInboxMessagesNotification: posted if there are new Inbox messages ```swift public func refreshMessages() -> Bool ``` --- ## Intelligence ### `setPiIdentifier(_:)` Set String identifier ```swift public func setPiIdentifier(_ identifier: String?) -> Bool ``` --- ### `piIdentifier()` Returns piIdentifier ```swift public func piIdentifier() -> String? ``` --- ### `trackMessageOpened(_:)` Track the inbox messages that are opened in the app ```swift public func trackMessageOpened(_ inboxMessage: [AnyHashable : Any]) ``` --- ### `trackPageView(url:title:item:search:)` Track the pageview visited in the page ```swift public func trackPageView(url: String, title: String?, item: String?, search: String?) ``` --- ### `trackCartContents(_:)` Track contents in the cart ```swift public func trackCartContents(_ cartDictionary: [AnyHashable : Any]) ``` --- ### `trackCartConversion(_:)` Track Conversion on the items in the cart ```swift public func trackCartConversion(_ orderDictionary: [AnyHashable : Any]) ``` --- ### `cartItemDictionary(price:quantity:item:uniqueId:)` Returns cartItem Dictionary with specific price, quantity, item and Id ```swift public func cartItemDictionary(price: NSNumber, quantity: NSNumber, item: String, uniqueId: String?) -> [AnyHashable : Any]? ``` --- ### `cartDictionary(cartItem:)` Returns cart Dictionary with cartItem ```swift public func cartDictionary(cartItem: [Any]) -> [AnyHashable : Any]? ``` --- ### `orderDictionary(orderNumber:shipping:discount:cart:)` Returns order Dictionary with ordernumber, shipping number, discount, cart dictionary ```swift public func orderDictionary(orderNumber: String, shipping: NSNumber, discount: NSNumber, cart: [AnyHashable : Any]) -> [AnyHashable : Any]? ``` --- ## Location ### `setLocationDelegate(_:)` Set location delegate ```swift public func setLocationDelegate(_ delegate: LocationDelegate?) ``` --- ### `regionFrom(dictionary:)` Returns region from collection of region ```swift public func regionFrom(dictionary: [AnyHashable : Any]) -> CLRegion? ``` --- ### `locationEnabled()` Returns if location is enabled in the SDK ```swift public func locationEnabled() -> Bool ``` --- ### `startWatchingLocation()` Enables the co-ordinates tracking on the device ```swift public func startWatchingLocation() ``` --- ### `stopWatchingLocation()` Disables the co-ordinates tracking on the device ```swift public func stopWatchingLocation() ``` --- ### `watchingLocation()` Returns if location watching is enabled or not ```swift public func watchingLocation() -> Bool ``` --- ### `lastKnownLocation()` Returns last known location ```swift public func lastKnownLocation() -> [String : String]? ``` --- # MarketingCloudSDK.bundle Inclusion Crash **important:** These troubleshooting steps apply only to the MobilePush SDK for iOS version 8.0.13 and earlier. In version 8.1.0 and later, the SDK automatically includes the bundle. When you upgrade to the latest version of the SDK, update `MarketingCloudSDK.bundle`. If you don’t copy the right versions, your app can crash because the older versions of `MarketingCloudSDK.bundle` don’t have the required resources. If you don’t include the latest `MarketingCloudSDK.bundle` in your app, you can encounter these exceptions. - NSInvalidArgumentException - : **Reason**: `+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'SFMCEndpointConfigurationEntity'` - NSInternalInconsistencyException - : **Reasons**: - `'NSFetchRequest could not locate an NSEntityDescription for entity name 'SFMCEventConfigurationEntity''` - `'Cannot create an NSPersistentStoreCoordinator with a nil model'` To resolve these exceptions, upgrade to the latest version of the SDK and then follow these steps. 1. In Xcode, under **Build phases** > **Copy Resources Bundle**, remove the existing `MarketingCloudSDK.bundle`. 2. Add the latest `MarketingCloudSDK.bundle`. See [Integrate the SDK for iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_integrate_ios/mc_engagement_integrate_ios.md). # MarketingCloudSdkConfigBuilder `Class` MarketingCloudSdkConfigBuilder class ## Declaration ```swift @objc(SFMarketingCloudSdkConfigBuilder) public class MarketingCloudSdkConfigBuilder : NSObject @objc public init(appId: String) @discardableResult @objc public func setAccessToken(_ accessToken: String) -> MarketingCloudSdkConfigBuilder @discardableResult @objc public func setMarketingCloudServerUrl(_ endpoint: URL) -> MarketingCloudSdkConfigBuilder @discardableResult @objc public func setMid(_ mid: String) -> MarketingCloudSdkConfigBuilder @discardableResult @objc public func setLocationEnabled(_ enabled: Bool) -> MarketingCloudSdkConfigBuilder @discardableResult @objc public func setInboxEnabled(_ enabled: Bool) -> MarketingCloudSdkConfigBuilder @discardableResult @objc public func setAnalyticsEnabled(_ enabled: Bool) -> MarketingCloudSdkConfigBuilder @discardableResult @objc public func setPIAnalyticsEnabled(_ enabled: Bool) -> MarketingCloudSdkConfigBuilder @discardableResult @objc public func setUseLegacyPIIdentifier(_ enabled: Bool) -> MarketingCloudSdkConfigBuilder @discardableResult @objc public func setApplicationControlsBadging(_ enabled: Bool) -> MarketingCloudSdkConfigBuilder @discardableResult @objc public func setDelayRegistrationUntilContactKeyIsSet(_ enabled: Bool) -> MarketingCloudSdkConfigBuilder @discardableResult @objc public func setEnableScreenEntryTracking(_ enabled: Bool) -> MarketingCloudSdkConfigBuilder @discardableResult @objc public func setMarkMessageReadOnInboxNotificationOpen(_ enabled: Bool) -> MarketingCloudSdkConfigBuilder @discardableResult @objc public func build() -> MarketingCloudSdkConfig ``` ## Cases ### `init(appId:)` Initialize MarketingCloudSdkConfigBuilder ```swift @objc public init(appId: String) ``` --- ### `setAccessToken(_:)` Sets the configuration value to use for the Salesforce MarketingCloud Tenant accessToken. ```swift @discardableResult @objc public func setAccessToken(_ accessToken: String) -> MarketingCloudSdkConfigBuilder ``` --- ### `setMarketingCloudServerUrl(_:)` Sets the configuration value to use for the Salesforce MarketingCloud Tenant Specific Url. ```swift @discardableResult @objc public func setMarketingCloudServerUrl(_ endpoint: URL) -> MarketingCloudSdkConfigBuilder ``` --- ### `setMid(_:)` Sets the configuration value to use for the Salesforce MarketingCloud Tenant Specific mid. ```swift @discardableResult @objc public func setMid(_ mid: String) -> MarketingCloudSdkConfigBuilder ``` --- ### `setLocationEnabled(_:)` Sets the configuration flag that enables or disables location services ```swift @discardableResult @objc public func setLocationEnabled(_ enabled: Bool) -> MarketingCloudSdkConfigBuilder ``` --- ### `setInboxEnabled(_:)` Sets the configuration flag that enables or disables inbox services ```swift @discardableResult @objc public func setInboxEnabled(_ enabled: Bool) -> MarketingCloudSdkConfigBuilder ``` --- ### `setAnalyticsEnabled(_:)` Sets the configuration flag that enables or disables Salesforce MarketingCloud Analytics services ```swift @discardableResult @objc public func setAnalyticsEnabled(_ enabled: Bool) -> MarketingCloudSdkConfigBuilder ``` --- ### `setPIAnalyticsEnabled(_:)` Sets the configuration flag that enables or disables Salesforce Predictive Intelligence analytics services ```swift @discardableResult @objc public func setPIAnalyticsEnabled(_ enabled: Bool) -> MarketingCloudSdkConfigBuilder ``` --- ### `setUseLegacyPIIdentifier(_:)` Sets the configuration flag that enables or disables Salesforce Predictive Intelligence email override to take contactKey if no value is set ```swift @discardableResult @objc public func setUseLegacyPIIdentifier(_ enabled: Bool) -> MarketingCloudSdkConfigBuilder ``` --- ### `setApplicationControlsBadging(_:)` Sets the configuration value which enables or disables application control over badging ```swift @discardableResult @objc public func setApplicationControlsBadging(_ enabled: Bool) -> MarketingCloudSdkConfigBuilder ``` --- ### `setDelayRegistrationUntilContactKeyIsSet(_:)` Sets the configuration value which enables or disables application control over delaying SDK registration until a contact key is set ```swift @discardableResult @objc public func setDelayRegistrationUntilContactKeyIsSet(_ enabled: Bool) -> MarketingCloudSdkConfigBuilder ``` --- ### `setEnableScreenEntryTracking(_:)` Sets the configuration value which enables or disables the screen entry tracking ```swift @discardableResult @objc public func setEnableScreenEntryTracking(_ enabled: Bool) -> MarketingCloudSdkConfigBuilder ``` --- ### `setMarkMessageReadOnInboxNotificationOpen(_:)` Activates/Deactivates the automatic marking of inbox messages as read when clicking the inbox notification, provided that this configuration is enabled. The default setting for this API is true. ```swift @discardableResult @objc public func setMarkMessageReadOnInboxNotificationOpen(_ enabled: Bool) -> MarketingCloudSdkConfigBuilder ``` --- ### `build()` Creates a MarketingCloudSdkConfig containing the current builder configuration settings. This can be passed to the ConfigBuilder method(s) ```swift @discardableResult @objc public func build() -> MarketingCloudSdkConfig ``` --- # MCCordovaPlugin~notificationOpenedCallback A callback function that’s called when a push message is opened. ## Kind Inner typedef of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | -------------- | -------- | -------------------------------------------------------------------------------------------------------------- | | `timeStamp` | `number` | Time since the epoch when the push message was opened. | | `values` | `Object` | The values of the notification message. | | `values.alert` | `string` | The alert text of the notification message. | | `values.title` | `string` | The title text of the notification message. | | `values.url` | `string` | The URL associated with the notification message. The URL can either be a CloudPages URL or an OpenDirect URL. | | `values.type` | `string` | Indicates the type of notification message. Possible values: `cloudPage`, `openDirect`, or `other`. | # MCCordovaPlugin~urlActionCallback A callback function that’s called when a URL action is taken. ## Kind Inner typedef of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | --------- | -------- | ----------------------------------------------------- | | `url` | `string` | The URL associated with the action taken by the user. | # MCE SDK (Marketing Cloud Engagement) Marketing Cloud Engagement SDK for MobilePush, location, and inbox ## API Reference ### [Classes](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/mce-sdk_classes_index.md) 2 classes # MCLogListener **Package:** com.salesforce.marketingcloud **SDK Version:** 11.0.0 ## Overview Interface for handling log output in the Salesforce Marketing Cloud Unified SDK. ## Interface Declaration ```kotlin interface MCLogListener ``` ## Inheritors - AndroidLogListener ## Nested Types ### AndroidLogListener ```kotlin open class AndroidLogListener : MCLogListener ``` Implementation of `MCLogListener` for Android logging. ### Companion ```kotlin object Companion ``` Companion object for the interface. ### LogLevel ```kotlin annotation class LogLevel ``` Annotation class defining log levels. ## Methods ### out ```kotlin abstract fun out( level: Int, tag: String, message: String, throwable: Throwable? ) ``` Outputs a log message. **Parameters:** - `level` - The log level (Int) - `tag` - The log tag identifier (String) - `message` - The log message content (String) - `throwable` - Optional throwable/exception (Throwable?) **Returns:** Unit (void) # Media **Package:** `com.salesforce.marketingcloud.pushmodels.data` **Module:** Push Models Module v1.0.2 **Platform:** androidJvm ## Overview ```kotlin data class Media( val url: String, val altText: Text? = null, val style: Style? = null, val actions: List? = listOf() ) : PushView, Parcelable ``` A data class representing media content in push notifications. Implements both `PushView` and Android's `Parcelable` interface. ## Constructors ### Media ```kotlin constructor( url: String, altText: Text? = null, style: Style? = null, actions: List? = listOf() ) ``` Creates a Media instance with the specified parameters. ## Properties ### url ```kotlin val url: String ``` The URL of the media resource. ### altText ```kotlin val altText: Text? ``` Optional alternative text description for the media. ### style ```kotlin open override val style: Style? ``` Optional styling information for the media display. Overrides `PushView.style`. ### actions ```kotlin open override val actions: List? ``` Optional list of actions associated with the media. Overrides `PushView.actions`. ## Functions ### toString ```kotlin open override fun toString(): String ``` Returns a string representation of the Media object. ## Nested Types ### Companion ```kotlin object Companion ``` Companion object for the Media class. # MediaProviders `Enumeration` Enum for enabling specific media providers in rich push notifications. Raw values are powers of two so callers can combine them into a bitmask with `|` (e.g. `MediaProviders.sfmc.rawValue | MediaProviders.someOther.rawValue` ). The special `.none` case (raw value `0` ) is the “opt-out” sentinel and is not a bit itself. ## Declaration ```swift @objc(SFMCMediaProviders) public enum MediaProviders : Int, CaseIterable case none = 0 case sfmc = 1 ``` ## Cases ### `none` Explicitly opt out of automatic media handling by the SDK. Use when the host app performs its own media download in `sfmcDidReceiveRequest` and does not want the SDK to run in parallel. ```swift case none = 0 ``` --- ### `sfmc` SFMC media provider — downloads media from SFMC push notifications. ```swift case sfmc = 1 ``` --- # Message **Package:** `com.salesforce.marketingcloud.messages` **SDK Version:** 11.0.0 **Platform:** androidJvm ```kotlin data class Message : Parcelable ``` A data class representing a message in the Salesforce Marketing Cloud SDK. --- ## Nested Types ### Companion ```kotlin object Companion ``` ### Media ```kotlin class Media : Parcelable ``` --- ## Properties ### alert ```kotlin @JvmField val alert: String ``` ### contentType ```kotlin @JvmField val contentType: Int ``` ### custom ```kotlin @JvmField val custom: String? ``` ### customKeys ```kotlin @JvmField val customKeys: Map? ``` ### endDateUtc ```kotlin @JvmField val endDateUtc: Date? ``` ### id ```kotlin @JvmField val id: String ``` ### isRollingPeriod ```kotlin @JvmField val isRollingPeriod: Boolean ``` ### media ```kotlin @JvmField val media: Message.Media? ``` ### messageLimit ```kotlin @JvmField val messageLimit: Int ``` ### messagesPerPeriod ```kotlin @JvmField val messagesPerPeriod: Int ``` ### messageType ```kotlin @JvmField val messageType: Int ``` ### numberOfPeriods ```kotlin @JvmField val numberOfPeriods: Int ``` ### openDirect ```kotlin @JvmField val openDirect: String? ``` ### periodType ```kotlin @JvmField val periodType: Int ``` ### proximity ```kotlin @JvmField val proximity: Int ``` ### sound ```kotlin @JvmField val sound: String? ``` ### startDateUtc ```kotlin @JvmField val startDateUtc: Date? ``` ### title ```kotlin @JvmField val title: String? ``` ### url ```kotlin @JvmField val url: String? ``` --- **Source:** https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages/-message/index.html **Available Versions:** 11.0.0, 10.0.0 # Message Class ## Package Information **Package:** `com.salesforce.marketingcloud.pushmodels` **Module:** Push Models Module v1.0.2 **Platform:** androidJvm ## Class Description ```kotlin data class Message : Parcelable ``` The `Message` class is a data class representing a push notification message in the Salesforce Marketing Cloud Unified SDK. It implements `Parcelable` for efficient data passing between Android components. ## Nested Types ### Companion Object ```kotlin object Companion ``` A companion object for the Message class. ### Media Class ```kotlin class Media : Parcelable ``` Represents media content associated with the message. Implements `Parcelable`. ## Properties All properties are annotated with `@JvmField` for Java interoperability. ### Message Content Properties - **`alert: String`** - The alert text of the push notification - **`title: String?`** - Optional title for the notification - **`sound: String?`** - Optional sound identifier for the notification ### Message Identification - **`id: String`** - Unique identifier for the message ### Message Configuration - **`contentType: Int`** - Type of content in the message - **`messageType: Int`** - Type classification of the message - **`messageLimit: Int`** - Limit on message delivery - **`proximity: Int`** - Proximity setting for the message ### Custom Data - **`custom: String?`** - Optional custom data string - **`customKeys: Map?`** - Optional map of custom key-value pairs ### Action Properties - **`openDirect: String?`** - Optional direct open action - **`url: String?`** - Optional URL associated with the message ### Date and Time Properties - **`startDateUtc: Date?`** - Optional start date in UTC - **`endDateUtc: Date?`** - Optional end date in UTC ### Period Configuration - **`isRollingPeriod: Boolean`** - Indicates if the period is rolling - **`periodType: Int`** - Type of period - **`numberOfPeriods: Int`** - Number of periods - **`messagesPerPeriod: Int`** - Number of messages allowed per period ### Media Content - **`media: Message.Media?`** - Optional media content associated with the message ## Inheritance - Implements: `android.os.Parcelable` # Messages with an OpenDirect URL Use OpenDirect to direct users to specific content when they tap a push notification. OpenDirect messages include a URL in the push payload that points to a web page, a deep link within your app, or any custom URL scheme your app handles. This feature lets marketers create notifications that take users directly to relevant content, such as product pages, promotional offers, article details, or specific app screens. When a user taps an OpenDirect notification, the SDK passes the URL to your application through the URL handling delegate. Your app then decides how to handle the URL. The can open the link in a browser, display the URL in an in-app browser using `SFSafariViewController`, navigate to a specific screen, or trigger custom logic based on URL parameters. A marketing admin enables OpenDirect on the MobilePush Administration page in Marketing Cloud Engagement Setup. ![The MobilePush Administration page in Marketing Cloud Engagement, showing the Open Direct option enabled.](https://developer.salesforce.com/media/push-messaging/open-direct-marketer-enable.png) # Migrate Android Apps to Version 10 of the SDK The process for migrating your Android apps to version 10 of the SDK depends on which features you use. To start the process of migrating your apps, use this code example to update the initialization code in your app to use version 10 of the SDK. ```kotlin class MyApplication: Application() { override fun onCreate() { super.onCreate() // Initialize logging _before_ initializing the SDK to avoid losing valuable debugging information. if (BuildConfig.DEBUG) { SFMCSdk.setLogging(LogLevel.DEBUG, LogListener.AndroidLogger()) MarketingCloudSdk.setLogLevel(MCLogListener.VERBOSE) MarketingCloudSdk.setLogListener(MCLogListener.AndroidLogListener()) } SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { engagementModuleConfig = MarketingCloudConfig.builder().apply { setApplicationId("{mc_application_id}") setAccessToken("{mc_access_token}") setMarketingCloudServerUrl("{marketing_cloud_url}") // Other configuration options }.build(applicationContext) }) { initStatus - > // TODO handle initialization status } } } ``` Next, update the code in your app for any of the SDK functions that you use. - [Register Contacts](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v10_register_contacts.md) - [Contact Dissociation](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v10_contact_dissociation.md) - [Set Contact Attributes](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v10_contact_attributes.md) - [Set Contact Tags](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v10_contact_tags.md) - [Set Runtime Toggles](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v10_runtime_toggles.md) - [In-App Messaging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v10_in_app_messaging.md) - [Inbox Messaging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v10_inbox_messaging.md) - [Location Messaging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v10_location_messaging.md) - [Beacons](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v10_beacons.md) - [Analytics](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v10_analytics.md) # Migrate Android Apps to Version 11 of the SDK Upgrading to Version 11 is a sequential process. To ensure a successful integration, you must first complete the [version 10 migration](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v10.md) before applying the final version 11 updates. To migrate your Android apps to version 11 of the SDK, you must update your project to support a modular architecture by [Updating Imports](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v11_update_imports.md) and reconfiguring [In-App Messaging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v11_in_app_messaging.md). # Migrate from Version 9 to Version 10 of the SDK Version 10 supplants versions 9 and earlier. Version 10 includes changes to initialization, contact management, and the availability of certain features. To migrate your apps to version 10 of the SDK, you must replace some code in your app. For more information about updating Android apps to version 10 of the SDK, see [Migrate to the SDK for Android Version 10](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v10.md). For more information about updating iOS apps to version 10 of the SDK, see [Migrate to the SDK for iOS Version 10](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v10.md). # Migrate iOS Apps to Version 10 of the SDK The process for migrating your iOS apps to version 10 of the SDK depends on which features you use. To start the process of migrating your apps, use this code example to update the initialization code in your app to use version 10 of the SDK. ```swift // Marketing Cloud SDK Configuration let mcAppID = "YOUR_MARKETING_CLOUD_APP_ID" let mcAccessToken = "YOUR_MARKETING_CLOUD_ACCESS_TOKEN" let mcServerURL = "YOUR_MARKETING_CLOUD_SERVER_URL" let mcMid = "YOUR_MARKETING_CLOUD_MID" // Define features of Marketing Cloud your app will use. let mcInboxEnabled = false let mcLocationEnabled = false let mcAnalyticsEnabled = true // MarketingCloud SDK: REQUIRED IMPLEMENTATION @discardableResult func configureSdk() -> Bool { var configBuilder = ConfigBuilder() // Enable logging for debugging early on. Debug level is not recommended for production apps, as significant data // about the SDK will be logged to the console. #if DEBUG SFMCSdk.setLogger(logLevel: .debug) #endif // Use the `MarketingCloudSdkConfigBuilder` to configure the MarketingCloud SDK. This gives you the maximum flexibility in SDK configuration. // The builder lets you configure the module parameters at runtime. let engagementConfiguration = MarketingCloudSdkConfigBuilder(appId: mcAppID) .setAccessToken(mcAccessToken) .setMarketingCloudServerUrl(URL(string: mcServerURL)!) .setMid(mcMid) .setInboxEnabled(mcInboxEnabled) .setLocationEnabled(mcLocationEnabled) .setAnalyticsEnabled(mcAnalyticsEnabled) .build() configBuilder = configBuilder .setEngagement(config: engagementConfiguration) let pushFeatureConfiguration = PushFeatureConfigBuilder() .setApplicationControlsBadging(true) .build() configBuilder = configBuilder .setPushFeature(config: pushFeatureConfiguration) // Set the completion handler to take action when all modules initialization is completed. // Seting the completion handler is optional. let completionHandler: ((_ status: [ModuleInitStatus]) -> Void) = { [weak self] status in DispatchQueue.main.async { self?.handleSDKInitializationCompletion(status: status) } } SFMCSdk.initializeSdk(configBuilder.build(), completion: completionHandler) return true } // MARK: - SDK Initialization Completion Handler private func handleSDKInitializationCompletion(status: [ModuleInitStatus]) { var allSuccessful = true for moduleStatus in status { print("Module: \(moduleStatus.moduleName.rawValue), Status: \(moduleStatus.initStatus.rawValue)") if moduleStatus.initStatus == .success { // Handle successful initialization for each module switch moduleStatus.moduleName { case .engagement: // Handle successful initialization for Marketing cloud module case .pushFeature: // Handle successful initialization for Push Feature module default: break } } else if moduleStatus.initStatus == .error { allSuccessful = false // module failed to initialize, check logs for more details } else if moduleStatus.initStatus == .cancelled { allSuccessful = false // module initialization was cancelled (for example due to re-confirguration triggered before init was completed) } else if moduleStatus.initStatus == .timeout { allSuccessful = false // module failed to initialize due to timeout, check logs for more details } } if allSuccessful { print("SDK initialization completed successfully") } else { print("SDK initialization completed with errors - check logs above") } } ``` Next, update the code in your app for the features you use. - [Update CocoaPods Imports](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v10_cocoapods.md) - [Register Contacts](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v10_register_contacts.md) - [Contact Dissociation](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v10_contact_dissociation.md) - [Set Contact Attributes](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v10_contact_attributes.md) - [Set Contact Tags](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v10_contact_tags.md) - [Set Runtime Toggles](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v10_runtime_toggles.md) - [In-App Messaging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v10_in_app_messaging.md) - [Location Messaging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v10_location_messaging.md) - [Analytics](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v10_analytics.md) # Migrate iOS Apps to Version 10 of the SDK using CocoaPods To migrate your iOS apps to version 10 of the SDK using CocoaPods, remove the existing SDK imports and add these imports: ```swift import MarketingCloudSDK import PushFeatureSDK ``` # Migrate iOS Apps to Version 11 of the SDK Upgrading to version 11 is a sequential process. To ensure a successful integration, you must first complete the [version 10 migration](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v10.md) before applying the final version 11 updates. The process for migrating your iOS apps to version 11 of the SDK depends on which features you use. To start the process of migrating your apps, use this code example to update the initialization code in your app to use version 11 of the SDK. ```swift // Marketing Cloud SDK Configuration let mcAppID = "" let mcAccessToken = "" let mcServerURL = "" let mcMid = "" // Define features of Marketing Cloud your app will use. let mcInboxEnabled = false let mcLocationEnabled = false let mcAnalyticsEnabled = true // MarketingCloud SDK: REQUIRED IMPLEMENTATION @discardableResult func configureSdk() -> Bool { var configBuilder = ConfigBuilder() // Enable logging for debugging early on. Debug level is not recommended for production apps, as significant data // about the SDK will be logged to the console. #if DEBUG SFMCSdk.setLogger(logLevel: .debug) #endif // Use the `MarketingCloudSdkConfigBuilder` to configure the MarketingCloud SDK. This gives you the maximum flexibility in SDK configuration. // The builder lets you configure the module parameters at runtime. let engagementConfiguration = MarketingCloudSdkConfigBuilder(appId: mcAppID) .setAccessToken(mcAccessToken) .setMarketingCloudServerUrl(URL(string: mcServerURL)!) .setMid(mcMid) .setInboxEnabled(mcInboxEnabled) .setLocationEnabled(mcLocationEnabled) .setAnalyticsEnabled(mcAnalyticsEnabled) .build() configBuilder = configBuilder .setEngagement(config: engagementConfiguration) let pushFeatureConfiguration = PushFeatureConfigBuilder() .setApplicationControlsBadging(true) .build() configBuilder = configBuilder .setPushFeature(config: pushFeatureConfiguration) // InAppMessageFeatureConfiguration let iamFeatureConfiguration = InAppMessagingFeatureConfigBuilder() .setEventDelegate(self) .setURLHandlingDelegate(self) .setInAppMessageFont(name: "HelveticaNeue") // Configures which permissions the iOS system dialog requests when the user taps a Push Primer in-app message button (defaults to [.alert, .sound, .badge] if not set). // .setNotificationAuthorizationOptions([.alert, .sound, .badge]) .build() configBuilder = configBuilder .setInAppMessagingFeature(config: iamFeatureConfiguration) // Set the completion handler to take action when all modules initialization is completed. // Seting the completion handler is optional. let completionHandler: ((_ status: [ModuleInitStatus]) -> Void) = { [weak self] status in DispatchQueue.main.async { self?.handleSDKInitializationCompletion(status: status) } } SFMCSdk.initializeSdk(configBuilder.build(), completion: completionHandler) return true } // MARK: - SDK Initialization Completion Handler private func handleSDKInitializationCompletion(status: [ModuleInitStatus]) { var allSuccessful = true for moduleStatus in status { print("Module: \(moduleStatus.moduleName.rawValue), Status: \(moduleStatus.initStatus.rawValue)") if moduleStatus.initStatus == .success { // Handle successful initialization for each module switch moduleStatus.moduleName { case .engagement: // Handle successful initialization for Marketing cloud module case .pushFeature: // Handle successful initialization for Push Feature module case .inappMessagingFeature: // Handle successful initialization for In-App Feature module default: break } } else if moduleStatus.initStatus == .error { allSuccessful = false // module failed to initialize, check logs for more details } else if moduleStatus.initStatus == .cancelled { allSuccessful = false // module initialization was cancelled (for example due to re-confirguration triggered before init was completed) } else if moduleStatus.initStatus == .timeout { allSuccessful = false // module failed to initialize due to timeout, check logs for more details } } if allSuccessful { print("SDK initialization completed successfully") } else { print("SDK initialization completed with errors - check logs above") } } ``` Next, update the code in your app for the features you use. - [Update Imports](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v11_update_imports.md) - [In-App Messaging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v11_in_app_messaging.md) # Migrate to Flutter Unified Plugin Migrate from the Marketing Cloud Engagement-specific or the Marketing Cloud Next-specific Flutter plugins to the unified Flutter plugin model. ## Overview The previous Flutter integration for Marketing Cloud Engagement uses one monolithic package (`sfmc`) and one static class (`SFMCSdk`) for all features. Similarly, the integration for Marketing Cloud Next uses a separate monolithic package (`mam`) with its own static class (`MobileAppMessaging`). The key changes in the Flutter unified implementation are: - The previous monolithic packages are split into focused packages: `sfmc_core` for core services, `sfmc_push` for push notifications, `sfmc_iam` for in-app messaging, `sfmc_marketingcloudsdk` for Marketing Cloud Engagement, and `sfmc_mobileappmessaging` for Marketing Cloud Next. - Static method calls are replaced with async module initialization using `requestSdk()`. - Identity, attribute, and event-tracking methods are moved to `sfmc_core`. - In-App Messaging (`sfmc_iam`) is a new, optional feature package with lifecycle events and display control. No equivalent existed in the previous Engagement-specific Flutter plugin. - Several callback-based listeners, such as the listeners for registration events and push tokens, are replaced with Dart streams that use `EventChannel`. ## Package Mapping Use this table to map dependencies from the previous, non-unified plugin to their equivalent packages in the unified plugin. | Previous Flutter dependency | Unified Dependency | Required? | | ------------------------------------------------------ | ------------------------- | ------------------------------------------------------------------------------------ | | `sfmc` (MobilePush / Engagement) | `sfmc_marketingcloudsdk` | Required. This package replaces the Engagement-specific package. | | `mam` (Marketing Cloud Next) | `sfmc_mobileappmessaging` | Required. This package replaces the Marketing Cloud Next-specific package. | | Identity, attributes, and events bundled inside `sfmc` | `sfmc_core` | Auto-installed as a transitive dependency of any product package. | | Push messaging support bundled inside `sfmc` | `sfmc_push` | Required if your app sends push notifications. | | No Dart equivalent (native-only or config-only) | `sfmc_iam` | Required if your app uses in-app messages. This is a new capability with a Dart API. | ## Prerequisites Before you begin your migration, make sure you meet these prerequisites: - Have your existing Marketing Cloud configuration values—such as App ID, Access Token, Server URL, and MID—available. - Perform the migration on a feature branch. Avoid mixing the migration with unrelated work. - Be prepared to update both Dart call sites and native (Android and iOS) setup files. - Make sure your app meets these minimum requirements: | Components | Minimum Requirement | | ---------- | ------------------------ | | Flutter | 3.3.0 or later | | Dart SDK | >=3.0.6 <4.0.0 | | iOS | 12.0 or later | | Android | minSdk 26, compileSdk 36 | # Migrate to React Native Unified Plugin Use this transition guidance to migrate from the Engagement-specific `react-native-marketingcloudsdk` model to the React Native unified plugin model. **note:** This topic applies only to the customers who use the Engagement-specific React Native implementation. ## Overview The previous React Native integration for Marketing Cloud Engagement uses one package and one static module (`MCReactModule`) for all features. The React Native unified plugin integration uses modular packages with async `requestSdk()` APIs. This model aligns with the native unified SDK architecture and lets you install only the modules you use. The key changes in the React Native unified implementation are: - The previous React-Native all-in-one package is split into multiple focused packages (`sfmc-core`, `push`, `iam`, `marketingcloudsdk`). - Static method calls are replaced with async module initialization using `requestSdk()`. - Identity, attributes, and event-tracking methods are moved to `sfmc-core`. - The React Native unified plugins require React Native New Architecture (TurboModules). The bridge support is removed. ## Engagement-specific and Unified Package Mapping Use this table to map your previous dependency to the unified packages. While the previous plugin came as a single package, the unified plugin is split into a core product package and several optional feature packages. | Engagement-specific React Native dependency | Unified dependency | Required? | | ----------------------------------------------------------------------- | -------------------------------------- | ------------------------------------------------------------------------------ | | `react-native-marketingcloudsdk` (MobilePush / Engagement) | `@sfmc/react-native-marketingcloudsdk` | Required. This package replaces the MobilePush or Engagement-specific package. | | SFMC core bundled inside the Engagement-specific package | `@sfmc/react-native-sfmc-core` | Auto-installed as a transitive dependency of any product package. | | Push messaging support bundled inside the Engagement-specific package | `@sfmc/react-native-push` | Required if your app sends push notifications. | | In-app messaging support bundled inside the Engagement-specific package | `@sfmc/react-native-iam` | Required if your app uses in-app messages. | ## Prerequisites The unified plugins require a substantial baseline change from the Engagement-specific plugin. Before you begin your migration, make sure you meet these prerequisites: - Enable React Native New Architecture app-wide. The unified plugins only run on the new architecture (TurboModules) and doesn't support the bridge that was supported in Engagement-specific React Native plugin. If your app is still on the previous bridge architecture, enable the new architecture app-wide. For more information, see [About the New Architecture](https://reactnative.dev/architecture/landing-page). - Upgrade React Native version to 0.85.1 or later. Upgrade to React Native 0.85.1 or later. Unlike the Engagement-specific React Native plugin, which supported version 0.60 and later, the unified plugins require this higher version. - Keep your existing Marketing Cloud configuration values available and confirm your App ID, Access Token, Server URL, and MID. - Perform the migration on a feature branch. Avoid mixing the migration with unrelated work. - Be prepared to update both JavaScript or TypeScript call sites, and native setup files. - Make sure your app meets these minimum requirements: | Components | Minimum Requirement | | ---------------- | ----------------------------------------------- | | React Native | 0.85.1 or later (with New Architecture enabled) | | React | 19.0 or later (tested against 19.2.3) | | Node.js | 20 or later | | iOS | 15.1 or later (Xcode 16 or later) | | Android | minSdk 26, compileSdk 36 or later | | Ruby (CocoaPods) | 3.1.0 or later | # Migrate to Version 11 of the SDK Version 11 replaces versions 10 and earlier of the SDK. For more information about updating Android apps to version 11 of the SDK, see [Migrate to the SDK for Android Version 11](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v11.md). For more information about updating iOS apps to version 11 of the SDK, see [Migrate to the SDK for iOS Version 11](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v11.md). # Migrate to Version 8 of MobilePush SDK for Android The version 8.x update of the MobilePush Android SDK sets a more modern architectural foundation to enable a variety of improvements and all new features for future versions. The updated MobilePush SDK is designed with existing MobilePush customers in mind so that the upgrade path is light and straightforward. ## Add the New MobilePush Android SDK Add the new MobilePush Android SDK version 8.x as a dependency to your `build.gradle` file, as shown in this example. ```java implementation("com.salesforce.marketingcloud:marketingcloudsdk:8.x") ``` To use the latest SDK version, replace 8.x with the latest version number available on the [Change Log](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_changelog.md). ## Initialize the SDK After you add the new SDK as a dependency, replace your existing initialization function to reference the new SDK. After your project retrieves the updated SDK version, the functions that must be modified are highlighted in your code. Ensure that you update how you initialize the SDK. You must replace the previous [MarketingCloudSDK.init](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/MarketingCloudSdk/7.4/com.salesforce.marketingcloud/-marketing-cloud-sdk/init.html) function with the new [SFMCSdk.configure](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/8.0/-s-f-m-c%20-s-d-k/com.salesforce.marketingcloud.sfmcsdk/-s-f-m-c-sdk/-companion/configure.html) function. **note:** The `SFMCSdk.configure` function takes in [MarketingCloudConfig](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/MarketingCloudSdk/9.0/-marketing%20-cloud%20-s-d-k/com.salesforce.marketingcloud/-marketing-cloud-config/index.html) as a parameter. This configuration is the same as the one you’re using for your existing implementation and doesn’t need to be changed. ## Update Identity Functions Next, update the existing identity functions within the SDK according to the following instructions. 1. Set the identity or ID of a known user: Update your existing identity tracking function [setContactKey](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/MarketingCloudSdk/7.4/com.salesforce.marketingcloud.registration/-registration-manager/-editor/set-contact-key.html) to instead use the new [setProfileID](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/8.0/-s-f-m-c%20-s-d-k/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity/set-profile-id.html) function. 2. Set the Attributes of a user: Update your existing identity tracking function [setAttribute](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/MarketingCloudSdk/7.4/com.salesforce.marketingcloud.registration/-registration-manager/-editor/set-attribute.html) to instead use the new [setProfileAttributes](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/8.0/-s-f-m-c%20-s-d-k/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity/set-profile-attributes.html) function. ## Update Remaining Functions Update all of the functions in your implementation to reference functions from the new SDK. All existing functions that require modification are highlighted as `deprecated` in your codebase. # Migrate to Version 8 of MobilePush SDK for iOS The MobilePush SDK version 8.x update sets a more modern architectural foundation to enable a variety of improvements and all new features for future versions. The updated MobilePush SDK is designed with existing MobilePush customers in mind so that the upgrade path is light and straightforward. To migrate to MobilePush SDK version 8 or later, follow these steps. - [Add the New iOS SDK Build](#add-the-new-ios-sdk-build) - [Initialize the SDK](#initialize-the-sdk) - [Update Identity Functions](#update-identity-functions) - [Update Remaining Functions](#update-remaining-functions) - [Capture Notifications On Launch (Only for 8.0.x)](#capture-notifications-on-launch-only-for-80x) ## Add the New iOS SDK Build 1. Remove the existing CocoaPods dependency before adding `MarketingCloudSDK` from Swift Package Manager (MobilePush). 2. Add the [MobilePush dependency](https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS) (tag `8.x`) to your application target. If you use version 8.0.13 or earlier of the SDK, add the [`SFMCSDK`](https://github.com/salesforce-marketingcloud/sfmc-sdk-ios) (tag `1.x`) and [MobilePush](https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS) (tag `8.x`) dependencies to your application target. Manually pull the `Resources/MarketingCloudSDK.bundle` from the `sources` folder in the `MarketingCloudSDK` Swift module and add it as a resource within **Copy Bundle Resources** in the build phase configuration. If you don't complete this step, you'll encounter this error: `Thread 1: Cannot create an NSPersistentStoreCoordinator with a nil model`. ## Initialize the SDK You must replace your existing initialization function to reference the new SDK. After you’ve fetched the updated SDK version in your project, the functions that must be modified are highlighted in your codebase. 1. Update the configuration builder function as shown in this example. 2. Ensure that the SDK has initialized correctly by using a check on the status of initialization or by using the completion handler, as shown in this example. ```swift // Old let builder = MarketingCloudSDKConfigBuilder() .sfmc_setApplicationId(appID) .sfmc_setAccessToken(accessToken) .sfmc_setMarketingCloudServerUrl(appEndpoint) .sfmc_build()! var success = false do { try MarketingCloudSDK.sharedInstance().sfmc_configure(with:builder) success = true } catch let error as NSError { // error logic } if success == true { //function logic } // New // With manual check on the module initialization success let configuration = PushConfigBuilder(appId: PUSH_APP_ID) .setAccessToken(PUSH_ACCESS_TOKEN) .setMarketingCloudServerUrl(URL(string: PUSH_TSE)!) .build() SFMCSdk.initializeSdk(ConfigBuilder().setPush(config: configuration).build()) if SFMCSdk.mp.getStatus() == .operational { //function logic } // Or with using the completion handler let configuration = PushConfigBuilder(appId: PUSH_APP_ID) .setAccessToken(PUSH_ACCESS_TOKEN) .setMarketingCloudServerUrl(URL(string: PUSH_TSE)!) .build() SFMCSdk.initializeSdk(ConfigBuilder() .setPush( config: configuration, onCompletion: {result in print("TODO, Module initialization result is: \(result.rawValue)")} ).build()) ``` ## Update Identity Functions 1. Set the identity or ID of a known user: Replace your current identity tracking function `setContactKey` with the updated function `setProfileID`. 2. Set the Attributes of a user: Replace your existing identity tracking function `setAttribute` with the updated function `setProfileAttributes`. ```swift // Old MarketingCloudSDK.sharedInstance().sfmc_setContactKey("john.smith") // New SFMCSdk.identity.setProfileId("john.smith") ``` ## Update Remaining Functions Align your existing functions with updated functions provided by the new SDK. All existing functions that need changes are marked as `deprecated` in your codebase. ## Capture Notifications On Launch (Only for 8.0.x) **note:** If you’re using version 8.1.x of the SDK, you don’t need to perform this step. Using the new `requestPushSdk` API enables the SDK to automatically capture notifications for you, regardless of the application’s state and the SDK initialization status. For a complete implementation example, see the [iOS LearningApp](https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS/blob/spm/examples/LearningApp/LearningApp/AppDelegate.swift#L251-L253). To ensure push notifications are processed accurately when your application isn’t actively running, capture them during application launch and store them in memory until the SDK initializes fully. Failing to do so prevents the SDK from processing incoming push notifications. After the SDK is operational, the notification is set to the SDK using `setNotificationUserInfo` API, as shown in this example. ```swift // Add a member variable in the AppDelegate class @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { // ... // Notification to capture var notificationUserInfo:[AnyHashable:Any]? // ----------------------------- func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Extract the notification from launchOptions if let options = launchOptions, let notification = options[UIApplication.LaunchOptionsKey.remoteNotification] as? [AnyHashable: Any] { self.notificationUserInfo = notification } // ... let completionHandler: (OperationResult) -> () = { result in if result == .success { // Method to call when the SDK is ready self.setupMobilePush() } } // Initialize the SDK SFMCSdk.initializeSdk( ConfigBuilder().setPush( config: mobilePushConfiguration, onCompletion: completionHandler ).build() ) // ... } // ----------------------------- func setupMobilePush() { // ... // Provide the notification object to SDK when the SDK is ready. DispatchQueue.main.async { if let userInfo = self.notificationUserInfo { SFMCSdk.mp.setNotificationUserInfo(userInfo) } else { debugPrint("No notification UserInfo: - either it should be a direct launch or Notification userInfo is not available when launched from notification") } } } } ``` For a complete implementation example, see the [iOS LearningApp](https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS/blob/29240f99e5fab3e7e674a847c48253ade82b140a/examples/LearningApp/LearningApp/AppDelegate.swift#L186L191). # Migration Checklist Use this checklist to validate your migration to the Flutter unified plugins. ## Tasks to Review Manually These items aren't mapped automatically, so review them manually. - Identity-event patterns from the previous plugin code. - `EventCategory` usage (`identity`, `engagement`, `system`) in the previous plugin's `CustomEvent`. - Deprecated commerce event models (`CartEvent`, `OrderEvent`, `CatalogObjectEvent`) and their `subtype` value changes. - Dynamic event names and dynamic attribute keys. - `InboxMessage` date fields use a raw UTC `String`, instead of the `DateTime` used in the previous plugin. - Native push notification customization and URL and delegate handling logic. - Existing Firebase and APNs setup and permissions behavior. - Mobile App Messaging registration listener migration from a callback to the `registrationEvents` stream. ## Migration Completion Checklist Verify that all the required migration updates are complete before you publish your app. - The toolchains for Flutter, Dart, iOS, and Android meet the minimum requirements. - The `sfmc` and `mam` packages from the previous package are removed, and unified packages are added. - Dart call sites are updated to use the `requestSdk()` module. - Identity migration is completed by moving `setContactKey` to `SFMCSdkModule.setProfileId` and `getContactKey` to `getProfileId`. - Attribute and event tracking calls are moved to `SFMCSdkModule`. - Push APIs are migrated to `PushModule`. - Inbox and message-status API renames applied (`getMessages` changes to `getAllMessages`, `setMessageRead` changes to `markMessageRead`, and `deleteMessage` changes to `markMessageDeleted`). - Analytics boolean setter patterns are replaced with enable and disable methods. - Event class usage is migrated to unified event objects, or replaced with `CustomEvent`. - Event listeners are migrated to `Stream` subscriptions, such as `registrationEvents`, `pushTokenStream`, and `inAppMessageEvents`. - In-App Messaging is integrated through `sfmc_iam` if your app uses it. - Android and iOS native configurations are migrated to module-based setup. - Items flagged for manual review are resolved. - End-to-end runtime validation is complete on both Android and iOS. # Migration Checklist Use this checklist to validate your migration to the React Native unified plugins. ## Tasks to Review Manually These items aren't mapped automatically, so review them manually: - Identity-event patterns from the previous plugin code. - `CustomEvent` category usage in the previous plugin. - Deprecated commerce event models (`CartEvent`, `OrderEvent`, `CatalogEvent` patterns). - Dynamic event names and dynamic attribute keys. - Native push notification customization and URL/delegate handling logic. - Existing Firebase/APNs setup and permissions behavior. ## Migration Completion Checklist Verify that all required migration updates are complete before release. - App is on React Native 0.85.1 with New Architecture enabled. - Toolchains meet minimum requirements (iOS, Android, Node.js, Ruby). - The package from the previous plugin is removed, and unified packages are added. - JavaScript and TypeScript call sites updated to module `requestSdk()` usage. - Identity migration completed (`setContactKey` and `getContactKey` moved to core profile APIs). - Attribute and event tracking calls moved to `SFMCSdkModule`. - Push APIs migrated to `PushModule`. - Inbox and message-status API renames applied. - Analytics boolean setter patterns replaced with enable/disable methods. - Event class usage migrated to `objType` event objects. - Event listeners migrated to module emitter subscriptions. - Android and iOS native configuration migrated to module-based setup. - Manual review items are resolved or explicitly accepted. - End-to-end runtime validation is complete on both Android and iOS. # Migration Steps Migrate your app from the Marketing Cloud Engagement-specific or Marketing Cloud Next-specific Flutter plugins to the unified Flutter plugin. ## Swap Dependencies 1. Remove the previous plugin package. ``` flutter pub remove sfmc ``` 2. Add the unified product package for each product that you use. ``` flutter pub add sfmc_marketingcloudsdk flutter pub add sfmc_mobileappmessaging ``` 3. To use the push or in-app messaging feature packages, add them to your configuration. ``` flutter pub add sfmc_push flutter pub add sfmc_iam ``` 4. For iOS apps, reinstall your pods. ``` cd ios pod install ``` ## Update the Initialization Model 1. Replace static `SFMCSdk` and `MobileAppMessaging` usage with module initialization through `requestSdk()`. 2. Initialize required modules at app startup and reuse those instances. ``` import 'package:sfmc_core/sfmc_core.dart'; import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; import 'package:sfmc_push/sfmc_push.dart'; import 'package:sfmc_iam/sfmc_iam.dart'; await SFMCSdkModule.requestSdk(); await MarketingCloudSdk.requestSdk(); await PushModule.requestSdk(); await IamModule.requestSdk(); ``` ## Migrate Dart Call Sites 1. Update method calls based on module ownership and method renames. | Previous Flutter Plugin Usage | Flutter Unified Plugin Usage | Module | | --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | ------------------------------------------------ | | `setContactKey`, `getContactKey` | `setProfileId`, `getProfileId` | `SFMCSdkModule` | | `setAttribute`, `clearAttribute`, `getAttributes`, `trackEvent` | `setAttribute`, `clearAttribute`, `getAttributes`, `track` (moved) | `SFMCSdkModule` | | `getSystemToken` | `getPushToken` | `PushModule` | | `addTag`, `removeTag`, `getTags` | same methods (moved) | `MarketingCloudSdk` | | `getMessages`, `setMessageRead`, `deleteMessage` | `getAllMessages`, `markMessageRead`, `markMessageDeleted` | `MarketingCloudSdk` | | `refreshInbox(callback)` | `refreshInbox()` (no callback. Returns `Future`) | `MarketingCloudSdk` | | `analytics`, `piAnalytics`, `registration` | module-specific methods | `MarketingCloudSdk` | | `MobileAppMessaging.getDeviceId`, `isAnalyticsEnabled`, `enableAnalytics`, `disableAnalytics` | same methods (moved) | `MobileAppMessaging` (`sfmc_mobileappmessaging`) | | `MobileAppMessaging.registerForRegistrationEvents(callback)` | `setRegistrationCallback()` + `registrationEvents` stream | `MobileAppMessaging` | 2. Find references to previous plugin call sites and update them. ``` rg "SFMCSdk\\.|MobileAppMessaging\\." rg "setContactKey|getContactKey|getSystemToken|setMessageRead|deleteMessage|logSdkState|registerForRegistrationEvents" ``` 3. Rename essential methods: - Change `getSystemToken` to `getPushToken`. - Change `getMessages` to `getAllMessages`. - Change `setMessageRead` to `markMessageRead`. - Change `deleteMessage` to `markMessageDeleted`. 4. Apply these additional required call-site updates: - Replace analytics boolean setters with explicit methods: - Change `setAnalyticsEnabled(true|false)` to `enableAnalytics()` / `disableAnalytics()`. - Change `setPiAnalyticsEnabled(true|false)` to `enablePiAnalytics()` / `disablePiAnalytics()`. - Replace identity APIs: - Change `setContactKey` to `setProfileId` and change `getContactKey` to `getProfileId` on `SFMCSdkModule`. - Update logging and SDK state handling: - Change `SFMCSdk.enableLogging()` and `disableLogging()` to `SFMCSdkModule.setLogging(LogLevel.debug|LogLevel.none)`. - Change `logSdkState()` to `SFMCSdkModule.getSdkState()` and log the returned value in your app. - Update `refreshInbox` call sites to drop the callback argument. It now returns `Future` directly. - Adopt new inbox tracking by using `MarketingCloudSdk.trackInboxMessageOpened(id)`. This method doesn't have an equivalent in the non-unified plugin. ## Migrate the Event Model 1. Update `CustomEvent` calls. The `category` argument is removed. Use the dedicated event classes instead. ``` // Previous Plugin // SFMCSdk.trackEvent(CustomEvent('Purchase', attributes: {'Total': 1234})); // Unified await SFMCSdkModule.track(CustomEvent(name: 'Purchase', attributes: {'Total': 1234})); ``` 2. Validate event attribute value types. Unified event attributes support these value types: - `String` - `num` - `bool` 3. Convert unsupported payload values from the previous plugin before tracking. If payloads from the previous plugin contain nested objects, arrays, or `null`, convert them to supported value types. 4. Remove unsupported event patterns from the previous plugin: - `EventCategory.identity` custom events have no direct equivalent in the unified model. Use `setProfileId` and `setAttribute` instead. - `CartEvent`, `OrderEvent`, and `CatalogObjectEvent` exist in the unified plugin but are deprecated in favor of `CustomEvent`. If you keep using them, note that their `subtype` values use short codes, for example, `'comment'`, instead of the previous plugin's descriptive factory names (for example, `"Comment Catalog Object"`). ## Migrate Event Listeners 1. Move callback-based listeners to `Stream` subscriptions. ``` import 'package:sfmc_marketingcloudsdk/sfmc_marketingcloudsdk.dart'; import 'package:sfmc_mobileappmessaging/sfmc_mobileappmessaging.dart' as mam; import 'package:sfmc_push/sfmc_push.dart'; import 'package:sfmc_iam/sfmc_iam.dart'; // Engagement registration changes: final regSub = MarketingCloudSdk.registrationEvents.listen((reg) { print('registration: $reg'); }); // Marketing Cloud Next registration changes: final mamRegSub = mam.MobileAppMessaging.registrationEvents.listen((reg) { print('mam registration: $reg'); }); // Push token refresh: final tokenSub = PushModule.pushTokenStream.listen((token) { print('new token: $token'); }); // In-App Messaging lifecycle: final iamSub = IamModule.inAppMessageEvents.listen((event) { switch (event.type) { case InAppMessageEventType.shouldShow: break; case InAppMessageEventType.didShow: break; case InAppMessageEventType.didClose: break; } }); // Always cancel subscriptions when no longer needed: regSub.cancel(); mamRegSub.cancel(); tokenSub.cancel(); iamSub.cancel(); ``` 2. Enable the registration callback before subscribing. Call `setRegistrationCallback()` on `MarketingCloudSdk` or `MobileAppMessaging` before subscribing to their respective `registrationEvents` streams. 3. Apply platform listener caveats: - The inbox response listener, `registerInboxResponseListener`, uses the previous callback-list pattern instead of a `Stream`. - Location-watching APIs (`startWatchingLocation`, `stopWatchingLocation`, `isWatchingLocation`, and `getLastKnownLocation`) work only with iOS apps. - Proximity messaging APIs (`enableProximityMessaging`, `disableProximityMessaging`, and `isProximityMessagingEnabled`) work only with Android apps. 4. Determine when to display an in-app message. Use this capability only if your app needs to allow or suppress in-app messages based on runtime logic. ``` IamModule.setInAppMessageDecisionHandler((message) { // Return (or resolve) true to display, false to suppress. return message.title != 'Suppress me'; }); // Clear the handler (restore default "always show"): IamModule.setInAppMessageDecisionHandler(null); ``` ## Update Platform-Specific Configurations 1. Update both native platforms to the module-based unified configuration model. - For Android apps, migrate your `Application` class setup to use module-based config blocks. For more information, see [Configure Flutter for Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/configure-flutter-android.md) and [Integrate the Android SDK](https://developer.salesforce.com/docs/mc_next/mc_next_integrate_android/mc_next_integrate_android.md#initialize-the-sdk). - For iOS apps, migrate your `AppDelegate.swift` setup to use module-based config blocks. For more information, see [Configure Flutter for iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/configure-flutter-ios.md) and [Integrate the iOS SDK](https://developer.salesforce.com/docs/mc_next/mc_next_integrate_ios/mc_next_integrate_ios.md). - Reapply existing notification, URL-handling, and delegate customization in the new module configuration. 2. Update Android apps to initialize using module-based configuration. ``` import com.salesforce.marketingcloud.MarketingCloudConfig import com.salesforce.marketingcloud.pushfeature.config.PushFeatureConfig import com.salesforce.marketingcloud.inappmessagingfeature.config.InAppMessagingFeatureConfig import com.salesforce.marketingcloud.sfmcsdk.SFMCSdk import com.salesforce.marketingcloud.sfmcsdk.SFMCSdkModuleConfig SFMCSdk.configure(this, SFMCSdkModuleConfig.build { engagementModuleConfig = MarketingCloudConfig.builder() .setApplicationId(BuildConfig.MC_APP_ID) .setAccessToken(BuildConfig.MC_ACCESS_TOKEN) .setMarketingCloudServerUrl(BuildConfig.MC_SERVER_URL) .setMid(BuildConfig.MC_MID) .setInboxEnabled(true) .build(this@Application) pushFeatureModuleConfig = PushFeatureConfig.builder() .setNotificationCustomizationOptions(/* your notification options */) .setUrlHandler(/* your UrlHandler */) .setShouldShowNotificationListener(/* your ShouldShowNotificationListener */) .build() inAppMessagingFeatureModuleConfig = InAppMessagingFeatureConfig.builder() .setUrlHandler(/* your UrlHandler */) .build() // If you also migrate Marketing Cloud Next, add its module config // alongside engagementModuleConfig (mamModuleConfig). }) { initStatus -> Log.i("SFMC", "SFMC SDK initialization status: $initStatus") } ``` 3. Update iOS apps to initialize using module-based configuration. If you also migrate Marketing Cloud Next, add its builder alongside `setEngagement`. ``` import SFMCSDK import PushFeatureSDK import InAppMessagingFeatureSDK import MarketingCloudSDK var configBuilder = ConfigBuilder() if let appEndpoint = URL(string: appEndpointURL) { let engagementConfig = MarketingCloudSdkConfigBuilder(appId: appID) .setAccessToken(accessToken) .setMarketingCloudServerUrl(appEndpoint) .setMid(mid) .setInboxEnabled(true) .setLocationEnabled(true) .setAnalyticsEnabled(true) .build() configBuilder = configBuilder.setEngagement(config: engagementConfig) } let pushConfig = PushFeatureConfigBuilder() .setApplicationControlsBadging(true) .build() configBuilder = configBuilder.setPushFeature(config: pushConfig) let iamConfig = InAppMessagingFeatureConfigBuilder().build() configBuilder = configBuilder.setInAppMessagingFeature(config: iamConfig) SFMCSdk.initializeSdk(configBuilder.build()) { status in // Inspect [ModuleInitStatus] per module. } ``` 4. Verify mandatory platform configuration requirements. - Flutter, Dart SDK, iOS, and Android minimums match the unified plugin requirements. - Android build minimums match the required versions. For example, minSdk and compileSdk. - Android 13+ push permission (`POST_NOTIFICATIONS`) is requested for push flows. - iOS deployment target minimum matches the unified plugin requirement. - Keep all existing notification, URL-handling, and delegate forwarding logic when porting to module-based initialization. For more information, see [Prerequisites](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/migrate-to-flutter-unified-plugin.md#prerequisites). 5. Find native initialization files and verify your final setup. ``` rg "SFMCSdk|MarketingCloudConfig|ConfigBuilder" android ios ``` ## See Also [Migration Checklist](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/flutter-migration-checklist.md) # Migration Steps Use these steps to migrate your app from the Engagement-specific React Native plugin to the React Native unified plugins. ## Swap Dependencies 1. Remove the Marketing Cloud Engagement-specific package. ``` yarn remove react-native-marketingcloudsdk ``` 2. Add the unified product package. ``` yarn add @sfmc/react-native-marketingcloudsdk ``` 3. To use the push or IAM feature packages, add them to your configuration. ``` yarn add @sfmc/react-native-push yarn add @sfmc/react-native-iam ``` 4. Reinstall iOS pods. ``` cd ios pod install ``` ## Update the Initialization Model 1. Replace static `MCReactModule` usage with module initialization through `requestSdk()`. 2. Initialize required modules at app startup and reuse those instances. ``` import { SFMCSdkModule } from '@sfmc/react-native-sfmc-core'; import { PushModule } from '@sfmc/react-native-push'; import { MCModule } from '@sfmc/react-native-marketingcloudsdk'; const [sfmc, push, mc] = await Promise.all([ SFMCSdkModule.requestSdk(), PushModule.requestSdk(), MCModule.requestSdk(), ]); ``` `requestSdk()` caches the initialized SDK instance, so calling it again returns the same module instance. ## Migrate JavaScript and TypeScript Call Sites 1. Update method calls based on module ownership and method renames. | Engagement-specific React Native usage | React Native unified plugin usage | Module | | ------------------------------------------------ | --------------------------------------------------------- | --------------- | | `setContactKey`, `getContactKey` | `setProfileId`, `getProfileId` | `SFMCSdkModule` | | `setAttribute`, `getAttributes`, `track` | same methods (moved) | `SFMCSdkModule` | | `getSystemToken` | `getPushToken` | `PushModule` | | `getMessages`, `setMessageRead`, `deleteMessage` | `getAllMessages`, `markMessageRead`, `markMessageDeleted` | `MCModule` | | `tags`, `analytics`, `registration` | `module-specific methods` | `MCModule` | 2. Find references to previous plugin call sites and update them. ``` rg "MCReactModule\\." rg "setContactKey|getContactKey|getSystemToken|setMessageRead|deleteMessage" ``` 3. Apply essential method renames: - `getSystemToken` -> `getPushToken` - `setMessageRead` -> `markMessageRead` - `deleteMessage` -> `markMessageDeleted` 4. Apply these additional required call-site updates: - Replace analytics boolean setters with explicit methods: - `setAnalyticsEnabled(true|false)` -> `enableAnalytics()` / `disableAnalytics()` - `setPiAnalyticsEnabled(true|false)` -> `enablePiAnalytics()` / `disablePiAnalytics()` - Replace identity APIs: - `setContactKey` / `getContactKey` -> `setProfileId` / `getProfileId` - Update logging and SDK state handling: - `enableLogging` / `disableLogging` -> `setLogging('DEBUG'|'NONE')` (or module-specific logging APIs) - `logSdkState()` -> `getSdkState()` and log the returned object in your app. ## Migrate the Event Model 1. Replace event classes from the previous plugin with unified event objects that use `objType`. ``` // Previous Plugin // MCReactModule.track(new CustomEvent('Purchase', { Total: 1234 })); // Unified sfmc.track({ objType: 'CustomEvent', name: 'Purchase', attributes: { Total: 1234 } }); ``` 2. Validate event attribute value types. Unified event attributes supports these value types: - `string` - `number` - `boolean` 3. Convert unsupported payload values from the previous plugin before tracking. If payload from the previous plugin contain nested objects, arrays, or `null`, convert them to supported value types. 4. Remove unsupported event patterns from the previous plugin: - `IdentityEvent` has no direct equivalent in the unified model. Use core identity APIs instead. - `CustomEvent` category argument is not supported in unified event objects. ## Migrate Event Listeners 1. Move listener logic to module emitters. ``` import { MCModule } from '@sfmc/react-native-marketingcloudsdk'; import { PushModule } from '@sfmc/react-native-push'; import { IamModule, IamEvent } from '@sfmc/react-native-iam'; // Engagement registration changes: const regSub = MCModule.getEmitter().addListener('sfmc_mc_registration', (reg) => { console.log('registration', reg); }); // Push token refresh (Android): const tokenSub = PushModule.getEmitter().addListener('sfmc_push_token_refreshed', (token) => { console.log('new token', token); }); // In-App Messaging lifecycle: const willShow = IamModule.getEmitter().addListener(IamEvent.WillShowMessage, (msg) => { /* ... */ }); const didShow = IamModule.getEmitter().addListener(IamEvent.DidShowMessage, (msg) => { /* ... */ }); const didClose = IamModule.getEmitter().addListener(IamEvent.DidCloseMessage, (msg) => { /* ... */ }); // Always remove listeners on unmount: regSub.remove(); tokenSub.remove(); willShow.remove(); didShow.remove(); didClose.remove(); ``` 2. Enable registration callback before subscribing. Call `setRegistrationCallback()` before subscribing to registration events. 3. Apply platform listener caveats: - IAM event constants are exported via `IamEvent`. - Engagement and push event names are subscribed using string event names. - Push token refresh listener is Android-only. - Inbox response listener behavior differs by platform; validate behavior on both Android and iOS. 4. (Optional) Gate whether an in-app message displays. Use this only if your app needs to allow or suppress in-app messages based on runtime logic. ``` IamModule.setInAppMessageDecisionHandler((message) => { // return (or resolve) true to display, false to suppress return message.title !== 'Suppress me'; }); // Clear the handler (restore default "always show"): IamModule.setInAppMessageDecisionHandler(null); ``` ## Update Native Configuration (Android and iOS) 1. Update both native platforms to the module-based unified configuration model. - Android: migrate `MainApplication.kt` setup to module-based config blocks. For more information about Android configuration, see [Integrate the Android SDK](https://developer.salesforce.com/docs/mc_next/mc_next_integrate_android/mc_next_integrate_android.md#initialize-the-sdk). - iOS: migrate `AppDelegate.swift` setup to module-based config blocks. For more information about iOS configuration, see [Integrate the iOS SDK](https://developer.salesforce.com/docs/mc_next/mc_next_integrate_ios/mc_next_integrate_ios.md). - Reapply existing notification, URL-handling, and delegate customization in the new module configuration. 2. Update Android native initialization using module-based configuration. ``` import com.salesforce.marketingcloud.MarketingCloudConfig import com.salesforce.marketingcloud.pushfeature.config.PushFeatureConfig import com.salesforce.marketingcloud.inappmessagingfeature.config.InAppMessagingFeatureConfig import com.salesforce.marketingcloud.sfmcsdk.SFMCSdk import com.salesforce.marketingcloud.sfmcsdk.SFMCSdkModuleConfig SFMCSdk.configure(this, SFMCSdkModuleConfig.build { engagementModuleConfig = MarketingCloudConfig.builder() .setApplicationId(BuildConfig.MC_APP_ID) .setAccessToken(BuildConfig.MC_ACCESS_TOKEN) .setMarketingCloudServerUrl(BuildConfig.MC_SERVER_URL) .setMid(BuildConfig.MC_MID) .setInboxEnabled(true) .build(this@MainApplication) pushFeatureModuleConfig = PushFeatureConfig.builder() .setNotificationCustomizationOptions(/* your notification options */) .setUrlHandler(/* your UrlHandler */) .setShouldShowNotificationListener(/* your ShouldShowNotificationListener */) .build() inAppMessagingFeatureModuleConfig = InAppMessagingFeatureConfig.builder() .setUrlHandler(/* your UrlHandler */) .build() }) { initStatus -> Log.i("SFMC", "SFMC SDK initialization status: $initStatus") } ``` 3. Update iOS native initialization using module-based configuration. ``` // The SFMCSDK module is included in the dependency packages for the SDK. Don't install it // separately or list it in your podfile. import SFMCSDK import PushFeatureSDK import InAppMessagingFeatureSDK import MarketingCloudSDK var configBuilder = ConfigBuilder() if let appEndpoint = URL(string: appEndpointURL) { let engagementConfig = MarketingCloudSdkConfigBuilder(appId: appID) .setAccessToken(accessToken) .setMarketingCloudServerUrl(appEndpoint) .setMid(mid) .setInboxEnabled(true) .setLocationEnabled(true) .setAnalyticsEnabled(true) .build() configBuilder = configBuilder.setEngagement(config: engagementConfig) } let pushConfig = PushFeatureConfigBuilder() .setApplicationControlsBadging(true) .build() configBuilder = configBuilder.setPushFeature(config: pushConfig) let iamConfig = InAppMessagingFeatureConfigBuilder().build() configBuilder = configBuilder.setInAppMessagingFeature(config: iamConfig) SFMCSdk.initializeSdk(configBuilder.build()) { status in // inspect [ModuleInitStatus] per module } ``` 4. Verify mandatory platform configuration requirements. - React Native New Architecture is enabled. - Android build minimums match the required versions. For example, minSdk and compileSdk. - Android 13+ push permission (`POST_NOTIFICATIONS`) is requested for push flows. - iOS deployment target and Xcode minimums match the unified plugin requirements. - Keep all existing notification, URL-handling, and delegate forwarding logic when porting to module-based initialization. For more information, see [Prerequisites](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/migrate-to-hybrid-react-native-plugin.md#prerequisites). 5. Find native initialization files and verify your final setup. ``` rg "SFMCSdk|MarketingCloudConfig|ConfigBuilder" android ios ``` ## See Also [Migration Checklist](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/migration-checklist.md) # MissingFieldException ## Package `com.salesforce.marketingcloud.pushmodels.exceptions` ## Module Push Models Module v1.0.2 ## Description Thrown when a required field is missing from push notification JSON. ## Inheritance Hierarchy ``` kotlin.Any └── com.salesforce.marketingcloud.pushmodels.exceptions.PushException └── com.salesforce.marketingcloud.pushmodels.exceptions.MissingFieldException ``` ## Class Declaration ```kotlin class MissingFieldException(fieldName: String) : PushException ``` ## Platform - **Target:** androidJvm - **SDK Version:** 11.0.0 ## Constructors ### MissingFieldException ```kotlin constructor(fieldName: String) ``` Creates a new MissingFieldException for a required field that was not found in the push notification data. **Parameters:** - `fieldName`: String - The name of the missing required field ## Usage This exception is part of the Salesforce Marketing Cloud Unified SDK and is used specifically for handling errors when parsing push notification data that lacks required fields. It extends `PushException` to provide specific error handling for missing field scenarios in push notification processing. ## Source https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushmodelsmodule/com.salesforce.marketingcloud.pushmodels.exceptions/-missing-field-exception/index.html # Mobile App Messaging SDK ## Packages - [com.salesforce.marketingcloud.mobileappmessaging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-mobileappmessaging/mobileappmessaging_index.md) - [com.salesforce.marketingcloud.mobileappmessaging.analytics](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-mobileappmessaging-analytics/mobileappmessaging-analytics_index.md) - [com.salesforce.marketingcloud.mobileappmessaging.registration](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-mobileappmessaging-registration/mobileappmessaging-registration_index.md) # MobileAppMessaging ## Overview The main entry point for the MobileAppMessaging module in the Salesforce Marketing Cloud Unified SDK. This class implements a singleton pattern with asynchronous initialization and component management. **Package:** `com.salesforce.marketingcloud.mobileappmessaging` **Inheritance:** `MobileAppMessaging : ModuleInterface` --- ## Nested Types ### Companion ```kotlin object Companion ``` Companion object for the MobileAppMessaging class. ### InitializationListener ```kotlin fun interface InitializationListener ``` Functional interface for receiving initialization completion callbacks. ### WhenReadyHandler ```kotlin abstract class WhenReadyHandler( looper: Looper?, val listener: MobileAppMessaging.WhenReadyListener ) ``` Handler class for processing asynchronous SDK requests. **Parameters:** - `looper` - Optional Looper for handler operations - `listener` - The WhenReadyListener callback ### WhenReadyListener ```kotlin fun interface WhenReadyListener ``` Functional interface callback for when the MobileAppMessaging module is ready for use. --- ## Properties ### state ```kotlin open override val state: JSONObject ``` Provides the current state of the MobileAppMessaging SDK as a JSON object. **Returns:** JSONObject containing: - Module information - Readiness status - Initialization configuration - Component states - Storage manager status - Error object if state creation fails --- ## Methods ### getAnalyticsManager ```kotlin fun getAnalyticsManager(): AnalyticsManager ``` Retrieves the analytics component for managing analytics state. **Returns:** `AnalyticsManager` instance ### getRegistrationManager ```kotlin fun getRegistrationManager(): RegistrationManager ``` Retrieves the registration component for managing device registration. **Returns:** `RegistrationManager` instance ### getVersionName ```kotlin fun getVersionName(): String ``` Gets the version name of the module. **Returns:** String representing the module version ## Related Classes - [AnalyticsManager](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/mobileappmessaging/com.salesforce.marketingcloud.mobileappmessaging.analytics/-analytics-manager/index.html) - [RegistrationManager](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/mobileappmessaging/com.salesforce.marketingcloud.mobileappmessaging.registration/-registration-manager/index.html) # MobileAppMessaging `Class` This class is a Swift Interface for SFMobileAppMessaging ## Declaration ```swift @objc(SFMobileAppMessaging) public final class MobileAppMessaging : NSObject, SFMCModule, Publisher @objc public static func requestSdk(_ callback: @escaping (_ mamCore: MobileAppMessagingApi?) -> Void) public func setRegistrationCallback(_ registrationCallback: @escaping (Dictionary) -> Void) public func unsetRegistrationCallback() public func deviceIdentifier() -> String? public func setAnalyticsEnabled(_ enabled: Bool) public func isAnalyticsEnabled() -> Bool ``` ## Request SDK Method ### `requestSdk(_:)` Requests the MobileAppMessaging Module when it’s operational and safe to use. The provided callback will be invoked with the MobileAppMessaging Module when it’s ready. All MobileAppMessaging module-related API calls should be made within this function. ```swift @objc public static func requestSdk(_ callback: @escaping (_ mamCore: MobileAppMessagingApi?) -> Void) ``` --- ## Registration Methods ### `setRegistrationCallback(_:)` Register a callback that will be notified when Registration related events happen @param registrationCallback closure to be provided when registration event occurs ```swift public func setRegistrationCallback(_ registrationCallback: @escaping (Dictionary) -> Void) ``` --- ### `unsetRegistrationCallback()` Removes the registration callback ```swift public func unsetRegistrationCallback() ``` --- ### `deviceIdentifier()` Returns the unique identifier associated with the device. ```swift public func deviceIdentifier() -> String? ``` **Returns:** A `String` representing the device identifier, or `nil` if unavailable. --- ## Feature Toggle Methods ### `setAnalyticsEnabled(_:)` Developer override to set the state of analytics enablement. If set false, the SDK will stop tracking analytics and also purges all the analytics stored locally. This value takes precedence over the config setting which is passed during the SDK initialization. ```swift public func setAnalyticsEnabled(_ enabled: Bool) ``` --- ### `isAnalyticsEnabled()` The current state of the Analytics enablement override ```swift public func isAnalyticsEnabled() -> Bool ``` **Returns:** A BOOL value of the Analytics enablement override considering config setting . --- # MobileAppMessagingConfig **Package:** `com.salesforce.marketingcloud.mobileappmessaging` **Inheritance:** `MobileAppMessagingConfig` extends `MamModuleConfig` ## Description A data class that provides configuration for the MobileAppMessaging module in the Salesforce Marketing Cloud Unified SDK. ## Class Declaration ```kotlin data class MobileAppMessagingConfig : MamModuleConfig ``` ## Properties | Property | Type | Description | | --------------------- | --------- | ------------------------------------------------ | | `accessToken` | `String` | Access token for authentication | | `analyticsEnabled` | `Boolean` | Flag indicating whether analytics are enabled | | `endpointUrl` | `String` | The endpoint URL for the messaging service | | `moduleApplicationId` | `String` | Module application identifier (overrides parent) | | `tenantId` | `String` | Tenant identifier | ## Nested Types ### Builder ```kotlin class Builder ``` A builder class for constructing `MobileAppMessagingConfig` instances. ### Companion ```kotlin object Companion ``` Companion object for the configuration class. # MobileAppMessagingConfigBuilder `Class` MobileAppMessagingConfigBuilder class ## Declaration ```swift @objc(SFMobileAppMessagingConfigBuilder) public class MobileAppMessagingConfigBuilder : NSObject @objc public init(appId: String) @discardableResult @objc public func build() -> MobileAppMessagingConfig @discardableResult @objc public func setAnalyticsEnabled(_ enabled: Bool) -> MobileAppMessagingConfigBuilder @discardableResult @objc public func setTenantId(_ tenantID: String) -> MobileAppMessagingConfigBuilder @discardableResult @objc public func setAccessToken(_ accessToken: String) -> MobileAppMessagingConfigBuilder @discardableResult @objc public func setMAMUrl(_ baseURL: URL) -> MobileAppMessagingConfigBuilder ``` ## Initialization ### `init(appId:)` Initialize MobileAppMessagingConfigBuilder with appId. ```swift @objc public init(appId: String) ``` --- ## Build Method ### `build()` Creates a MobileAppMessaging config containing the current builder configuration settings. This can be passed to the ConfigBuilder method(s) ```swift @discardableResult @objc public func build() -> MobileAppMessagingConfig ``` --- ## Configuration Methods ### `setAnalyticsEnabled(_:)` Set preferred configuration to enable or disable analytics for the module. ```swift @discardableResult @objc public func setAnalyticsEnabled(_ enabled: Bool) -> MobileAppMessagingConfigBuilder ``` **Returns:** MobileAppMessagingConfigBuilder instancetype value --- ### `setTenantId(_:)` Set Tenant ID. ```swift @discardableResult @objc public func setTenantId(_ tenantID: String) -> MobileAppMessagingConfigBuilder ``` **Returns:** MobileAppMessagingConfigBuilder instancetype value --- ### `setAccessToken(_:)` Sets Access Token. ```swift @discardableResult @objc public func setAccessToken(_ accessToken: String) -> MobileAppMessagingConfigBuilder ``` **Returns:** MobileAppMessagingConfigBuilder instancetype value --- ### `setMAMUrl(_:)` Set the tenant specific endpoint url for your application. ```swift @discardableResult @objc public func setMAMUrl(_ baseURL: URL) -> MobileAppMessagingConfigBuilder ``` **Returns:** MobileAppMessagingConfigBuilder instancetype value --- # MobileAppMessagingInitializationStatus **Package:** `com.salesforce.marketingcloud.mobileappmessaging` **SDK Version:** 11.0.0 ## Overview The `MobileAppMessagingInitializationStatus` class provides detailed information about the initialization state of the MobileAppMessaging module. It reports the overall status, any errors encountered, and lists successfully initialized components. ## Class Declaration ```kotlin class MobileAppMessagingInitializationStatus ``` ## Nested Types ### Status ```kotlin enum Status : Enum ``` An enumeration representing the overall initialization outcome for the module. ## Properties ### initializedComponents ```kotlin val initializedComponents: List ``` A list containing the names of all components that were successfully initialized. ### isUsable ```kotlin val isUsable: Boolean ``` Indicates whether the module can be used despite any initialization errors that may have occurred. ### status ```kotlin val status: MobileAppMessagingInitializationStatus.Status ``` The current initialization status of the module. ### storageError ```kotlin val storageError: Boolean ``` Returns `true` if storage initialization failed during the module setup process. ### unrecoverableException ```kotlin val unrecoverableException: Throwable? ``` Contains an unrecoverable exception that occurred during initialization, or `null` if no such exception was encountered. ## Usage This class is used to inspect the initialization state after attempting to initialize the MobileAppMessaging module, allowing developers to determine if the module is ready for use and diagnose any initialization issues. # ModuleConfig `Protocol` SFMCSdk Module Configuration protocol that all registered modules adopt as configuration. ## Declaration ```swift @objc(SFMCSdkModuleConfig) public protocol ModuleConfig var name: ModuleName { get } var appId: String { get } var trackScreens: Bool { get } ``` ## Cases ### `name` Module name ```swift var name: ModuleName { get } ``` --- ### `appId` ```swift var appId: String { get } ``` --- ### `trackScreens` Enable or disbale screen tracking ```swift var trackScreens: Bool { get } ``` --- # ModuleInitStatus `Class` Represents the initialization result for a specific SFMC SDK module. Contains the module identifier ( `moduleName` ) and its initialization outcome ( `initStatus` ). Used in SDK initialization completion handlers to report per-module status. The SDK creates instances internally. Instances are immutable. ## Declaration ```swift @objc(SFMCModuleInitStatus) public final class ModuleInitStatus : NSObject @objc public let moduleName: ModuleName @objc public let initStatus: OperationResult ``` ## Cases ### `moduleName` The module this status refers to, such as `.engagement` or `.cdp` . ```swift @objc public let moduleName: ModuleName ``` --- ### `initStatus` The result of the module’s initialization. Possible values: `.success` , `.error` , `.timeout` , and `.cancelled` . ```swift @objc public let initStatus: OperationResult ``` --- # ModuleName `Enumeration` ## Declaration ```swift @objc(SFMCSdkModuleName) public enum ModuleName : Int, CaseIterable case cdp case engagement case personalization case pushFeature case mobileAppMessaging case inappMessagingFeature ``` ## Cases ### `cdp` ```swift case cdp ``` --- ### `engagement` ```swift case engagement ``` --- ### `personalization` ```swift case personalization ``` --- ### `pushFeature` ```swift case pushFeature ``` --- ### `mobileAppMessaging` ```swift case mobileAppMessaging ``` --- ### `inappMessagingFeature` ```swift case inappMessagingFeature ``` --- # Notification Segmentation Deliver location messages to a subset of your audience by using the Android SDK. For example, when a mobile device enters a geofence or is close to a Bluetooth beacon, the SDK can prompt a callback to your mobile app. The app then assesses whether to display a message. For example, you can use segmentation in these use cases: - Show the message if the user’s preferred store location is within the geofence region. - Show the message if the user has items in the app shopping cart and if the message has an `"abandonedCart":"true"` custom key. - Show the message only when the store is open based on the app’s store location list and the region and local time. - Don’t show messages if the user isn’t logged in to the app. - Show specific messages based on the user’s customer profile. For example, customers who are coffee lovers get messages about coffee, but customers who prefer pastries receive a message to "buy coffee” when they’re in the shop. Provide an implementation of [ShouldShowNotificationListener](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.notifications/-notification-manager/-should-show-notification-listener/index.html) to the [NotificationManager](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.notifications/-notification-manager/index.html). When you implement `shouldShowNotification`, you can access all information about the triggering message, including region data for geofence and beacon triggers. This example shows how to target only Gold loyalty-tier customers for delivery of a message. The marketer sets the custom key `loyaltyLevel` to `gold` while creating the location message. ::::::tabset{tabs='["SDK v8+", "SDK v7"]'} :::::tab ```java SFMCSdk.requestSdk { sdk -> sdk.mp { it.notificationManager.setShouldShowNotificationListener { message -> val messageLoyaltyLevel = message.customKeys["loyaltyLevel"] val customerLoyaltyLevel = it.registrationManager.attributes["loyaltyLevel"] messageLoyaltyLevel == "gold" && customerLoyaltyLevel == "gold" } } } ``` ::::: :::::tab ```java MarketingCloudSdk.requestSdk { sdk -> sdk.notificationManager.setShouldShowNotificationListener { message -> val messageLoyaltyLevel = message.customKeys()["loyaltyLevel"] val customerLoyaltyLevel = sdk.registrationManager.attributes["loyaltyLevel"] messageLoyaltyLevel == "gold" && customerLoyaltyLevel == "gold" } } ``` ::::: :::::: # NotificationCustomizationOptions **Package:** `com.salesforce.marketingcloud.notifications` **SDK Version:** 11.0.0 ## Overview ```kotlin open class NotificationCustomizationOptions ``` This class manages notification customization options for the Salesforce Marketing Cloud SDK. It provides two approaches for customizing notifications: **Option 1 (Guided Approach):** - Minimum requirement: resource ID for notification's small icon - Optional: `NotificationLaunchIntentProvider` for custom click destinations - Optional: `NotificationChannelIdProvider` for per-message channel assignment **Option 2 (Full Control):** - Provide a `NotificationBuilder` implementation - Full responsibility for notification setup including: - Creating the `NotificationCompat.Builder` - Assigning notification channels - Redirecting launch intents via `redirectIntentForAnalytics()` for analytics The SDK handles notification display in both options. ## Properties ### notificationBuilder ```kotlin @get:Nullable val notificationBuilder: NotificationManager.NotificationBuilder ``` Gets the custom notification builder if one was provided. ## Methods ### create #### Variant 1: Builder Only ```kotlin @NonNull open fun create( @NonNull notificationBuilder: NotificationManager.NotificationBuilder ): NotificationCustomizationOptions ``` Creates options with only a `NotificationBuilder`. **Parameters:** - `notificationBuilder` - Custom builder for complete notification control **Returns:** `NotificationCustomizationOptions` instance --- #### Variant 2: Small Icon Only ```kotlin @NonNull open fun create( @DrawableRes smallIconResId: Int ): NotificationCustomizationOptions ``` Creates options with just the small icon resource ID. **Parameters:** - `smallIconResId` - Drawable resource ID for the notification's small icon **Returns:** `NotificationCustomizationOptions` instance --- #### Variant 3: Full Guided Approach ```kotlin @NonNull open fun create( @DrawableRes smallIconResId: Int, @Nullable launchIntentProvider: NotificationManager.NotificationLaunchIntentProvider, @Nullable channelIdProvider: NotificationManager.NotificationChannelIdProvider ): NotificationCustomizationOptions ``` Creates options with icon and optional providers. **Parameters:** - `smallIconResId` - Drawable resource ID for the notification's small icon - `launchIntentProvider` - Optional provider for custom launch intents - `channelIdProvider` - Optional provider for notification channel IDs **Returns:** `NotificationCustomizationOptions` instance --- ### toString ```kotlin @NonNull open fun toString(): String ``` Returns string representation of the options. ## See Also - `NotificationManager.createDefaultNotificationChannel()` --- _Target: androidJvm_ # NotificationCustomizationOptions ## Package `com.salesforce.marketingcloud.pushfeature.notifications` ## Description This class manages notification customization settings for the SDK. It offers two approaches for customizing push notifications: **Option 1 - Guided Approach**: Provide a small icon resource ID at minimum. Optionally add a `NotificationLaunchIntentProvider` for click handling or a `NotificationChannelIdProvider` for per-message channel assignment. **Option 2 - Full Control**: Supply a `NotificationBuilder` to manage the complete notification setup, including: - Creating the `NotificationCompat.Builder` - Setting the notification channel - Routing intents through SDK analytics via `NotificationManager.redirectIntentForAnalytics` The SDK handles notification display in both scenarios. ## Class Declaration ```kotlin class NotificationCustomizationOptions ``` ## Properties ### channelIdProvider ```kotlin val channelIdProvider: NotificationManager.NotificationChannelIdProvider? ``` Provider for determining notification channel IDs on a per-message basis. ### launchIntentProvider ```kotlin val launchIntentProvider: NotificationManager.NotificationLaunchIntentProvider? ``` Provider for customizing the intent when a notification is clicked. ### notificationBuilder ```kotlin val notificationBuilder: NotificationManager.NotificationBuilder? ``` Custom builder for complete control over notification creation. ### smallIconResId ```kotlin val smallIconResId: Int ``` Resource ID for the notification's small icon. ## Nested Types ### Companion ```kotlin object Companion ``` Companion object for the NotificationCustomizationOptions class. ## See Also - `NotificationManager.Companion.getDefaultNotificationBuilder` - `NotificationManager.Companion.createDefaultNotificationChannel` # NotificationManager **Package:** `com.salesforce.marketingcloud.notifications` **SDK Version:** 11.0.0 ## Description An abstract class for managing push notifications in the Salesforce Marketing Cloud Android SDK. ## Constructor ```kotlin constructor() ``` ## Properties ### DEFAULT_CHANNEL_ID ```kotlin val DEFAULT_CHANNEL_ID: String = "com.salesforce.marketingcloud.DEFAULT_CHANNEL" ``` The SDK's default notification channel identifier. ### DEFAULT_FOREGROUND_CHANNEL_ID ```kotlin val DEFAULT_FOREGROUND_CHANNEL_ID: String = "com.salesforce.marketingcloud.DEFAULT_FOREGROUND_CHANNEL" ``` The SDK's default foreground notification channel identifier. ## Methods ### areNotificationsEnabled ```kotlin abstract fun areNotificationsEnabled(): Boolean ``` Returns the current notification enablement status. **Returns:** `Boolean` - true if notifications are enabled, false otherwise --- ### enableNotifications ```kotlin abstract fun enableNotifications() ``` Activates SDK notifications. --- ### disableNotifications ```kotlin abstract fun disableNotifications() ``` Deactivates SDK notifications. --- ### createDefaultNotificationChannel ```kotlin open fun createDefaultNotificationChannel(context: Context): String ``` Creates the SDK's default channel if it doesn't exist. **Parameters:** - `context: Context` - The application context **Returns:** `String` - The channel ID ```kotlin open fun createDefaultNotificationChannel(context: Context, forceRecreate: Boolean): String ``` Creates the SDK's default channel, optionally forcing recreation. **Parameters:** - `context: Context` - The application context - `forceRecreate: Boolean` - If true, recreates the channel even if it exists **Returns:** `String` - The channel ID --- ### createForegroundNotificationChannel ```kotlin open fun createForegroundNotificationChannel(context: Context): String ``` Creates the foreground channel if it doesn't exist. **Parameters:** - `context: Context` - The application context **Returns:** `String` - The foreground channel ID --- ### cancelNotificationMessage ```kotlin open fun cancelNotificationMessage(context: Context, message: NotificationMessage) ``` Dismisses the notification for the specified message. **Parameters:** - `context: Context` - The application context - `message: NotificationMessage` - The notification message to cancel --- ### extractMessage ```kotlin open fun extractMessage(intent: Intent): NotificationMessage? ``` Retrieves the NotificationMessage from an Intent. **Parameters:** - `intent: Intent` - The intent containing the notification message **Returns:** `NotificationMessage?` - The extracted notification message, or null if not present --- ### getDefaultNotificationBuilder ```kotlin open fun getDefaultNotificationBuilder( context: Context, message: NotificationMessage, channelId: String, smallIconResId: Int ): NotificationCompat.Builder ``` Constructs a Builder with SDK default settings. **Parameters:** - `context: Context` - The application context - `message: NotificationMessage` - The notification message to display - `channelId: String` - The notification channel ID - `smallIconResId: Int` - Resource ID for the small icon **Returns:** `NotificationCompat.Builder` - A configured notification builder --- ### redirectIntentForAnalytics ```kotlin open fun redirectIntentForAnalytics( context: Context, openIntent: PendingIntent, message: NotificationMessage, autoCancel: Boolean ): PendingIntent ``` Creates a PendingIntent that routes through analytics tracking. **Parameters:** - `context: Context` - The application context - `openIntent: PendingIntent` - The original intent to wrap - `message: NotificationMessage` - The notification message - `autoCancel: Boolean` - Whether to auto-cancel the notification **Returns:** `PendingIntent` - A pending intent with analytics tracking ```kotlin open fun redirectIntentForAnalytics( context: Context, openIntent: PendingIntent, message: NotificationMessage, autoCancel: Boolean, bundle: Bundle? ): PendingIntent ``` Extended version accepting an optional Bundle parameter. **Parameters:** - `context: Context` - The application context - `openIntent: PendingIntent` - The original intent to wrap - `message: NotificationMessage` - The notification message - `autoCancel: Boolean` - Whether to auto-cancel the notification - `bundle: Bundle?` - Optional bundle with additional data **Returns:** `PendingIntent` - A pending intent with analytics tracking --- ### registerNotificationMessageDisplayedListener ```kotlin abstract fun registerNotificationMessageDisplayedListener( listener: NotificationMessageDisplayedListener ) ``` Adds a display listener to receive notification display events. **Parameters:** - `listener: NotificationMessageDisplayedListener` - The listener to register --- ### unregisterNotificationMessageDisplayedListener ```kotlin abstract fun unregisterNotificationMessageDisplayedListener( listener: NotificationMessageDisplayedListener ) ``` Removes a display listener. **Parameters:** - `listener: NotificationMessageDisplayedListener` - The listener to unregister --- ### setShouldShowNotificationListener ```kotlin abstract fun setShouldShowNotificationListener( listener: ShouldShowNotificationListener? ) ``` Sets a listener to control notification display decisions. **Parameters:** - `listener: ShouldShowNotificationListener?` - The listener to set, or null to remove ## Nested Interfaces ### NotificationBuilder Customizes notification creation via NotificationCustomizationOptions. ### NotificationChannelIdProvider Supplies channel IDs via NotificationCustomizationOptions. ### NotificationLaunchIntentProvider Provides launch intents via NotificationCustomizationOptions. ### NotificationMessageDisplayedListener Receives notification display events. ### ShouldShowNotificationListener Controls notification display logic. # NotificationManager ## Package `com.salesforce.marketingcloud.pushfeature.notifications` ## Overview An abstract class for managing push notifications in the Salesforce Marketing Cloud SDK. **Module:** Push Feature Module v2.0.0 **SDK:** Salesforce Marketing Cloud Unified SDK 11.0.0 **Platform:** androidJvm --- ## Constructor ### NotificationManager() ```kotlin NotificationManager() ``` Default constructor with no parameters. --- ## Methods ### areNotificationsEnabled ```kotlin fun areNotificationsEnabled(): Boolean ``` Returns whether notifications are currently enabled. **Returns:** `Boolean` - true if notifications are enabled, false otherwise --- ### enableNotifications ```kotlin fun enableNotifications() ``` Enables push notifications. --- ### disableNotifications ```kotlin fun disableNotifications() ``` Disables push notifications. --- ### showNotificationMessage ```kotlin fun showNotificationMessage(message: NotificationMessage) ``` Displays a notification message. **Parameters:** - `message`: `NotificationMessage` - The NotificationMessage to display --- ### setShouldShowNotificationListener ```kotlin fun setShouldShowNotificationListener(listener: NotificationManager.ShouldShowNotificationListener?) ``` Sets a listener to determine if a notification should be displayed. **Parameters:** - `listener`: `NotificationManager.ShouldShowNotificationListener?` - The ShouldShowNotificationListener instance (nullable) --- ### registerNotificationMessageDisplayedListener ```kotlin fun registerNotificationMessageDisplayedListener(listener: NotificationManager.NotificationMessageDisplayedListener) ``` Registers a listener for notification display events. **Parameters:** - `listener`: `NotificationManager.NotificationMessageDisplayedListener` - The NotificationMessageDisplayedListener to register --- ### unregisterNotificationMessageDisplayedListener ```kotlin fun unregisterNotificationMessageDisplayedListener(listener: NotificationManager.NotificationMessageDisplayedListener) ``` Removes a previously registered listener. **Parameters:** - `listener`: `NotificationManager.NotificationMessageDisplayedListener` - The NotificationMessageDisplayedListener to unregister --- ## Nested Types ### Companion ```kotlin object Companion ``` Static companion object. --- ### NotificationBuilder ```kotlin fun interface NotificationBuilder ``` Provides custom notification building. Used in `NotificationCustomizationOptions` during SDK initialization via `PushFeatureConfig.notificationCustomizationOptions`. --- ### NotificationChannelIdProvider ```kotlin fun interface NotificationChannelIdProvider ``` Provides notification channel IDs. Used in `NotificationCustomizationOptions`. --- ### NotificationLaunchIntentProvider ```kotlin fun interface NotificationLaunchIntentProvider ``` Provides intents for notification launches. --- ### NotificationMessageDisplayedListener ```kotlin fun interface NotificationMessageDisplayedListener ``` Listens for notification display events. --- ### ShouldShowNotificationListener ```kotlin fun interface ShouldShowNotificationListener ``` Queries whether a notification should be shown. # NotificationMessage **Package:** `com.salesforce.marketingcloud.notifications` **Inheritance:** `Parcelable` A data class representing a notification message in the Salesforce Marketing Cloud SDK. ## Declaration ```kotlin data class NotificationMessage : Parcelable ``` --- ## Nested Types ### Sound ```kotlin enum Sound : Enum ``` Enumeration for notification sound types. ### Trigger ```kotlin enum Trigger : Enum ``` Enumeration for notification trigger types. ### Type ```kotlin enum Type : Enum ``` Enumeration for notification message types. --- ## Properties ### alert ```kotlin @JvmField val alert: String ``` The alert message text. ### custom ```kotlin @JvmField val custom: String? ``` Custom data associated with the notification (nullable). ### customKeys ```kotlin @JvmField val customKeys: Map ``` A map of custom key-value pairs. ### id ```kotlin @JvmField val id: String ``` The unique identifier for the notification message. ### mediaAltText ```kotlin @JvmField val mediaAltText: String? ``` Alternative text for media content (nullable). ### mediaUrl ```kotlin @JvmField val mediaUrl: String? ``` URL for media content (nullable). ### payload ```kotlin @JvmField val payload: Map? ``` Additional payload data as a map (nullable). ### region ```kotlin @JvmField val region: Region? ``` The geographic region associated with the notification (nullable). ### requestId ```kotlin @JvmField val requestId: String? ``` The request identifier (nullable). ### richFeatures ```kotlin @JvmField val richFeatures: RichFeatures? ``` Rich notification features (nullable). ### sound ```kotlin @JvmField val sound: NotificationMessage.Sound ``` The sound setting for the notification. ### soundName ```kotlin @JvmField val soundName: String? ``` The name of the custom sound file (nullable). ### subtitle ```kotlin @JvmField val subtitle: String? ``` The notification subtitle (nullable). ### title ```kotlin @JvmField val title: String? ``` The notification title (nullable). ### trigger ```kotlin @JvmField val trigger: NotificationMessage.Trigger ``` The trigger type for the notification. ### type ```kotlin @JvmField val type: NotificationMessage.Type ``` The type of notification message. ### url ```kotlin @JvmField val url: String? ``` URL associated with the notification (nullable). --- ## Functions ### toJson ```kotlin fun toJson(): JSONObject ``` Converts the notification message to a JSON object. **Returns:** A `JSONObject` representation of the notification message. # NotificationMessage **Package:** `com.salesforce.marketingcloud.pushmodels` **Module:** Push Models Module v1.0.2 A data class representing a notification message in the Salesforce Marketing Cloud Unified SDK. ## Declaration ```kotlin data class NotificationMessage : Parcelable ``` ## Nested Types ### Sound ```kotlin enum Sound : Enum ``` Enumeration representing sound options for notifications. ### Trigger ```kotlin enum Trigger : Enum ``` Enumeration representing trigger types for notifications. ### Type ```kotlin enum Type : Enum ``` Enumeration representing notification message types. ## Properties ### alert ```kotlin @JvmField val alert: String ``` The alert text for the notification. ### context ```kotlin @JvmField val context: String? ``` Optional context information for the notification. ### custom ```kotlin @JvmField val custom: String? ``` Optional custom data string. ### customKeys ```kotlin @JvmField val customKeys: Map ``` Map of custom key-value pairs. ### id ```kotlin @JvmField val id: String ``` Unique identifier for the notification message. ### mediaAltText ```kotlin @JvmField val mediaAltText: String? ``` Optional alternative text for media content. ### mediaUrl ```kotlin @JvmField val mediaUrl: String? ``` Optional URL for media content. ### payload ```kotlin @JvmField val payload: Map? ``` Optional map containing payload data. ### propertyBag ```kotlin @JvmField val propertyBag: String? ``` Optional property bag string. ### region ```kotlin @JvmField val region: Region? ``` Optional region information. ### requestId ```kotlin @JvmField val requestId: String? ``` Optional request identifier. ### richFeatures ```kotlin @JvmField val richFeatures: RichFeatures? ``` Optional rich notification features. ### sound ```kotlin @JvmField val sound: NotificationMessage.Sound ``` Sound configuration for the notification. ### soundName ```kotlin @JvmField val soundName: String? ``` Optional custom sound name. ### subtitle ```kotlin @JvmField val subtitle: String? ``` Optional subtitle text. ### title ```kotlin @JvmField val title: String? ``` Optional title text. ### trigger ```kotlin @JvmField val trigger: NotificationMessage.Trigger ``` Trigger type for the notification. ### type ```kotlin @JvmField val type: NotificationMessage.Type ``` Type of the notification message. ### url ```kotlin @JvmField val url: String? ``` Optional URL associated with the notification. # OperationResult `Enumeration` ## Declaration ```swift @objc(SFMCSdkOperationResult) public enum OperationResult : Int public typealias RawValue = String case cancelled case error case success case timeout public var rawValue: RawValue { get } public init?(rawValue: RawValue) ``` ## Cases ### `RawValue` ```swift public typealias RawValue = String ``` --- ### `cancelled` ```swift case cancelled ``` --- ### `error` ```swift case error ``` --- ### `success` ```swift case success ``` --- ### `timeout` ```swift case timeout ``` --- ### `rawValue` ```swift public var rawValue: RawValue { get } ``` --- ### `init(rawValue:)` ```swift public init?(rawValue: RawValue) ``` --- # Order **Package:** `com.salesforce.marketingcloud.sfmcsdk.components.events` **Platform:** androidJvm **SDK Version:** 11.0.0 ## Overview A data class representing an order in the Salesforce Marketing Cloud SDK. This class encapsulates order information including line items, total value, currency, and custom attributes. ## Class Declaration ```kotlin data class Order @JvmOverloads constructor( val id: String, val lineItems: List = listOf(), val totalValue: Double? = null, val currency: String? = null, val attributes: Map = mapOf() ) ``` ## Constructor ### Order ```kotlin @JvmOverloads constructor( id: String, lineItems: List = listOf(), totalValue: Double? = null, currency: String? = null, attributes: Map = mapOf() ) ``` Creates an Order instance with the specified parameters. All parameters except `id` have default values. ## Properties ### id ```kotlin val id: String ``` A unique identifier representing the order. This is a required field. ### lineItems ```kotlin val lineItems: List ``` An list of Line Item Data values. Defaults to an empty list if not provided. ### totalValue ```kotlin val totalValue: Double? ``` The total value of the order. This is an optional nullable property. ### currency ```kotlin val currency: String? ``` The currency of the total value for the order. This is an optional nullable property. ### attributes ```kotlin val attributes: Map ``` A map of user-supplied values. Defaults to an empty map if not provided. This allows for custom key-value pairs to be associated with the order. ## Related Classes - `LineItem` - Represents individual items within the order # OrderEvent **Package:** `com.salesforce.marketingcloud.sfmcsdk.components.events` **SDK Version:** 11.0.0 ## Overview `OrderEvent` is a sealed class that extends `EngagementEvent`. It represents order-related events in the Salesforce Marketing Cloud SDK. ## Class Declaration ```kotlin sealed class OrderEvent : EngagementEvent ``` ## Inheritance - **Superclass:** `EngagementEvent` ## Properties | Property | Type | Description | | -------- | ------- | ------------------------------------------- | | `order` | `Order` | The order object associated with this event | ## Inheritors The following classes inherit from `OrderEvent`: - `PurchaseOrderEvent` - Represents a purchase order event - `PreorderEvent` - Represents a preorder event - `CancelOrderEvent` - Represents an order cancellation event - `ShipOrderEvent` - Represents an order shipping event - `DeliverOrderEvent` - Represents an order delivery event - `ReturnOrderEvent` - Represents an order return event - `ExchangeOrderEvent` - Represents an order exchange event ## Nested Types ### Companion ```kotlin object Companion ``` A companion object for the `OrderEvent` class. ## Related Types - `Order` - The order data type used by the `order` property - `EngagementEvent` - The parent class for all engagement events # PERSONALIZATION `Class` ## Declaration ```swift @objc(SFMCSdkPersonalization) public final class PERSONALIZATION : NSObject, SFMCModuleApi @objc public func getStatus() -> ModuleStatus @objc public func getIdentity() -> ModuleIdentity? ``` ## Cases ### `getStatus()` ```swift @objc public func getStatus() -> ModuleStatus ``` --- ### `getIdentity()` ```swift @objc public func getIdentity() -> ModuleIdentity? ``` --- # PiCart **Package:** `com.salesforce.marketingcloud.analytics` **Platform:** androidJvm ## Description A data class representing a shopping cart for analytics tracking. This class implements `Parcelable` and is used with `AnalyticsManager.trackCartContents` or as the cart value for `PiOrder.cart`. ## Class Declaration ```kotlin data class PiCart( val cartItems: List ) : Parcelable ``` ## Constructors ### PiCart ```kotlin constructor(cartItems: List) ``` Creates a new PiCart instance. **Parameters:** - `cartItems`: List of `PiCartItem` objects representing items in the cart ## Properties ### cartItems ```kotlin @JvmField val cartItems: List ``` The list of items contained in this shopping cart. Each item is represented as a `PiCartItem` object. # PiCartItem **Package:** `com.salesforce.marketingcloud.analytics` **SDK Version:** 11.0.0 ## Overview ```kotlin data class PiCartItem( val item: String, val quantity: Int, val price: Double, val uniqueId: String? ) : Parcelable ``` A data class representing a cart content item, designed to be used as part of `PiCart.cartItems`. ## Constructors ### Primary Constructor ```kotlin constructor( item: String, quantity: Int, price: Double, uniqueId: String? ) ``` Creates a `PiCartItem` with all parameters including an optional unique identifier. **Parameters:** - `item` - The item name or identifier - `quantity` - The quantity of this item - `price` - The price of the item - `uniqueId` - Optional unique identifier for the item ### Secondary Constructor ```kotlin constructor( item: String, quantity: Int, price: Double ) ``` Creates a `PiCartItem` without a unique identifier (uniqueId will be null). **Parameters:** - `item` - The item name or identifier - `quantity` - The quantity of this item - `price` - The price of the item ## Properties ### item ```kotlin @JvmField val item: String ``` The item name or identifier. ### quantity ```kotlin @JvmField val quantity: Int ``` The quantity of this item in the cart. ### price ```kotlin @JvmField val price: Double ``` The price of the item. ### uniqueId ```kotlin @JvmField val uniqueId: String? ``` Optional unique identifier for the cart item. ## Inheritance Implements `android.os.Parcelable` for Android parcelization support. # PiOrder **Package:** `com.salesforce.marketingcloud.analytics` **SDK Version:** 11.0.0 ## Overview `PiOrder` is a data class representing an order object used with the Salesforce Marketing Cloud SDK's analytics tracking functionality. It implements `Parcelable` for Android serialization and is specifically designed for tracking cart conversions through the `AnalyticsManager.trackCartConversion` method. All fields in this class are required and cannot be null. ## Class Declaration ```kotlin data class PiOrder( val cart: PiCart, val orderNumber: String, val shipping: Double, val discount: Double ) : Parcelable ``` ## Inheritance - Implements: `android.os.Parcelable` ## Constructor ```kotlin constructor( cart: PiCart, orderNumber: String, shipping: Double, discount: Double ) ``` ### Parameters | Parameter | Type | Description | | ------------- | -------- | -------------------------------------------- | | `cart` | `PiCart` | The shopping cart associated with this order | | `orderNumber` | `String` | The unique identifier for this order | | `shipping` | `Double` | The shipping cost for this order | | `discount` | `Double` | The discount amount applied to this order | ## Properties ### cart ```kotlin @JvmField val cart: PiCart ``` The shopping cart object containing the items in this order. ### orderNumber ```kotlin @JvmField val orderNumber: String ``` The unique order number identifying this transaction. ### shipping ```kotlin @JvmField val shipping: Double ``` The shipping cost amount for this order. ### discount ```kotlin @JvmField val discount: Double ``` The discount amount applied to this order. ## Usage This class is used in conjunction with `AnalyticsManager.trackCartConversion()` to track e-commerce order conversions in the Salesforce Marketing Cloud platform. # PreorderEvent ## Overview **Package:** `com.salesforce.marketingcloud.sfmcsdk.components.events` **Inheritance Hierarchy:** `Event` → `EngagementEvent` → `OrderEvent` → `PreorderEvent` **Platform:** androidJvm **SDK Version:** SFMC SDK v3.1.0 **API Version:** 11.0.0 ## Description An E-commerce event for when a user places a preorder. This class represents a specific type of order event within the Salesforce Marketing Cloud Unified SDK, designed to track when users place preorders in an e-commerce context. ## Class Declaration ```kotlin class PreorderEvent : OrderEvent ``` ## Properties ### Inherited from OrderEvent #### order ```kotlin val order: Order ``` The order associated with this event. ### Inherited from EngagementEvent #### category ```kotlin open override var category: Event.Category ``` The event category name. Category contains a list of allowed values. #### priority ```kotlin open override val priority: Priority ``` The priority level for this event. ## Methods ### Inherited from EngagementEvent #### attributes() ```kotlin open override fun attributes(): Map ``` Returns the event attributes for this event as a map of string keys to any values. **Returns:** `Map` - The event attributes #### name() ```kotlin open override fun name(): String ``` Returns the name for the event. **Returns:** `String` - The event name **Note:** This value must match the Event Name used when creating the event in the Marketing Cloud UI for any action to result from tracking this event. ## Order Class Reference The `order` property contains an instance of the `Order` class with the following structure: ### Order Constructor ```kotlin @JvmOverloads constructor( id: String, lineItems: List = listOf(), totalValue: Double? = null, currency: String? = null, attributes: Map = mapOf() ) ``` **Parameters:** - `id` (String, required) - A unique identifier representing the order - `lineItems` (List, optional) - A list of Line Item Data values (defaults to empty list) - `totalValue` (Double?, optional) - The total value of the order (nullable, defaults to null) - `currency` (String?, optional) - The currency of the total value for the order (nullable, defaults to null) - `attributes` (Map, optional) - A map of user-supplied values (defaults to empty map) ### Order Properties - `id: String` - A unique identifier representing the order - `lineItems: List` - A list of Line Item Data values - `totalValue: Double?` - The total value of the order - `currency: String?` - The currency of the total value for the order - `attributes: Map` - A map of user-supplied values ## Related Classes ### Other OrderEvent Subclasses - `PurchaseOrderEvent` - For completed purchases - `CancelOrderEvent` - For canceled orders - `ShipOrderEvent` - For shipped orders - `DeliverOrderEvent` - For delivered orders - `ReturnOrderEvent` - For returned orders - `ExchangeOrderEvent` - For exchanged orders ## Notes - `PreorderEvent` is part of a sealed class hierarchy, where `OrderEvent` is a sealed class - All direct subclasses of `OrderEvent` must be defined in the same file or compilation unit - The event name returned by `name()` must match the Event Name configured in the Marketing Cloud UI for proper event tracking # Prerequisites Before you configure your Marketing Cloud environment to send push notifications, set up the push notification services and download the required authentication and configuration files. ## Configure Apple Push Notification Service for iOS If you plan to send push notifications to iOS devices, configure Apple Push Notification service (APNs) and create a `.p8` key. For information about creating a `.p8` key, see _Apple Developer Documentation_: [Create a private key to access a service](https://developer.apple.com/help/account/keys/create-a-private-key/). Store your key in a private and secure location. The key isn’t saved in your Apple Developer account, so you can’t download it again if you lose it. It isn’t necessary to generate separate `.p8` keys for your production and sandbox environments. Apple uses the same key to send notifications to apps, regardless of the environment. ## Configure Google Firebase for Android If you plan to send push notifications to Android devices, configure Google Firebase for your app and download a configuration file. For information about obtaining a configuration file, see _Firebase Documentation_: [Add Firebase to your Android project](https://firebase.google.com/docs/android/setup). # Prevent or Delay Message Display Delay or prevent the display of an in-app message. For example, you can choose to prevent an in-app message from displaying during the loading process, sign-in flow, and other situations. To prevent or delay message display, set the [shouldShowMessage](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/inappmessagingfeaturemodule/com.salesforce.marketingcloud.inappmessagingfeature/-in-app-message-manager/-event-listener/should-show-message.html) method to return `false`. You can capture data of any [in-app message](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/inappmessagingmodelsmodule/com.salesforce.marketingcloud.inappmessaging.models/-in-app-message/index.html) and use it to display the message at a later time. For example, you can present the message after the user successfully signs in by capturing the [ID](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/inappmessagingmodelsmodule/com.salesforce.marketingcloud.inappmessaging.models/-in-app-message/id.html) of the message and showing that message later. ::::::tabset{tabs='["SDK v11", "SDK v10", "SDK v8", "SDK v7"]'} :::::tab Use this code to show a captured message later in version 11 of the SDK for Android. ```java InAppMessagingFeature.requestSdk { inAppMessagingFeatureModule -> inAppMessagingFeatureModule.getInAppMessageManager().showMessage(blockedMessageId) } ``` ::::: :::::tab Use this code to show a captured message later in version 10 of the SDK for Android. ```java MarketingCloudSdk.requestSdk { engagementSdk -> engagementSdk.inAppMessageManager.showMessage(blockedMessageId) } ``` ::::: :::::tab Use this code to show a captured message later in version 8 of the SDK for Android. ```java SFMCSdk.requestSdk { sdk -> sdk.mp { it.inAppMessageManager.showMessage(blockedMessageId) } } ``` ::::: :::::tab Use this code to show a captured message later in version 7 of the SDK for Android. ```java MarketingCloudSdk.requestSdk { sdk-> sdk.inAppMessageManager.showMessage(blockedMessageId) } ``` ::::: :::::: # Prevent or Delay Message Display Delay or prevent the display of an in-app message by using the [shouldShow](/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessageeventdelegate.html) method. For example, you can choose to prevent an in-app message from displaying during the loading process, sign-in flow, and other situations. To prevent or delay message display, set the `shouldShow` method to return `false`. ```swift func shouldShow(inAppMessage message: InAppMessageDetails) -> Bool { // using your app's logic, can this message be shown? if (self.messageCanBeShown) { return true } else { // capture the message id in the event self.showMessageId = message.id } return false } ``` You can capture in-app message data and use it to display the message later. For example, you can present the message after the user successfully signs in. ::::::tabset{tabs='["SDK v11", "SDK v10", "SDK v8.1", "SDK v8.0", "SDK v7"]'} :::::tab Use this code to show a captured message later in version 11 of the SDK for iOS. Access the message ID in the `InAppMessageDetails` object within the delegate. Trigger the display through the `InAppMessagingFeature` module by using these methods: - `message.id` (property of InAppMessageDetails) - `showInAppMessage` ```swift // if you've previously captured the messageId, you can show the In-App Message later // (for instance, you've returned false from shouldShow(inAppMessage message: InAppMessageDetails) because // your UI or application logic couldn't be interrupted) if (self.showMessageId != nil) { InAppMessagingFeature.requestSdk { iam in iam?.showInAppMessage(messageId: self.showMessageId) } } ``` ::::: :::::tab Use this code to show a captured message later in version 10 of the SDK for iOS. Use these methods: - `sfmc_messageIdForMessage` - `sfmc_showInAppMessage` ```swift // If you previously captured the messageId, you can show the In-App Message // later (for example, if you returned false from sfmc_shouldShowInAppMessage() // because your UI or app logic couldn't be interrupted). if (self.showMessageId != nil) { MarketingCloudSdk.requestSdk { mc in mc?.showInAppMessage(messageId: self.showMessageId) } } ``` ::::: :::::tab Use this code to show a captured message later in version 8.1 of the SDK for iOS. ```swift // If you previously captured the messageId, you can show the In-App Message // later (for example, if you returned false from sfmc_shouldShowInAppMessage() // because your UI or app logic couldn't be interrupted). if (self.showMessageId != nil) { SFMCSdk.requestPushSdk { mp in mp.showInAppMessage(messageId: self.showMessageId) } } ``` ::::: :::::tab Use this code to show a captured message later in version 8.0 of the SDK for iOS. ```swift // If you previously captured the messageId, you can show the In-App Message // later (for example, if you returned false from sfmc_shouldShowInAppMessage() // because your UI or app logic couldn't be interrupted). // Make sure the SDK is operational if (self.showMessageId != nil) { SFMCSdk.mp.showInAppMessage(messageId: self.showMessageId) } ``` ::::: :::::tab Use this code to show a captured message later in version 7 of the SDK for iOS. ```swift // if you've previously captured the messageId, you can show the In-App Message later // (for instance, you've returned false from sfmc_shouldShowInAppMessage() because // your UI or application logic couldn't be interrupted) if (self.showMessageId != nil) { MarketingCloudSDK.sharedInstance().sfmc_show(inAppMessage: self.showMessageId) } ``` ::::: :::::: # Privacy Manifest Support for Hybrid Plugins The React Native and Cordova plugins for the Salesforce Engagement SDK require iOS version 11.0 or later. However, the native iOS SDK v8.1.2 that includes support for privacy manifests has a minimum deployment target of 12.0. For your hybrid framework apps to be compliant with [Apple’s third-party SDK privacy requirements](https://developer.apple.com/support/third-party-SDK-requirements/), change the minimum deployment target for your apps to `12.0` and then update the dependencies for your project. ## Update Deployment Target for React Native Plugin Compatibility By default, the React Native Plugin automatically fetches the most recent version of the Salesforce Engagement SDK, as long as the SDK’s minimum deployment target requirement is satisfied. To ensure compatibility with the privacy manifest in SDK version 8.1.2 or later, your application must support a deployment target of iOS 12 or higher. To update your app’s deployment target, follow these steps. 1. Open your iOS project in Xcode. 2. In the Navigation section, select your project and then select your project target. 3. On the General tab, change the value of **Minimum Deployments** to `12.0`. 4. At the command line, in your `ios` folder, run `pod update`. Performing these steps fetches `MarketingCloudSDK 8.1.2` or later versions. These versions contain the privacy manifest. ## Update Deployment Target for Cordova Plugin Compatibility The Cordova Plugin automatically fetches the most recent version of the SDK, as long as the SDK’s minimum deployment target requirement is satisfied. To comply with the privacy manifest in SDK version 8.1.2 or later, your application must support a deployment target of iOS 12 or higher. To update your app’s deployment target, follow these steps. 1. Open the `config.xml` file. 2. Update the `deployment-target` to include a later deployment target, as shown in this example. ```xml ``` 3. At the command line, run these commands to remove and add the iOS platform. ```bash cordova platform remove ios cordova platform add ios ``` # Privacy Manifest Support for Older iOS SDK Versions Apple requires all third-party frameworks to include a privacy manifest. Version 8.1.2 and later of the SDK meet this requirement. These versions of the SDK include a signed framework and a privacy manifest file, and requires a deployment target of iOS 12 or later. If your app uses version 7.6.0–8.1.1 of the MobilePush iOS SDK, you can still include a privacy manifest in your implementation. However, this solution works only if you manually add the SDKs to your app as opposed to using CocoaPods or Swift Package Manager. 1. Download the privacy manifest from [this commit](https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS/commit/151b9f0fd0f1ea1be2ad26c93f60c3c6aa40f9cb#diff-e648e192936b0c57333e3edbb1e6f49e72342088da217b7f2e99aeffc3994774). 2. Expand the `MarketingCloudSDK.xcframework` folder and find folders for two architectures, `ios-arm64_armv7_armv7s` and `ios-arm64_i386_x86_64-simulator`. 3. Within each architecture folder, expand the `MarketingCloudSDK.framework` folder and copy the `PrivacyInfo.xcprivacy` file. 4. In your SDK folder, paste the `PrivacyInfo.xcprivacy` file you copied for each architecture into the corresponding architecture folder. 5. Include the updated framework in your project. **important:** Versions 8.1.0 and 8.1.1 of the SDK for iOS are code-signed. When you modify the signed SDK, Apple validation fails because of a signature mismatch error. To prevent failed validations, delete the `_CodeSignature` folder from the `MarketingCloudSDK.framework` folder, add the SDK to your project, and mark it as **Embed & Sign**. This step ensures that the application owner re-signs the SDK, preventing the signature mismatch error. # Protocols - [IdentityInfo](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/identityinfo.md) - [IdentityModifier](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/identitymodifier.md) - [InAppMessageAnimation](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessageanimation.md) - [InAppMessageBorder](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessageborder.md) - [InAppMessageButton](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagebutton.md) - [InAppMessageCloseButton](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessageclosebutton.md) - [InAppMessageDetails](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagedetails.md) - [InAppMessageEventDelegate](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessageeventdelegate.md) - [InAppMessageMedia](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagemedia.md) - [InAppMessageShadow](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessageshadow.md) - [InAppMessageSpacing](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagespacing.md) - [InAppMessageTertiaryText](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagetertiarytext.md) - [InAppMessageText](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessagetext.md) - [LocationDelegate](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/locationdelegate.md) - [ModuleConfig](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/moduleconfig.md) - [URLHandlingDelegate](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/urlhandlingdelegate.md) # ProximityMessageResponse A class representing a response containing proximity-based messaging data in the Salesforce Marketing Cloud SDK. **Package:** `com.salesforce.marketingcloud.messages.proximity` **Inheritance:** Extends `MessageResponse` **Target Platform:** androidJvm --- ## Overview `ProximityMessageResponse` is a data class that handles proximity messaging responses. It contains information about beacon regions and refresh parameters for location-based messaging. --- ## Properties ### beacons ```kotlin @JvmField val beacons: List ``` A list of Region objects representing beacon locations for proximity messaging. ### refreshCenter ```kotlin open override val refreshCenter: LatLon ``` The geographic center point for refresh operations, specified as latitude and longitude coordinates. ### refreshRadius ```kotlin open override val refreshRadius: Int ``` The radius (in meters) from the refresh center within which refresh operations should occur. --- ## Related Types - **Parent Class:** `MessageResponse` - Base class for message responses - **Related Types:** - `Region` - Represents a geographic region for beacon monitoring - `LatLon` - Represents latitude/longitude coordinates # ProximityNotificationCustomizationOptions ## Overview `ProximityNotificationCustomizationOptions` is a class in the Salesforce Marketing Cloud Unified SDK that provides customization options for proximity-based notifications. **Package:** `com.salesforce.marketingcloud.proximity` **Platform:** androidJvm **SDK Version:** 11.0.0 ## Class Declaration ```kotlin class ProximityNotificationCustomizationOptions ``` ## Properties ### channelIdProvider ```kotlin val channelIdProvider: NotificationManager.NotificationChannelIdProvider? ``` Provider for notification channel IDs used in proximity notifications. **Type:** `NotificationManager.NotificationChannelIdProvider?` (nullable) ### smallIconResId ```kotlin val smallIconResId: Int ``` Resource ID for the small icon displayed in proximity notifications. **Type:** `Int` ## Nested Types ### Companion ```kotlin object Companion ``` Companion object for the `ProximityNotificationCustomizationOptions` class. # ProximityNotificationCustomizer **Package:** `com.salesforce.marketingcloud.notifications` **Available since:** SDK version 11.0.0 (also available in 10.0.0) ## Overview An open class that extends `NotificationCustomizer` for handling proximity-based notifications in the Salesforce Marketing Cloud SDK. ## Class Declaration ```kotlin open class ProximityNotificationCustomizer : NotificationCustomizer ``` ## Constructors ### ProximityNotificationCustomizer ```kotlin constructor( @NonNull smallIconResId: Int, @Nullable channelIdProvider: NotificationManager.NotificationChannelIdProvider ) ``` Creates a new instance of ProximityNotificationCustomizer. **Parameters:** - `smallIconResId` - `Int` (@NonNull) - Resource ID for the notification's small icon - `channelIdProvider` - `NotificationManager.NotificationChannelIdProvider` (@Nullable) - Provider for notification channel ID ## Methods ### setupNotificationBuilder ```kotlin @NonNull open fun setupNotificationBuilder( @NonNull context: Context, @NonNull message: NotificationMessage ): NotificationCompat.Builder ``` Provides the Notification Builder to be used when displaying a notification message. Creates and configures the notification builder for displaying messages. **Parameters:** - `context` - `Context` (@NonNull) - Android context - `message` - `NotificationMessage` (@NonNull) - The notification message to display **Returns:** - `NotificationCompat.Builder` (@NonNull) - Configured notification builder ## Inheritance Hierarchy ``` NotificationCustomizer └── ProximityNotificationCustomizer ``` ## Usage This customizer is specifically designed for proximity-based notifications (geofence/beacon messages) in the Marketing Cloud Mobile Push SDK. Extend this class to customize how proximity notifications are displayed to users. **Source:** [Salesforce Marketing Cloud Android SDK JavaDocs](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.notifications/-proximity-notification-customizer/index.html) # Public Properties The Salesforce Engagement SDK offers these convenience methods for retrieving inbox messages: - [`getAllMessages`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/get-messages.html) - [`getUnreadMessages`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/get-unread-messages.html) - [`getReadMessages`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/get-read-messages.html) - [`getDeletedMessages`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/get-deleted-messages.html) Each method returns a list of `InboxMessage` Objects. A consuming application can access these properties within each message object. ## Message Properties | Key | Type | Nullable | SDK Version Availability | | --------------------- | --------------------- | -------- | ------------------------ | | `alert` | String | Yes | Version 8 and later | | `custom` | String | Yes | Version 8 and later | | `customKeys` | `Map` | Yes | Version 8 and later | | `deleted` | Boolean | No | Version 8 and later | | `endDateUtc` | Date | Yes | Version 8 and later | | `id` | String | No | Version 8 and later | | `inboxMessage` | String | Yes | Version 9 and later | | `inboxMessageType` | Int | Yes | Version 9 and later | | `inboxSubtitle` | String | Yes | Version 9 and later | | `media` | InboxMessage.Media | Yes | Version 8 and later | | `notificationMessage` | NotificationMessage | Yes | Version 9 and later | | `read` | Boolean | No | Version 8 and later | | `sendDateUtc` | Date | Yes | Version 8 and later | | `sound` | String | Yes | Version 8 and later | | `startDateUtc` | Date | Yes | Version 8 and later | | `subject` | String | Yes | Version 8 and later | | `subtitle` | String | Yes | Version 8 and later | | `title` | String | Yes | Version 8 and later | | `url` | String | Yes | Version 8 and later | The `inboxMessageType` classifies inbox messages using integer values to represent different types. A value of `1` indicates an Inbox 1.0 message, `2` signifies an Inbox 2.0 message, and `3` represents a Push Copy to Inbox (PCTI) message. This attribute applies to Inbox 1.0, Inbox 2.0, and PCTI. Additionally, `inboxSubtitle` and `inboxMessage` are available to Inbox 2.0, while `notificationMessage` is specific to PCTI. The remaining properties in the message dictionary, such as `contentType` and `requestId`, are reserved for internal use. Don't use these properties in your app. ## Sort Inbox Messages by Sent Date To sort inbox messages in your custom inbox implementation, use the value of [sendDateUtc](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message/send-date-utc.html) from the Inbox Message returned by [getMessages](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages.inbox/-inbox-message-manager/get-messages.html). # Public Properties The SDK offers these convenience methods for retrieving inbox messages: - [getAllMessages](/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/marketingcloudsdk.html#getallmessages) - [getUnreadMessages](/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/marketingcloudsdk.html#getunreadmessages) - [getReadMessages](/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/marketingcloudsdk.html#getreadmessages) - [getDeletedMessages](/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/marketingcloudsdk.html#getdeletedmessages) ## Message Properties Each method returns an array of dictionaries. Each dictionary within the array represents a message. This table lists the properties returned in these dictionaries. | Key | Data Type | Notes | | --------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `alert` | String? | Available in SDK v8 and later. | | `contentType` | String? | For internal SDK use. Don't use in consuming applications. | | `custom` | String? | Available in SDK v8 and later. | | `deleted` | Boolean | Available in SDK v8 and later. | | `endDateUtc` | Date? | Available in SDK v8 and later. | | `id` | String? | Available in SDK v8 and later. | | `inboxMessage` | String? | Available in SDK v9 and later. | | `inboxMessageType` | Int? | Classifies inbox messages using integer values to represent different types. A value of `1` indicates an Inbox 1.0 message, `2` signifies an Inbox 2.0 message, and `3` represents a PCTI message. Available in SDK v9 and later. | | `inboxSubtitle` | String? | Only present when `inboxMessageType` is 2. Available in SDK v9 and later. | | `messageDeleted` | String? | For internal SDK use. Don't use in consuming applications. | | `messageHash` | String? | For internal SDK use. Don't use in consuming applications. | | `name` | String? | Available in SDK v8 and later. | | `notificationMessage` | [String: Any]? | The message content for a PCTI message. Only present when `inboxMessageType` is 3. Available in SDK v9 and later. | | `read` | Boolean | Available in SDK v8 and later. | | `requestId` | String? | For internal SDK use. Don't use in consuming applications. | | `sound` | String? | Available in SDK v8 and later. | | `startDateUtc` | Date? | Available in SDK v8 and later. | | `statusDirty` | String? | For internal SDK use. Don't use in consuming applications. | | `subject` | String? | Available in SDK v8 and later. | | `subtitle` | String? | Available in SDK v8 and later. | | `title` | String? | Available in SDK v8 and later. | | `url` | String? | Available in SDK v8 and later. | ## Sort Inbox Messages by Sent Date To sort inbox messages in your inbox implementation, use the value of `sendDateUtc` from the inbox message returned by `getAllMessages` and other getters. # PurchaseOrderEvent **Package:** `com.salesforce.marketingcloud.sfmcsdk.components.events` **SDK Version:** SFMC SDK v3.1.0 (Salesforce Marketing Cloud Unified SDK 11.0.0) **Platform:** androidJvm ## Description An E-commerce event for when a user makes a purchase. ## Declaration ```kotlin class PurchaseOrderEvent : OrderEvent ``` ## Inheritance Hierarchy ``` Event (interface) └── EngagementEvent (sealed class) └── OrderEvent (sealed class) └── PurchaseOrderEvent (class) ``` ## Inherited Properties ### From OrderEvent #### order ```kotlin val order: Order ``` Contains the order information associated with this event. ### From EngagementEvent #### category ```kotlin open override var category: Event.Category ``` The Event category Name. Category contains list of allowed values. #### priority ```kotlin open override val priority: Priority ``` Defines the priority level for the engagement event. ## Inherited Methods ### From EngagementEvent #### attributes() ```kotlin open override fun attributes(): Map ``` The Event attributes for this event. **Returns:** A map containing string keys and any-type values representing event attributes. #### name() ```kotlin open override fun name(): String ``` The name for the event. This value must match the Event Name used when creating the event in the Marketing Cloud UI for any action to result from tracking this event. **Returns:** The event name as a string. ## Related Classes ### Order The `order` property contains an `Order` data class with the following structure: ```kotlin data class Order @JvmOverloads constructor( val id: String, val lineItems: List = listOf(), val totalValue: Double? = null, val currency: String? = null, val attributes: Map = mapOf() ) ``` **Order Properties:** | Property | Type | Default | Description | | ------------ | ------------------ | ---------- | --------------------------------------------- | | `id` | `String` | required | A unique identifier for the order | | `lineItems` | `List` | `listOf()` | A list of line item data values | | `totalValue` | `Double?` | `null` | The total monetary value of the order | | `currency` | `String?` | `null` | The currency code for the order's total value | | `attributes` | `Map` | `mapOf()` | User-supplied custom attribute map | ## Related Events Other `OrderEvent` subclasses in the same package: - `PreorderEvent` - Represents a preorder event - `CancelOrderEvent` - Represents an order cancellation event - `ShipOrderEvent` - Represents an order shipment event - `DeliverOrderEvent` - Represents an order delivery event - `ReturnOrderEvent` - Represents an order return event - `ExchangeOrderEvent` - Represents an order exchange event ## Usage Notes - `PurchaseOrderEvent` is part of the sealed `OrderEvent` class hierarchy, providing type-safe handling of order-related events - This event should be tracked when a user completes a purchase transaction - The event name must match the Event Name configured in the Marketing Cloud UI for proper tracking and triggering of actions - Uses the `Order` data class to encapsulate order details including line items, total value, and currency # Push Delivery Analytics Starting with version 9.0.0, the MobilePush iOS SDK tracks successful delivery of push notifications to the SDK. To enable this feature, contact your Marketing Cloud Engagement admin. For more information, see [MobilePush Install, Inactive Devices, Push Delivery Events](https://help.salesforce.com/s/articleView?id=mktg.mc_mobilepush_events.htm). # Push Feature Module ## Packages - [com.salesforce.marketingcloud.pushfeature](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-pushfeature/pushfeature_index.md) - [com.salesforce.marketingcloud.pushfeature.config](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-pushfeature-config/pushfeature-config_index.md) - [com.salesforce.marketingcloud.pushfeature.notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-pushfeature-notifications/pushfeature-notifications_index.md) - [com.salesforce.marketingcloud.pushfeature.push](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-pushfeature-push/pushfeature-push_index.md) # Push Feature Module Push notification module for token management and badge handling ## API Reference ### [Classes](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/push-feature_classes_index.md) 2 classes # Push Messages Not Displayed If you encounter issues receiving messages in your app, consider these troubleshooting steps: - [Check the SDK’s log output](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios_push_display_log_check.md) - [Send a test push](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios_push_display_test_send.md) - [Evaluate the SDK’s state](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios_push_display_sdk_check.md) - [Unblock Network Ports](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios_push_display_unblock_ports.md) # Push Messaging This section provides API reference details for the Push Messaging module in the Flutter unified plugin. ## enablePush Enables push messaging. ### Syntax ```dart PushModule.enablePush(); ``` ### Returns - `Future` ### Example ```dart import 'package:sfmc_push/sfmc_push.dart'; await PushModule.requestSdk(); await PushModule.enablePush(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.push/-push-message-manager/enable-push.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/PushFeatureSdk/2.0/Classes/PushFeature.html#/c:@CM@PushFeatureSDK@objc(cs)SFPushFeature(im)setPushEnabledWithPushEnabled:>) ## disablePush Disables push messaging. ### Syntax ```dart PushModule.disablePush(); ``` ### Returns - `Future` ### Example ```dart import 'package:sfmc_push/sfmc_push.dart'; await PushModule.requestSdk(); await PushModule.disablePush(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.push/-push-message-manager/disable-push.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/PushFeatureSdk/2.0/Classes/PushFeature.html#/c:@CM@PushFeatureSDK@objc(cs)SFPushFeature(im)setPushEnabledWithPushEnabled:>) ## isPushEnabled Returns the state of the `pushEnabled` flag. ### Syntax ```dart PushModule.isPushEnabled(); ``` ### Returns - `Future` - A future that indicates whether push messaging is enabled. ### Example ```dart import 'package:sfmc_push/sfmc_push.dart'; await PushModule.requestSdk(); final enabled = await PushModule.isPushEnabled(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.push/-push-message-manager/is-push-enabled.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/PushFeatureSdk/2.0/Classes/PushFeature.html#/c:@CM@PushFeatureSDK@objc(cs)SFPushFeature(im)isPushEnabled>) ## getPushToken Returns the token that Marketing Cloud uses to send push messages to the device. ### Syntax ```dart PushModule.getPushToken(); ``` ### Returns - `Future` - A future that completes with the push token string, or `null`. ### Example ```dart import 'package:sfmc_push/sfmc_push.dart'; await PushModule.requestSdk(); final token = await PushModule.getPushToken(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.push/-push-message-manager/get-push-token.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/PushFeatureSdk/2.0/Classes/PushFeature.html#/c:@CM@PushFeatureSDK@objc(cs)SFPushFeature(im)deviceToken>) ## pushTokenStream A broadcast stream of push token updates. Emits a new token string when the push token changes. ### Syntax ```dart PushModule.pushTokenStream; ``` ### Returns - `Stream` ### Example ```dart import 'package:sfmc_push/sfmc_push.dart'; await PushModule.requestSdk(); final sub = PushModule.pushTokenStream.listen((token) { print('Token updated: $token'); }); await sub.cancel(); ``` # Push Messaging This section provides API reference details for the Push Messaging module in the React Native unified plugin. ## enablePush Enables push messaging in the native Marketing Cloud SDK. ### Syntax ```javascript PushMessagingSdkModule.enablePush(); ``` ### Returns - `void` ### Example ```javascript import { PushModule } from "@sfmc/react-native-push"; import type { PushApi } from "@sfmc/react-native-push"; const push: PushApi = await PushModule.requestSdk(); push.enablePush(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.push/-push-message-manager/enable-push.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/PushFeatureSdk/2.0/Classes/PushFeature.html#/c:@CM@PushFeatureSDK@objc(cs)SFPushFeature(im)setPushEnabledWithPushEnabled:>) ## disablePush Disables push messaging in the native Marketing Cloud SDK. ### Syntax ```javascript PushMessagingSdkModule.disablePush(); ``` ### Returns - `void` ### Example ```javascript import { PushModule } from "@sfmc/react-native-push"; import type { PushApi } from "@sfmc/react-native-push"; const push: PushApi = await PushModule.requestSdk(); push.disablePush(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.push/-push-message-manager/disable-push.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/PushFeatureSdk/2.0/Classes/PushFeature.html#/c:@CM@PushFeatureSDK@objc(cs)SFPushFeature(im)setPushEnabledWithPushEnabled:>) ## isPushEnabled Returns the current state of the push-enabled flag in the native Marketing Cloud SDK. ### Syntax ```javascript PushMessagingSdkModule.isPushEnabled(); ``` ### Returns - `Promise` - A promise that resolves to whether push messaging is enabled. ### Example ```javascript import { PushModule } from "@sfmc/react-native-push"; import type { PushApi } from "@sfmc/react-native-push"; const push: PushApi = await PushModule.requestSdk(); const enabled = await push.isPushEnabled(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.push/-push-message-manager/is-push-enabled.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/PushFeatureSdk/2.0/Classes/PushFeature.html#/c:@CM@PushFeatureSDK@objc(cs)SFPushFeature(im)isPushEnabled>) ## getPushToken Returns the token that Marketing Cloud uses to send push messages to the device. ### Syntax ```javascript PushMessagingSdkModule.getPushToken(); ``` ### Returns - `Promise` - A promise that resolves to the push token string, or `null`. ### Example ```javascript import { PushModule } from "@sfmc/react-native-push"; import type { PushApi } from "@sfmc/react-native-push"; const push: PushApi = await PushModule.requestSdk(); const token = await push.getPushToken(); const sub = PushModule.getEmitter().addListener("sfmc_push_token_refreshed", ({ token }) => { console.log("Token refreshed:", token); }); sub.remove(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.push/-push-message-manager/get-push-token.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/PushFeatureSdk/2.0/Classes/PushFeature.html#/c:@CM@PushFeatureSDK@objc(cs)SFPushFeature(im)deviceToken>) # Push Models Module ## Packages - [com.salesforce.marketingcloud.pushmodels](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-pushmodels/pushmodels_index.md) - [com.salesforce.marketingcloud.pushmodels.data](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-pushmodels-data/pushmodels-data_index.md) - [com.salesforce.marketingcloud.pushmodels.exceptions](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-pushmodels-exceptions/pushmodels-exceptions_index.md) - [com.salesforce.marketingcloud.pushmodels.location](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-pushmodels-location/pushmodels-location_index.md) - [com.salesforce.marketingcloud.pushmodels.rich](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-pushmodels-rich/pushmodels-rich_index.md) - [com.salesforce.marketingcloud.pushmodels.rich.buttons](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-pushmodels-rich-buttons/pushmodels-rich-buttons_index.md) - [com.salesforce.marketingcloud.pushmodels.rich.carousel](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-pushmodels-rich-carousel/pushmodels-rich-carousel_index.md) # Push Notifications Use the Salesforce Engagement SDK to send push notifications to your mobile app users. Send push notifications to reach your users with timely, personalized messages, even when they aren’t actively using your app. ## Configure Push Notifications Start by setting up push notification capabilities in your app. For iOS apps, see [Push Notifications for iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios.md) and [Enable Push Notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_enable.md). For Android apps, see [Push Notifications for Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_android.md). Before sending notifications to Android 13+ devices, [Request Push Notification Permission](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_android_permission_request.md) from users. ## Customize Notification Appearance Customize the look and behavior of your push notifications to match your brand. For iOS apps, see [Customize Push Notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_customize.md) and [Customize Sounds](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_sounds_customize.md) to customize notification sounds. For Android apps, start with [Customize Push Notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_android_customize.md). Then explore [Basic Customization](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_android_customize_basic.md) for icons, colors, and sounds. For complete control over presentation, see [Full Control Customization](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_android_customize_full_control.md). You can also create [Custom Notification Builder](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_android_custom_notification.md) layouts. ## Add Rich Media and Interactions Enhance your notifications with media and interactive elements. iOS apps can show [Rich Notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_rich_notifications.md) with images and videos. iOS apps can also implement [Interactive Notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_interactive_notifications.md) with action buttons. Android apps can implement [Button Carousel Notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_android_button_carousel.md) with multiple actions. ## Handle Notification Actions on iOS Respond to user interactions with notifications in your iOS app. You can [Handle URLs](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_urls_handle.md), [Handle OpenDirect URLs](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_opendirect_urls_handle.md) for deep linking, and [Handle Custom Keys](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_custom_keys_handle.md) for custom payload data. ## Target and Track Notifications Send notifications to specific user groups and measure their effectiveness. Android apps can [Send Push Notifications to Subsegments](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_android_subsegments_send.md) to target particular audiences. Track notification performance by enabling push analytics. For iOS apps, see [Enable Push Analytics](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_push_analytics_enable.md). For Android apps, see [Enable Push Analytics](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_android_push_analytics_enable.md). # Push Notifications for Android Use the Salesforce Engagement SDK to send push notifications to your Android app users. Push notifications help you engage users with timely messages, promotions, and updates. ## Prerequisites Before you implement push notifications, complete these tasks: - [Set up Firebase Cloud Messaging (FCM)](https://developer.salesforce.com/docs/marketing/before-you-begin/engagement_sdk_guides_before_you_begin_prereqs.md#configure-google-firebase-for-android) in your Google Developer account - [Integrate the SDK for Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_integrate_android/engagement_sdk_guide_integrate_android.md) - Configure your Android app in Marketing Cloud Engagement ## Getting Started For Android 13 and later, [request runtime notification permission](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_android_permission_request.md) before your app can display notifications. ## Customization You can customize the content and behaviors of the notifications that you send. The SDK supports these customizations for Android push notifications: - [Customize Push Notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_android_customize_basic.md) — Customize notifications, launch intents, and tap actions - [Advanced Push Notification Customization](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_android_customize_full_control.md) — Manage all aspects of notification display properties, tap actions, notification channel creation, and launch intent actions - [Custom Notification Channels](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_android_custom_notification.md) — Create custom notification channels for Android 8.0 and later - [Interactive Notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_android_button_carousel.md) — Configure actions for button taps and carousel image interactions - [Notification Segmentation](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_android_subsegments_send.md) — Implement logic to determine whether to display a notification based on user preferences, login status, or other factors ## Analytics To track the delivery and performance of your notifications, [enable push analytics](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_android_push_analytics_enable.md) in your app. # Push Notifications for Android Implement and customize push notifications in your Android app using the Mobile App Messaging SDK. ## Prerequisites Before you implement push notifications, [configure the SDK for Android in your app](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_next_integrate_android/mc_next_integrate_android.md). ## Getting Started Start by enabling push notifications and requesting permissions: - [Enable Push Notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_android_enable.md) — Configure your app to receive push notifications - [Request Runtime Notification Permission](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_android_permission_request.md) — Request notification permission on Android 13 and later ## Customization Customize how push notifications appear and behave in your app: - [Basic Push Notification Customization](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_android_customize_basic.md) — Customize notification appearance and behavior - [Full Control Push Notification Customization](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_android_customize_full_control.md) — Take full control over notification display - [Implement Default and Custom Notification Channels](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_android_custom_notification.md) — Create custom notification channels - [Configure Button and Carousel Actions](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_android_button_carousel.md) — Handle button taps and carousel interactions ## See Also - [Push Notifications for iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_ios.md) # Push Notifications for iOS Use the Salesforce Engagement SDK to send push notifications to your iOS app users. Push notifications help you engage users with timely messages, promotions, and updates. ## Prerequisites Before you implement push notifications, complete these tasks: - [Integrate the SDK for iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_integrate_ios/mc_engagement_integrate_ios.md) - [Configure the SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_integrate_ios/mc_engagement_integrate_ios_configure.md) - Enable push notifications in your Apple Developer account - Configure your iOS app in Marketing Cloud Engagement ## Getting Started Start by [configuring your iOS app to receive and display push notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_enable.md). ## Customization You can customize the content and behaviors of the notifications that you send. The SDK supports these customizations for iOS push notifications: - [Custom Sounds](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_sounds_customize.md) - [Interactive Push Notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_interactive_notifications.md) - [Rich Media Notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_rich_notifications.md) ## Handling Notification Data Push notifications can include URLs, custom data, and other information that require special handling to deep link into your app, open web content, or trigger specific functionality. The SDK provides methods to extract and process this data: - [Handle URLs in Push Notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_urls_handle.md) - [Handle OpenDirect URLs](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_opendirect_urls_handle.md) - [Handle Custom Keys](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_custom_keys_handle.md) ## Analytics To track the delivery and performance of your notifications, [enable push analytics](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications_ios_push_analytics_enable.md) in your app. # Push Notifications for iOS Implement and customize push notifications in your iOS app using the Mobile App Messaging SDK. ## Prerequisites Before you implement push notifications, [configure the SDK for iOS in your app](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_next_integrate_ios/mc_next_integrate_ios.md). ## Getting Started Get started by [configuring your app to receive push notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_ios_enable.md). ## Customization After you set up your app to receive push notifications, customize the appearance and behavior of push notifications. - [Specify a Custom Notification Sound](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_ios_sounds_customize.md) — Use custom audio files for push notification alerts. - [Display Interactive Notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_ios_interactive_notifications.md) — Add buttons and actions to push notifications. - [Send Rich Notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_ios_rich_notifications.md) — Include images, videos, and mutable content in notifications. ## URL Handling For messages that include links, [configure URL handling in your app](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_ios_urls_handle.md). ## See Also - [Push Notifications for Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_android.md) # Push Notifications in the Engagement SDK Implement and customize push notifications in your mobile apps using the Engagement SDK. ## Getting Started Configure push notifications for [Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_android.md) and [iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_ios.md) apps. ## Enable Push Notifications For Android apps, [enable push notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_android_enable.md) to configure your app to receive push notifications. On Android 13 and later, you must also [request runtime notification permission](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_android_permission_request.md) from users. For iOS apps, [enable push notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_ios_enable.md) to configure your app to receive push notifications. ## Customize Push Notifications - [Basic Push Notification Customization on Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_android_customize_basic.md) — Customize notification appearance and behavior. - [Full Control Push Notification Customization on Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_android_customize_full_control.md) — Take full control over notification display. * [Implement Default and Custom Notification Channels on Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_android_custom_notification.md) — Create custom notification channels. * [Configure Button and Carousel Actions on Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_android_button_carousel.md) — Handle button taps and carousel interactions. * [Specify a Custom Notification Sound on iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_ios_sounds_customize.md) — Use custom audio files for push notification alerts. * [Display Interactive Notifications on iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_ios_interactive_notifications.md) — Add buttons and actions to push notifications. * [Send Rich Notifications on iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_ios_rich_notifications.md) — Include images, videos, and mutable content in notifications. * [Handle URLs from Push Notifications on iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications_ios_urls_handle.md) — Process CloudPage and action URLs from push notifications. # PushException ## Package `com.salesforce.marketingcloud.pushmodels.exceptions` ## Description Exception thrown when there is an error in the push module. This is the base exception for all push exceptions. ## Class Declaration ```kotlin open class PushException( val errorCode: PushException.ErrorCode, val message: String? = null ) : Exception ``` ## Constructors ### Primary Constructor ```kotlin constructor( errorCode: PushException.ErrorCode, message: String? = null ) ``` **Parameters:** - `errorCode` - The error code enum value indicating the type of push error - `message` - Optional error message string (nullable, defaults to null) ## Properties ### errorCode ```kotlin val errorCode: PushException.ErrorCode ``` The error code associated with this exception. ### message ```kotlin open override val message: String? ``` The optional error message describing the exception. ## Methods ### toJson ```kotlin fun toJson(): JSONObject ``` Returns the error message as a JSON object to be sent to the server. **Returns:** A JSONObject representation of the error ## Nested Types ### ErrorCode ```kotlin enum ErrorCode : Enum ``` Enum defining the various error codes for push exceptions. #### Enum Values - `UNKNOWN_ERROR` - Represents an unspecified or unknown error condition - `INVALID_JSON` - Indicates a JSON parsing or validation error - `INVALID_COMPRESSION` - Signifies an issue with data compression - `MISSING_FIELD` - Denotes a required field is absent - `UNSUPPORTED_TYPE` - Indicates an unsupported data or content type - `BAD_MEDIA` - Represents an error related to media content #### Properties - `entries` - Returns an immutable list of all enum entries in declaration order (type: `EnumEntries`) #### Methods - `valueOf(value: String)` - Returns the enum constant matching the specified name (exact match required) - `values()` - Returns an array of all constants in this enum type ## Inheritors The following classes inherit from PushException: - `InvalidJsonException` - `InvalidCompressionException` - `MissingFieldException` - `UnsupportedWidgetException` - `UnknownErrorException` - `BadMediaException` ## Module Information - Part of: Salesforce Marketing Cloud Unified SDK - Module: Push Models Module v1.0.2 - SDK Version: 11.0.0 - Platform: androidJvm # PushFeature **Package:** `com.salesforce.marketingcloud.pushfeature` **Type:** `class` **Implements:** `ModuleInterface` ## Description Main class for the Push Feature Module. This class provides comprehensive functionality for push notifications and related features within the Salesforce Marketing Cloud SDK. **Key Features:** - Firebase Cloud Messaging (FCM) integration - Push token management and refresh - Push notification enablement/disablement - Silent push message handling - Job scheduling for background operations - State management and debugging capabilities **Initialization Pattern:** - Singleton pattern with thread-safe initialization - State management and lifecycle handling - Component-based architecture - Proper error handling and logging - Asynchronous initialization with completion callbacks **Thread Safety:** This class is thread-safe and uses atomic operations for state management. All public methods can be called from any thread. **Since:** 1.0.0 ## Example Usage ```kotlin // Initialize PushFeature module PushFeature.init(context, config, sdkComponents) { status -> if (status.isUsable) { val pushFeature = PushFeature.getInstance() val pushMessageManager = pushFeature.getPushMessageManager() // Register for token refresh events pushMessageManager.registerTokenRefreshListener { token -> // Handle new token } } } ``` ## Types ### Companion `object Companion` ## Properties ### state ```kotlin open override val state: JSONObject ``` Returns the current state of the PushFeature module as a JSONObject. ## Methods ### getConfig ```kotlin fun getConfig(): PushFeatureConfig ``` Gets the configuration used to initialize this PushFeature instance. **Returns:** The `PushFeatureConfig` instance --- ### getInitializationStatus ```kotlin fun getInitializationStatus(): PushFeatureInitializationStatus? ``` Gets the initialization status of this PushFeature instance. **Returns:** The initialization status or null if not initialized --- ### getNotificationManager ```kotlin fun getNotificationManager(): NotificationManager ``` Gets the NotificationManager instance for notification operations. **Returns:** The `NotificationManager` instance --- ### getPushMessageManager ```kotlin fun getPushMessageManager(): PushMessageManager ``` Gets the PushMessageManager instance for push notification operations. **Returns:** The `PushMessageManager` instance --- ### isTornDown ```kotlin fun isTornDown(): Boolean ``` Checks if the PushFeature instance is torn down. **Returns:** `true` if torn down, `false` otherwise # PushFeature `Class` The main API class of PushFeature module ## Declaration ```swift @objc(SFPushFeature) public final class PushFeature: NSObject, SFMCModule, Subscriber, Publisher @objc public static func requestSdk(_ callback: @escaping (_ pushFeature: PushFeatureApi?) -> Void) public func setDeviceToken(_ deviceToken: Data) public func deviceToken() -> String? public func setPushEnabled(pushEnabled: Bool) public func isPushEnabled() -> Bool public func setNotificationResponse(_ response: UNNotificationResponse) public func notificationResponse() -> UNNotificationResponse? public func setNotificationUserInfo(_ userInfo: [AnyHashable : Any]) public func notificationUserInfo() -> [AnyHashable : Any] public func setURLHandlingDelegate(_ delegate: URLHandlingDelegate) ``` ## Request SDK Method ### `requestSdk(_:)` Requests the Push Feature Module when it’s operational and safe to use. The provided callback will be invoked with the Push Feature Module when it’s ready. All push feature module-related API calls should be made within this function. ```swift @objc public static func requestSdk(_ callback: @escaping (_ pushFeature: PushFeatureApi?) -> Void) ``` --- ## Push Token Methods ### `setDeviceToken(_:)` Responsible for sending the Apple device token back to all the subscribers. It marks the end of the token registration flow. If it is unable to reach Salesforce server, it will save the token and try again later. This method is necessary to the implementation of Salesforce Push. ```swift public func setDeviceToken(_ deviceToken: Data) ``` --- ### `deviceToken()` Returns the device token as a String. ```swift public func deviceToken() -> String? ``` --- ## Feature Toggle Methods ### `setPushEnabled(pushEnabled:)` Developer override to set the state of push enablement to true/false. If set to false, the application will not receive any push notifications once the Marketing Cloud server has been updated. When this value is false, it takes precedence (overrides) the user notifications settings (i.e., setting this to false will always disable push.) Conversely, if the user has notifications settings disabled, the developer cannot enable push via this method. A false value from either source (user settings or developer interface) always wins. ```swift public func setPushEnabled(pushEnabled: Bool) ``` --- ### `isPushEnabled()` Combination of push enabled from user notifications settings and push enabled by sdk. ```swift public func isPushEnabled() -> Bool ``` --- ## PushNotification Methods ### `setNotificationResponse(_:)` Informs the module of the current notification response when user clicks a notification. ```swift public func setNotificationResponse(_ response: UNNotificationResponse) ``` --- ### `notificationResponse()` Returns the last notification response delivered to the module. ```swift public func notificationResponse() -> UNNotificationResponse? ``` --- ### `setNotificationUserInfo(_:)` Informs the module of the current userInfo when user clicks a notification. ```swift public func setNotificationUserInfo(_ userInfo: [AnyHashable : Any]) ``` --- ### `notificationUserInfo()` Returns the user info of the last notification delivered to the module. ```swift public func notificationUserInfo() -> [AnyHashable : Any] ``` --- ## URLHandling ### `setURLHandlingDelegate(_:)` Set URLHandling delegate to handle URLs in OpenDirect URLs, CloudPage URLs, CloudPage URLs from inbox messages.This value takes precedence over the config setting which is passed during the SDK initialization. ```swift public func setURLHandlingDelegate(_ delegate: URLHandlingDelegate) ``` --- # PushFeatureConfig ## Package `com.salesforce.marketingcloud.pushfeature.config` ## Overview A data class that extends `PushFeatureModuleConfig` to configure push notification functionality for the Salesforce Marketing Cloud SDK. It provides settings for Firebase Cloud Messaging integration, notification customization, URL handling, and notification filtering. ## Class Declaration ```kotlin data class PushFeatureConfig : PushFeatureModuleConfig ``` ## Inheritance - Extends: `PushFeatureModuleConfig` ## Properties ### senderId ```kotlin @JvmField val senderId: String? ``` The Firebase Cloud Messaging sender ID for push notifications. This is required for FCM integration. ### notificationCustomizationOptions ```kotlin @JvmField val notificationCustomizationOptions: NotificationCustomizationOptions ``` Configuration options for customizing notification appearance and behavior, including icon, sound, LED color, and other visual elements. ### urlHandler ```kotlin @JvmField val urlHandler: UrlHandler? ``` Optional handler for processing URLs from push notifications. Implement this interface to customize URL handling behavior. ### shouldShowNotificationListener ```kotlin @JvmField val shouldShowNotificationListener: NotificationManager.ShouldShowNotificationListener? ``` Optional listener for filtering or controlling whether notifications should be displayed. Allows dynamic control of notification visibility based on custom logic. ## Methods ### toBuilder() ```kotlin fun toBuilder(): PushFeatureConfig.Builder ``` Creates a new Builder instance initialized with the current configuration values. **Returns:** A `Builder` with current configuration values ## Nested Types ### Builder ```kotlin class PushFeatureConfig.Builder ``` Builder class for constructing `PushFeatureConfig` instances using a fluent API pattern. #### Builder Methods ##### setSenderId ```kotlin fun setSenderId(senderId: String?): Builder ``` Sets the Firebase Cloud Messaging sender ID. **Parameters:** - `senderId` - The FCM sender ID (typically a 12-digit number) **Returns:** The Builder instance for method chaining ##### setNotificationCustomizationOptions ```kotlin fun setNotificationCustomizationOptions(options: NotificationCustomizationOptions): Builder ``` Sets the notification customization options. **Parameters:** - `options` - NotificationCustomizationOptions instance with customization settings **Returns:** The Builder instance for method chaining ##### setUrlHandler ```kotlin fun setUrlHandler(handler: UrlHandler?): Builder ``` Sets the URL handler for processing notification URLs. **Parameters:** - `handler` - UrlHandler implementation or null **Returns:** The Builder instance for method chaining ##### setShouldShowNotificationListener ```kotlin fun setShouldShowNotificationListener(listener: NotificationManager.ShouldShowNotificationListener?): Builder ``` Sets the listener for controlling notification visibility. **Parameters:** - `listener` - ShouldShowNotificationListener implementation or null **Returns:** The Builder instance for method chaining ##### build ```kotlin fun build(): PushFeatureConfig ``` Finalizes the configuration and creates the `PushFeatureConfig` instance. **Returns:** A new `PushFeatureConfig` instance with the specified configuration ### Companion ```kotlin object Companion ``` Companion object providing factory methods for creating Builder instances. #### Companion Methods ##### builder ```kotlin fun builder(): PushFeatureConfig.Builder ``` Creates a new Builder instance for constructing a `PushFeatureConfig`. **Returns:** A new `PushFeatureConfig.Builder` instance ## Usage Example ```kotlin val pushConfig = PushFeatureConfig.builder() .setSenderId("123456789012") .setNotificationCustomizationOptions( NotificationCustomizationOptions.create(R.drawable.ic_notification) ) .setUrlHandler(customUrlHandler) .setShouldShowNotificationListener { message -> // Return true to show notification, false to suppress true } .build() ``` ## Related Types - **PushFeature** - The main push feature module - **PushFeatureModuleConfig** - Parent configuration class - **NotificationCustomizationOptions** - Notification customization settings - **UrlHandler** - Interface for handling URLs from notifications - **NotificationManager.ShouldShowNotificationListener** - Interface for notification filtering # PushFeatureConfigBuilder `Class` PushFeatureConfigBuilder class ## Declaration ```swift @objc(SFPushFeatureConfigBuilder) public class PushFeatureConfigBuilder : NSObject @discardableResult @objc public func build() -> PushFeatureConfig @discardableResult @objc public func setApplicationControlsBadging(_ enabled: Bool) -> PushFeatureConfigBuilder @discardableResult @objc public func setURLHandlingDelegate(_ delegate: URLHandlingDelegate) -> PushFeatureConfigBuilder ``` ## Build Method ### `build()` Creates a PushFeatureConfig containing the current builder configuration settings. This can be passed to the ConfigBuilder method(s) ```swift @discardableResult @objc public func build() -> PushFeatureConfig ``` --- ### `setApplicationControlsBadging(_:)` Sets the configuration value which allows sdk to control application badge count ```swift @discardableResult @objc public func setApplicationControlsBadging(_ enabled: Bool) -> PushFeatureConfigBuilder ``` --- ### `setURLHandlingDelegate(_:)` Set URLHandling delegate to handle URLs in OpenDirect URLs, CloudPage URLs, CloudPage URLs from inbox messages ```swift @discardableResult @objc public func setURLHandlingDelegate(_ delegate: URLHandlingDelegate) -> PushFeatureConfigBuilder ``` --- # PushFeatureInitializationStatus ## Package `com.salesforce.marketingcloud.pushfeature` ## Description Represents the initialization status of the PushFeature module, following the same pattern as the main SDK's InitializationStatus. This class provides information about the outcome of the PushFeature module's initialization process and helps diagnose any issues that may have occurred. ## Type `class` ## Properties ### `initializedComponents` - **Type:** `List` - **Description:** List of component names initialized in the module. Useful for debugging initialization issues. ### `isUsable` - **Type:** `Boolean` - **Description:** Indicates if the module initialized enough to be usable. Returns `true` when status is `SUCCESS` or `COMPLETED_WITH_DEGRADED_FUNCTIONALITY`. ### `pushManagerError` - **Type:** `Boolean` - **Description:** Indicates if an error occurred while initializing the push manager. ### `status` - **Type:** `PushFeatureInitializationStatus.Status` - **Description:** Initialization status of the PushFeature module. ### `unrecoverableException` - **Type:** `Throwable?` - **Description:** If an unrecoverable exception occurred during initialization, it can be accessed here. This property is nullable. ## Nested Types ### Status **Type:** `enum class Status : Enum` Represents the overall outcome of the PushFeature module's initialization. #### Enum Values ##### `SUCCESS` Indicates that the PushFeature module initialized successfully without any issues. ##### `COMPLETED_WITH_DEGRADED_FUNCTIONALITY` Indicates that the PushFeature module completed initialization but with some reduced functionality. The module is still usable but may not have all features available. # PushKeys **Package:** `com.salesforce.marketingcloud.pushmodels` **Module:** Push Models Module v1.0.2 **Type:** `object` ## Overview `PushKeys` is a Kotlin object that provides constant string keys used for push notification configuration in the Salesforce Marketing Cloud Unified SDK. ## Properties All properties are `const val` of type `String`: ### Layout & Styling - **`alignment`** - Alignment configuration key - **`backgroundColor`** - Background color configuration key - **`fontColor`** - Font color configuration key - **`fontSize`** - Font size configuration key - **`fontStyle`** - Font style configuration key - **`padding`** - Padding configuration key ### Content - **`title`** - Title text key - **`subtitle`** - Subtitle text key - **`text`** - Body text content key - **`altText`** - Alternative text key ### Media & Icons - **`icon`** - Icon resource key - **`smallIcon`** - Small icon resource key - **`largeIcon`** - Large icon resource key - **`media`** - Media content key ### Interactive Elements - **`actions`** - Actions configuration key - **`buttons`** - Buttons configuration key - **`url`** - URL link key ### Structure - **`items`** - List items key - **`style`** - Style configuration key - **`type`** - Type identifier key - **`identifier`** - Unique identifier key - **`viewTemplate`** - View template configuration key ### Timing - **`timerInMilliSec`** - Timer duration in milliseconds key ## Usage These constants are used as keys for configuring push notification properties and layouts within the Salesforce Marketing Cloud SDK. --- **Source:** [MarketingCloudSDK-Android Javadocs](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushmodelsmodule/com.salesforce.marketingcloud.pushmodels/-push-keys/index.html) # PushMessageManager **Package:** `com.salesforce.marketingcloud.pushfeature.push` **Module:** Push Feature Module v2.0.0 ## Overview ```kotlin abstract class PushMessageManager ``` Abstract class for managing push messages in the PushFeature module. Provides APIs for token management, message handling, and push enablement. This class serves as the public interface for push functionality, similar to the original PushMessageManager in the main SDK. ## Constructors ### PushMessageManager ```kotlin constructor() ``` ## Nested Types ### Companion ```kotlin object Companion ``` ### PushStatus ```kotlin sealed interface PushStatus ``` Represents the current state of push enablement, providing detailed information about why push notifications might be disabled. ### PushTokenRefreshListener ```kotlin fun interface PushTokenRefreshListener ``` Listener interface for push token refresh events. ### SilentPushListener ```kotlin fun interface SilentPushListener ``` Listener interface for silent push messages. Silent push messages are background messages that don't display notifications. ## Methods ### enablePush ```kotlin abstract fun enablePush() ``` Enables push messaging in the SDK. Push messaging is on by default. If after enabling push you still don't see notifications then check the system notification settings. ### disablePush ```kotlin abstract fun disablePush() ``` Disables push messaging in the SDK. Calling this will result in no push messages being sent to the device. ### isPushEnabled ```kotlin abstract fun isPushEnabled(): Boolean ``` Returns whether or not push messaging is enabled. If false then no push messages will be sent to the device. **Returns:** `Boolean` - True if push messaging is enabled ### getPushEnabledState ```kotlin abstract fun getPushEnabledState(): PushMessageManager.PushStatus ``` Returns the current state of push messaging enablement with detailed information about why push notifications might be disabled. **Returns:** `PushMessageManager.PushStatus` - Current push status ### getPushToken ```kotlin abstract fun getPushToken(): String? ``` Returns the push token used to push. This is either the value retrieved by the SDK or the one provided in `setPushToken`. **Returns:** `String?` - The push token, or null if not available ### setPushToken ```kotlin abstract fun setPushToken(pushToken: String) ``` Only call this method if you are handling the request, and refresh of, the push token from Google. Set the push token to be used by the Marketing Cloud to send push messages to the device. The push token is a required value to send a registration payload to the Marketing Cloud so if you fail to set this value you will not see updates to the registration. **Parameters:** - `pushToken: String` - The push token from Google ### handleMessage (RemoteMessage) ```kotlin abstract fun handleMessage(message: RemoteMessage): Boolean ``` Handles the remote message payload for any message sent from the Marketing Cloud. **Parameters:** - `message: RemoteMessage` - The remote message to handle **Returns:** `Boolean` - True if the message was handled ### handleMessage (Map) ```kotlin abstract fun handleMessage(pushData: Map): Boolean ``` Handles the push message payload for any message sent from the Marketing Cloud. **Parameters:** - `pushData: Map` - The push message data **Returns:** `Boolean` - True if the message was handled ### getPushDebugInfo ```kotlin abstract fun getPushDebugInfo(): JSONObject ``` Returns information that can help investigate push message issues. Please be sure to provide this information when submitting a request for support. **Returns:** `JSONObject` - Debug information as JSON ### registerTokenRefreshListener ```kotlin abstract fun registerTokenRefreshListener(listener: PushMessageManager.PushTokenRefreshListener) ``` Registers the provided `PushTokenRefreshListener`. **Parameters:** - `listener: PushMessageManager.PushTokenRefreshListener` - The listener to register ### unregisterTokenRefreshListener ```kotlin abstract fun unregisterTokenRefreshListener(listener: PushMessageManager.PushTokenRefreshListener) ``` Unregisters the provided `PushTokenRefreshListener`. **Parameters:** - `listener: PushMessageManager.PushTokenRefreshListener` - The listener to unregister ### registerSilentPushListener ```kotlin abstract fun registerSilentPushListener(listener: PushMessageManager.SilentPushListener) ``` Registers the provided `SilentPushListener`. **Parameters:** - `listener: PushMessageManager.SilentPushListener` - The listener to register ### unregisterSilentPushListener ```kotlin abstract fun unregisterSilentPushListener(listener: PushMessageManager.SilentPushListener) ``` Unregisters the provided `SilentPushListener`. **Parameters:** - `listener: PushMessageManager.SilentPushListener` - The listener to unregister # PushMessagingService ## Package `com.salesforce.marketingcloud.pushfeature.push` ## Module Push Feature Module v2.0.0 ## SDK Salesforce Marketing Cloud Unified SDK 11.0.0 --- ## Class Declaration ```kotlin class PushMessagingService : FirebaseMessagingService ``` ## Description A Firebase Cloud Messaging service implementation for handling push notifications within the PushFeature module. This service extends `FirebaseMessagingService` to provide integration between Firebase Cloud Messaging and the PushFeature module, managing token refresh events and incoming push messages. ### Key Responsibilities - Handling new FCM token generation - Processing incoming push messages - Forwarding events to the PushFeature module - Logging and error handling for FCM events ### Integration - Extends `FirebaseMessagingService` for FCM integration - Integrates with PushFeature module for token management - Provides logging through SFMC SDK logging system - Supports testing through visible methods ### Lifecycle This service is managed by the Android system and Firebase SDK. It will be automatically started when FCM events occur. ### Since 1.0.0 ### See Also - `FirebaseMessagingService` - `PushFeature` - `PushMessageManager` --- ## Constructors ### PushMessagingService ```kotlin constructor() ``` Default constructor for the service. --- ## Methods ### onMessageReceived ```kotlin open override fun onMessageReceived(message: RemoteMessage) ``` Called when a new push message is received. **Parameters:** - `message: RemoteMessage` - The incoming remote message from FCM --- ### onNewToken ```kotlin open override fun onNewToken(token: String) ``` Called when a new FCM token is generated. **Parameters:** - `token: String` - The new FCM registration token --- ## Usage Example To use this service in your Android application, add it to your `AndroidManifest.xml`: ```xml ``` # PushNotificationActionHandler ## Package `com.salesforce.marketingcloud.notifications` ## Overview A `BroadcastReceiver` class that processes action payloads from Marketing Cloud Push Notifications. ## Inheritance ```kotlin class PushNotificationActionHandler : BroadcastReceiver ``` Extends: `android.content.BroadcastReceiver` ## Constructors ### PushNotificationActionHandler ```kotlin constructor() ``` Default constructor with no parameters. ## Methods ### onReceive ```kotlin open override fun onReceive( context: Context, intent: Intent ) ``` Overrides the `BroadcastReceiver.onReceive()` method to handle incoming broadcast intents. **Parameters:** - `context`: The `Context` in which the receiver is running - `intent`: The `Intent` being received **Returns:** Unit (void) --- _SDK Version: 11.0.0.0_ _Platform: androidJvm_ # QuickViewCatalogEvent ## Overview An event to capture when a user performs a quick view of a catalog object. **Package:** `com.salesforce.marketingcloud.sfmcsdk.components.events` **Platform:** androidJvm **SDK Version:** SFMC SDK v3.1.0 (API 11.0.0) ## Class Declaration ```kotlin class QuickViewCatalogEvent : CatalogEvent ``` ## Inheritance Hierarchy ``` Event (abstract) └─ EngagementEvent (sealed) └─ CatalogEvent (sealed) └─ QuickViewCatalogEvent (class) ``` ## Description `QuickViewCatalogEvent` is a concrete implementation of `CatalogEvent` used to track when a user performs a quick view action on a catalog object within your application. This event is part of the Salesforce Marketing Cloud SDK's engagement tracking system for catalog-related user interactions. ## Inherited Properties From `CatalogEvent`: ### catalogObject ```kotlin val catalogObject: CatalogObject ``` Represents the catalog object associated with this event. From `EngagementEvent`: ### category ```kotlin open override var category: Event.Category ``` The Event category Name. Category contains list of allowed values. ### priority ```kotlin open override val priority: Priority ``` Defines the priority level for the engagement event. ## Inherited Methods From `EngagementEvent`: ### name() ```kotlin open override fun name(): String ``` The name for the event. This value must match the Event Name used when creating the event in the Marketing Cloud UI for any action to result from tracking this event. **Returns:** The event name as a String. ### attributes() ```kotlin open override fun attributes(): Map ``` The Event attributes for this event. **Returns:** A map containing attribute key-value pairs for the event. ## Related Types ### CatalogObject The `CatalogObject` class represents various items that can be tracked (e.g., a product, a blog post). **Constructor:** ```kotlin @JvmOverloads constructor( type: String, id: String, attributes: Map = mapOf(), relatedCatalogObjects: Map> = mapOf() ) ``` **Parameters:** - `type`: String - A type name representing the catalog object - `id`: String - A unique id representing the catalog object - `attributes`: Map - A map of user-supplied values (optional, defaults to empty map) - `relatedCatalogObjects`: Map> - A map of related catalog objects (optional, defaults to empty map) ## Sibling Event Types Other `CatalogEvent` implementations include: - `ViewCatalogEvent` - Captures when a user views a catalog object - `ViewCatalogDetailEvent` - Captures when a user views catalog object details - `ShareCatalogEvent` - Captures when a user shares a catalog object - `ReviewCatalogEvent` - Captures when a user reviews a catalog object - `CommentCatalogEvent` - Captures when a user comments on a catalog object - `FavoriteCatalogEvent` - Captures when a user favorites a catalog object ## Notes - As a subclass of the sealed `CatalogEvent` class, `QuickViewCatalogEvent` provides type-safe event tracking - The event name returned by `name()` must match the Event Name configured in the Marketing Cloud UI for proper event handling ## See Also - [CatalogEvent](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.events/-catalog-event/index.html) - [EngagementEvent](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.events/-engagement-event/index.html) - [CatalogObject](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.events/-catalog-object/index.html) # React Native Plugin Use the [React Native plugin](https://github.com/salesforce-marketingcloud/react-native-marketingcloudsdk) to integrate the Salesforce Engagement SDK into your iOS and Android apps. **important:** If you're integrating the React Native plugin for the first time, use the [React Native Unified Plugin](https://developer.salesforce.com/docs/marketing/unified_modules/hybrid-frameworks/react-native/unified-react-native-setup.md). If your `package.json` contains the unscoped `react-native-marketingcloudsdk` dependency, your app uses the Engagement-specific React Native plugin. If you're already on the Engagement-specific React Native plugin, use this section to update your configuration or troubleshoot issues. **note:** The SDK supports the existing React Native plugin for Marketing Cloud Engagement. For the most seamless experience, [migrate to the React Native unified plugin](https://developer.salesforce.com/docs/marketing/unified_modules/hybrid-frameworks/react-native/migrate-to-hybrid-react-native-plugin.md). ## Prerequisites Before you install the React Native plugin in your app, upgrade the native MarketingCloudSdk to the latest supported version. If you use MarketingCloudSdk version 7, first upgrade to version 8, and then upgrade to version 9 or later. This sequence upgrade through version 8 preserve in-place migrations, such as schema and preference upgrades. You can upgrade to a specific plugin version by using [npm](https://www.npmjs.com/package/react-native-marketingcloudsdk) or [Yarn](https://yarnpkg.com/package/react-native-marketingcloudsdk). The Engagement-specific React Native plugin has these baseline requirements: | Component | Minimum Requirement | Recommendation | | ------------ | --------------------------------- | ------------------------------------------------------------------------------------------------ | | React Native | 0.60 or later | For React Native 0.85.1 or later with the new architecture, use the React Native unified plugin. | | iOS | See SDK for iOS release notes | Match the deployment target supported by the version of the SDK that you use. | | Android | See SDK for Android release notes | Match the minSdk or compileSdk supported by the version of the SDK that you use. | ## Installation 1. Import the SDK modules into your application. - For iOS apps, import both `SFMCSDK` and `MarketingCloudSDK` into `AppDelegate`. - For Android apps, import `SFMCSdk` into `MainApplication.java`. 2. Add the React Native plugin to your application using [npm](https://www.npmjs.com/package/react-native-marketingcloudsdk) or [Yarn](https://yarnpkg.com/package/react-native-marketingcloudsdk). Use this command to install the plugin by using `npm`: ```bash npm install react-native-marketingcloudsdk --save ``` Alternatively, use this command to install the plugin by using `yarn`: ```bash yarn add react-native-marketingcloudsdk ``` # React Native Plugin API Reference For reference information about the React Native plugin, see the React Native Plugin API Reference (this link opens in a new tab). # React Native Plugin for Engagement API Reference This section provides reference information for the React Native plugin for the MobilePush SDK. It includes information about these methods: - [addTag](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_addTag.md) - [clearAttribute](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_clearAttribute.md) - [disableLogging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_disableLogging.md) - [disablePush](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_disablePush.md) - [enableLogging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_enableLogging.md) - [enablePush](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_enablePush.md) - [getAttributes](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_getAttributes.md) - [getContactKey](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_getContactKey.md) - [getDeviceId](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_getDeviceId.md) - [getSystemToken](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_getSystemToken.md) - [getTags](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_getTags.md) - [isAnalyticsEnabled](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_isAnalyticsEnabled.md) - [isPiAnalyticsEnabled](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_isPiAnalyticsEnabled.md) - [isPushEnabled](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_isPushEnabled.md) - [logSdkState](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_logSdkState.md) - [removeTag](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_removeTag.md) - [setAnalyticsEnabled](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_setAnalyticsEnabled.md) - [setAttribute](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_setAttribute.md) - [setContactKey](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_setContactKey.md) - [setPiAnalyticsEnabled](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_setPiAnalyticsEnabled.md) - [track](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_track.md) # React Native Unified Plugin API Reference For information about APIs in Unified React Native plugin, see the React Native Unified Plugin API Reference. # React Native Unified Plugin API Reference This section contains the API reference information for React Native unified plugin packages in Marketing Cloud Unified Mobile SDK. - [SFMC Core](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmc-core.md) - [Marketing Cloud Engagement SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/marketing-cloud-engagement-sdk.md) - [Marketing Cloud Mobile App Messaging SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/marketing-cloud-mobile-app-messaging-sdk.md) - [Push Messaging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/push-messaging.md) - [In-App Messaging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/in-app-messaging.md) # refreshInbox Refreshes the inbox by fetching the latest messages from the server. ## Syntax ```dart Future refreshInbox() ``` ## Returns - `Future` - Returns `true` if the refresh was successful, `false` otherwise. ## Example ```dart try { bool success = await SfmcSdk.refreshInbox(); if (success) { print('Inbox refreshed successfully'); } else { print('Failed to refresh inbox'); } } catch (e) { print('Error refreshing inbox: $e'); } ``` ## Notes - This method fetches the latest messages from the Marketing Cloud server. - Use this method to ensure you have the most up-to-date inbox content. # Region ## Overview `Region` is a data class in the Salesforce Marketing Cloud Unified SDK that represents a geographic or proximity-based region for location-based messaging. It implements `Parcelable` for Android serialization and `Comparable` for sorting capabilities. **Package:** `com.salesforce.marketingcloud.messages` **Inheritance:** - Implements: `Parcelable`, `Comparable` ## Properties ### center ```kotlin @JvmField val center: LatLon ``` The geographic center point of the region. ### description ```kotlin @JvmField val description: String? ``` Optional description text for the region. ### id ```kotlin @JvmField val id: String ``` Unique identifier for the region. ### major ```kotlin @JvmField val major: Int ``` Major value for beacon-based regions. ### messages ```kotlin @JvmField val messages: List ``` Collection of messages associated with this region. ### minor ```kotlin @JvmField val minor: Int ``` Minor value for beacon-based regions. ### name ```kotlin @JvmField val name: String? ``` Optional display name for the region. ### proximityUuid ```kotlin @JvmField val proximityUuid: String? ``` UUID for proximity beacon identification. ### radius ```kotlin @JvmField val radius: Int ``` The radius distance (in meters) for geofence regions. ### regionType ```kotlin @JvmField val regionType: Int ``` Integer value indicating the type of region (geofence, beacon, etc.). ## Methods ### toJson ```kotlin fun toJson(): JSONObject ``` Serializes the Region object to a JSON representation. **Returns:** `JSONObject` containing the region data. ## Nested Types ### Companion ```kotlin object Companion ``` Companion object for the Region class. # Region **Package:** `com.salesforce.marketingcloud.pushmodels` **Module:** Push Models Module v1.0.2 **SDK:** Salesforce Marketing Cloud Unified SDK 11.0.0 ## Overview `Region` is a data class representing a geographic or beacon region in the Salesforce Marketing Cloud SDK. It provides functionality for managing both geofence regions and proximity beacon regions. ## Declaration ```kotlin data class Region : Parcelable, Comparable ``` ## Inheritance - Implements `Parcelable` - Enables Android inter-component communication - Implements `Comparable` - Allows sorting and comparison operations ## Constructor As a data class, `Region` has a primary constructor with the following parameters: ```kotlin Region( center: LatLon, description: String?, id: String, major: Int, messages: List, minor: Int, name: String?, proximityUuid: String?, radius: Int, regionType: Int ) ``` ## Properties All properties are annotated with `@JvmField` for direct field access from Java: | Property | Type | Description | | --------------- | --------------- | ---------------------------------------------------------------- | | `center` | `LatLon` | The geographic center coordinates of the region | | `description` | `String?` | Optional textual description of the region | | `id` | `String` | Unique identifier for the region | | `major` | `Int` | Major value (typically used for beacon regions) | | `messages` | `List` | Collection of messages associated with this region | | `minor` | `Int` | Minor value (typically used for beacon regions) | | `name` | `String?` | Optional display name for the region | | `proximityUuid` | `String?` | Optional UUID for proximity beacons | | `radius` | `Int` | The radius of the region (in meters for geofences) | | `regionType` | `Int` | Numeric type identifier for the region (see Companion constants) | ## Methods ### toJson ```kotlin fun toJson(): JSONObject ``` Converts the Region object to its JSON representation. **Returns:** `JSONObject` containing the region data ## Companion Object The `Region.Companion` object provides constants and factory methods for working with Region instances. ### Constants #### REGION_TYPE_FENCE ```kotlin const val REGION_TYPE_FENCE: Int = 1 ``` Constant representing a fence-type region (geofence). #### REGION_TYPE_PROXIMITY ```kotlin const val REGION_TYPE_PROXIMITY: Int = 3 ``` Constant representing a proximity-type region (beacon). ### Factory Methods #### fromJson ```kotlin @JvmStatic fun fromJson(jsonObject: JSONObject?): Region? ``` Creates a Region object from a JSONObject. **Parameters:** - `jsonObject` - A nullable `JSONObject` containing region data **Returns:** A nullable `Region` instance, or `null` if creation fails **Annotations:** `@JvmStatic` - Makes this function accessible as a static method from Java ## Usage Example ```kotlin // Creating a geofence region val geofenceRegion = Region( center = LatLon(latitude = 37.7749, longitude = -122.4194), description = "San Francisco Office", id = "sf-office-001", major = 0, messages = emptyList(), minor = 0, name = "SF Office", proximityUuid = null, radius = 100, regionType = Region.REGION_TYPE_FENCE ) // Creating a beacon region val beaconRegion = Region( center = LatLon(latitude = 37.7749, longitude = -122.4194), description = "Store Entrance Beacon", id = "beacon-001", major = 1, messages = emptyList(), minor = 2, name = "Entrance", proximityUuid = "12345678-1234-1234-1234-123456789012", radius = 0, regionType = Region.REGION_TYPE_PROXIMITY ) // Converting to JSON val jsonObject = geofenceRegion.toJson() // Creating from JSON val region = Region.fromJson(jsonObject) ``` ## Related Classes - `LatLon` - Represents geographic coordinates (latitude/longitude) - `Message` - Represents messages associated with a region # RegionMessageManager **Package:** `com.salesforce.marketingcloud.messages` **Type:** Interface ## Description An interface for managing region-based messaging (geofence and proximity) in the Salesforce Marketing Cloud SDK. This interface provides methods to enable/disable geofence and proximity messaging, check their status, and register/unregister listeners for message responses and region transition events. ## Nested Types ### GeofenceMessageResponseListener ```kotlin interface GeofenceMessageResponseListener ``` Interface for listening to geofence message response events. ### ProximityMessageResponseListener ```kotlin interface ProximityMessageResponseListener ``` Interface for listening to proximity message response events. ### RegionTransitionEventListener ```kotlin interface RegionTransitionEventListener ``` Interface to use to listen for region (Geofence/Proximity) transition (enter/exit) events. ## Methods ### Geofence Messaging Methods #### enableGeofenceMessaging ```kotlin @RequiresPermission( allOf = [ Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION ] ) abstract fun enableGeofenceMessaging(): Boolean ``` Enables geofence messaging. **Returns:** `Boolean` - `true` if geofence messaging was successfully enabled, `false` otherwise. **Required Permissions:** - `Manifest.permission.ACCESS_FINE_LOCATION` - `Manifest.permission.ACCESS_BACKGROUND_LOCATION` #### disableGeofenceMessaging ```kotlin abstract fun disableGeofenceMessaging() ``` Disables geofence messaging. #### isGeofenceMessagingEnabled ```kotlin abstract fun isGeofenceMessagingEnabled(): Boolean ``` Indicates whether geofence messaging is enabled. **Returns:** `Boolean` - `true` if geofence messaging is enabled, `false` otherwise. ### Proximity Messaging Methods #### enableProximityMessaging ```kotlin @RequiresPermission( allOf = [ Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_BACKGROUND_LOCATION ] ) abstract fun enableProximityMessaging(): Boolean ``` Enables proximity messaging. **Returns:** `Boolean` - `true` if proximity messaging was successfully enabled, `false` otherwise. **Required Permissions:** - `Manifest.permission.ACCESS_FINE_LOCATION` - `Manifest.permission.ACCESS_BACKGROUND_LOCATION` #### disableProximityMessaging ```kotlin abstract fun disableProximityMessaging() ``` Disables proximity messaging. #### isProximityMessagingEnabled ```kotlin abstract fun isProximityMessagingEnabled(): Boolean ``` Indicates whether proximity messaging is enabled. **Returns:** `Boolean` - `true` if proximity messaging is enabled, `false` otherwise. ### Listener Registration Methods #### registerGeofenceMessageResponseListener ```kotlin abstract fun registerGeofenceMessageResponseListener( @NonNull listener: RegionMessageManager.GeofenceMessageResponseListener ) ``` Registers the provided listener for geofence message response events. **Parameters:** - `listener` - The `GeofenceMessageResponseListener` to register (must not be null) #### unregisterGeofenceMessageResponseListener ```kotlin abstract fun unregisterGeofenceMessageResponseListener( @NonNull listener: RegionMessageManager.GeofenceMessageResponseListener ) ``` Unregisters the provided listener for geofence message response events. **Parameters:** - `listener` - The `GeofenceMessageResponseListener` to unregister (must not be null) #### registerProximityMessageResponseListener ```kotlin abstract fun registerProximityMessageResponseListener( @NonNull listener: RegionMessageManager.ProximityMessageResponseListener ) ``` Registers the provided listener for proximity message response events. **Parameters:** - `listener` - The `ProximityMessageResponseListener` to register (must not be null) #### unregisterProximityMessageResponseListener ```kotlin abstract fun unregisterProximityMessageResponseListener( @NonNull listener: RegionMessageManager.ProximityMessageResponseListener ) ``` Unregisters the provided listener for proximity message response events. **Parameters:** - `listener` - The `ProximityMessageResponseListener` to unregister (must not be null) #### registerRegionTransitionEventListener ```kotlin abstract fun registerRegionTransitionEventListener( @NonNull listener: RegionMessageManager.RegionTransitionEventListener ) ``` Registers the provided listener for region transition events. **Parameters:** - `listener` - The `RegionTransitionEventListener` to register (must not be null) #### unregisterRegionTransitionEventListener ```kotlin abstract fun unregisterRegionTransitionEventListener( @NonNull listener: RegionMessageManager.RegionTransitionEventListener ) ``` Unregisters the provided listener for region transition events. **Parameters:** - `listener` - The `RegionTransitionEventListener` to unregister (must not be null) # Register Contacts and Devices To register contacts and devices with Marketing Cloud Engagement, work with your marketing team to determine your contact key strategy, configure attributes and tags, and set all required registration fields. ## Prerequisites Before you begin, configure the SDK and initialize it. See [Use the SDK with Marketing Cloud Engagement](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement.md). ## Contact Key Strategy The contact key is a unique identifier that represents an individual in Marketing Cloud. Your contact key strategy influences how you implement registration and determines whether you can send messages to anonymous users, known users, or both. - [Determine Your Contact Key Strategy](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_register_contacts_devices_determine_key_strategy.md) — Understand contact key options and their implications for messaging - [Set the Contact Key](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_register_contacts_devices_set_contact_key.md) — Configure the contact key in your app using the SDK ## Attributes and Tags Use attributes and tags to segment your audience and personalize messages. Attributes are key-value pairs for demographic data, while tags are categories that let users express interests or preferences. - [Set Contact Attributes and Tags](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_register_contacts_devices_attributes_tags.md) — Overview of attributes and tags, including how to create custom attributes and manage both - [Set or Clear Attributes](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_register_contacts_devices_attributes_manage.md) — Manage attribute key-value pairs using the SDK - [Manage Tags](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_register_contacts_devices_tags_manage.md) — Add or remove tags using the SDK ## Contact Dissociation When a user changes their contact key or multiple users share a device, contacts can become dissociated from devices. Understanding and managing this behavior helps maintain accurate contact records. - [Contact Dissociation](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_register_contacts_devices_contact_dissociation.md) — Understand why contacts become dissociated and how to minimize it - [Delay Registrations Until Contact Key is Set (Android)](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_register_contacts_devices_contact_dissociation_delay_android.md) — Configure Android apps to delay registration - [Delay Registrations Until Contact Key is Set (iOS)](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_register_contacts_devices_contact_dissociation_delay_ios.md) — Configure iOS apps to delay registration ## Registration Validation After implementing registration, verify that all required fields are properly set and that Marketing Cloud successfully processes the registration. - [Check Required Registration Fields](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_register_contacts_devices_check_fields.md) — Understand required fields and validate registration data # Register Contacts in Android Apps that use SDK Version 10 The process of registering contacts by setting the value of the Contact Key has been updated in version 10 of the SDK. To upgrade your app to version 10 of the SDK, first [update the initialization code](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v10.md) -->. Then, use this code example to update the contact registration code in your app. ```kotlin SFMCSdk.requestSdk { sfmcSdk - > // Set contact key/profileId for all modules sfmcSdk.identity.edit { profileId = "uniquelyIdentifyingKey" } // Retrieve the contact key val profileId = sfmcSdk.identity.profileId } ``` # Register Contacts in iOS Apps that use SDK Version 10 The process of registering contacts by setting the value of the Contact Key has been updated in version 10 of the SDK. To upgrade your app to version 10 of the SDK, first [update the initialization code](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v10.md). Then, use this code example to update the contact registration code in your app. ```swift // Set contact key for mobile push module SFMCSdk.identity.edit { [self] model in model.profileId = "user@example.com" return model } // Retrieve the contact key SFMCSdk.identity.get()?.profileId ``` # registerInboxResponseListener Registers a callback function to listen for inbox response events. ## Syntax ```dart void registerInboxResponseListener(Function callback) ``` ## Parameters - `callback` (Function) - The callback function to be called when inbox events occur ## Returns - `void` - No return value ## Example ```dart void onInboxResponse(dynamic response) { print('Inbox response received: $response'); } SfmcSdk.registerInboxResponseListener(onInboxResponse); ``` ## Notes - The callback function will be invoked when inbox-related events occur. - Make sure to unregister the listener when it's no longer needed to prevent memory leaks. ## Related Methods - [unregisterInboxResponseListener()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_unregisterInboxResponseListener.md) # Registration **Package:** `com.salesforce.marketingcloud.mobileappmessaging.registration` **SDK Version:** 11.0.0 ## Description A data class representing a device registration record for the Salesforce Marketing Cloud Mobile App Messaging SDK. Contains device information, app details, user attributes, and a lazily calculated hash value. ## Declaration ```kotlin data class Registration ``` ## Parameters | Parameter | Type | Description | | --------------------------- | ------------------- | ------------------------------------------------- | | `eventId` | String | Unique identifier for this registration event | | `registrationId` | String | Unique identifier for the registration session | | `deviceId` | String | Unique device identifier | | `dateTimeInDevice` | String | Timestamp when registration was created on device | | `deviceSystemToken` | String? | Push notification token for the device | | `pushEnabled` | Boolean | Whether push notifications are enabled | | `deviceTimeZone` | String | Device's timezone | | `deviceModel` | String? | Device model information | | `devicePlatform` | String | Device platform (e.g., "Android", "iOS") | | `deviceVersion` | String? | Device OS version | | `sdkVersion` | String? | Marketing Cloud SDK version | | `mobileAppId` | String | Application identifier | | `mobileAppName` | String? | Human-readable application name | | `mobileAppVersion` | String? | Application version | | `locale` | String | Device locale setting | | `attributes` | Map | Custom key-value attributes for the user/device | | `partyIdentificationNumber` | String? | User's party identification number | | `partyIdentificationType` | String? | Type of party identification | | `partyIdentificationName` | String? | User's party identification name | ## Properties ### attributes ```kotlin val attributes: Map ``` ### dateTimeInDevice ```kotlin val dateTimeInDevice: String ``` ### deviceId ```kotlin val deviceId: String ``` ### deviceModel ```kotlin val deviceModel: String? ``` ### devicePlatform ```kotlin val devicePlatform: String ``` ### deviceSystemToken ```kotlin val deviceSystemToken: String? ``` ### deviceTimeZone ```kotlin val deviceTimeZone: String ``` ### deviceVersion ```kotlin val deviceVersion: String? ``` ### locale ```kotlin val locale: String ``` ### mobileAppId ```kotlin val mobileAppId: String ``` ### mobileAppName ```kotlin val mobileAppName: String? ``` ### mobileAppVersion ```kotlin val mobileAppVersion: String? ``` ### partyIdentificationName ```kotlin val partyIdentificationName: String? ``` ### partyIdentificationNumber ```kotlin val partyIdentificationNumber: String? ``` ### partyIdentificationType ```kotlin val partyIdentificationType: String? ``` ### pushEnabled ```kotlin val pushEnabled: Boolean ``` ### sdkVersion ```kotlin val sdkVersion: String? ``` ## Nested Types ### Companion ```kotlin object Companion ``` ## Platform - **Target:** androidJvm # Registration Class ## Package `com.salesforce.marketingcloud.registration` ## Class Definition ```kotlin data class Registration ``` A data class representing device registration information for the Salesforce Marketing Cloud SDK. ## Properties ### appId ```kotlin @JvmField val appId: String ``` The application identifier. ### appVersion ```kotlin @JvmField val appVersion: String ``` The version of the application. ### attributes ```kotlin @JvmField val attributes: Map ``` A map of custom attributes associated with the registration. ### contactKey ```kotlin @JvmField val contactKey: String? ``` The contact key identifier (nullable). ### deviceId ```kotlin @JvmField val deviceId: String ``` The unique device identifier. ### dst ```kotlin @JvmField val dst: Boolean ``` Daylight saving time indicator. ### hwid ```kotlin @JvmField val hwid: String ``` Hardware identifier. ### locale ```kotlin @JvmField val locale: String ``` The device locale setting. ### locationEnabled ```kotlin @JvmField val locationEnabled: Boolean ``` Indicates whether location services are enabled. ### platform ```kotlin @JvmField val platform: String ``` The platform name (e.g., Android). ### platformVersion ```kotlin @JvmField val platformVersion: String ``` The version of the platform/OS. ### proximityEnabled ```kotlin @JvmField val proximityEnabled: Boolean ``` Indicates whether proximity features are enabled. ### pushEnabled ```kotlin @JvmField val pushEnabled: Boolean ``` Indicates whether push notifications are enabled. ### sdkVersion ```kotlin @JvmField val sdkVersion: String ``` The version of the Marketing Cloud SDK. ### signedString ```kotlin @JvmField val signedString: String? ``` A signed string for authentication (nullable). ### systemToken ```kotlin @JvmField val systemToken: String? ``` The system token for push notifications (nullable). ### tags ```kotlin @JvmField val tags: Set ``` A set of tags associated with the registration. ### timeZone ```kotlin @JvmField val timeZone: Int ``` The time zone offset in minutes. ## Methods Each property has a corresponding getter method with the same name: ### appId() ```kotlin fun appId(): String ``` Returns the application identifier. ### appVersion() ```kotlin fun appVersion(): String ``` Returns the application version. ### attributes() ```kotlin fun attributes(): Map ``` Returns the attributes map. ### contactKey() ```kotlin fun contactKey(): String? ``` Returns the contact key (nullable). ### deviceId() ```kotlin fun deviceId(): String ``` Returns the device identifier. ### dst() ```kotlin fun dst(): Boolean ``` Returns the daylight saving time status. ### hwid() ```kotlin fun hwid(): String ``` Returns the hardware identifier. ### locale() ```kotlin fun locale(): String ``` Returns the locale. ### locationEnabled() ```kotlin fun locationEnabled(): Boolean ``` Returns the location enabled status. ### platform() ```kotlin fun platform(): String ``` Returns the platform name. ### platformVersion() ```kotlin fun platformVersion(): String ``` Returns the platform version. ### proximityEnabled() ```kotlin fun proximityEnabled(): Boolean ``` Returns the proximity enabled status. ### pushEnabled() ```kotlin fun pushEnabled(): Boolean ``` Returns the push enabled status. ### sdkVersion() ```kotlin fun sdkVersion(): String ``` Returns the SDK version. ### signedString() ```kotlin fun signedString(): String? ``` Returns the signed string (nullable). ### systemToken() ```kotlin fun systemToken(): String? ``` Returns the system token (nullable). ### tags() ```kotlin fun tags(): Set ``` Returns the set of tags. ### timeZone() ```kotlin fun timeZone(): Int ``` Returns the time zone offset. ## Platform Target - **androidJvm** - This class is available for Android/JVM targets only. # RegistrationManager ## Overview ```kotlin interface RegistrationManager ``` The RegistrationManager interface provides methods for managing SDK registration, including contact keys, attributes, tags, and push notification settings in the Salesforce Marketing Cloud SDK. ## Nested Types ### Editor ```kotlin interface Editor ``` This class handles the setting of customer configurable values in the SDK. ### RegistrationEventListener ```kotlin interface RegistrationEventListener ``` Interface for receiving registration-related events. ## Methods ### edit ```kotlin @NonNull abstract fun edit(): RegistrationManager.Editor ``` Returns an instance of Editor which can be used to update the SDK's configurable values including contact key, attributes, and tags. **Returns:** An Editor instance for modifying registration values --- ### getAttributes ```kotlin @NonNull abstract fun getAttributes(): Map ``` Getter for attributes map. **Returns:** Map of attribute key-value pairs --- ### getContactKey ```kotlin @Nullable abstract fun getContactKey(): String ``` Getter for contactKey, formerly known as SubscriberKey in the SDK. **Returns:** The current contact key, or null if not set --- ### getDeviceId ```kotlin @NonNull abstract fun getDeviceId(): String ``` Getter for the running device's unique identifier. **Returns:** The device's unique identifier --- ### getSignedString ```kotlin @Nullable abstract fun getSignedString(): String ``` Getter for 'Signed String' **Returns:** The signed string value, or null if not available --- ### getSystemToken ```kotlin @Nullable abstract fun getSystemToken(): String ``` Getter for Google's Push Notification Token **Returns:** The push notification token, or null if not available --- ### getTags ```kotlin @NonNull abstract fun getTags(): Set ``` Getter for tags **Returns:** Set of tags associated with the registration --- ### isPushEnabled ```kotlin abstract fun isPushEnabled(): Boolean ``` Checks if push notifications are currently enabled for this device. **Returns:** true if push is enabled, false otherwise --- ### registerForRegistrationEvents ```kotlin abstract fun registerForRegistrationEvents(@NonNull listener: RegistrationManager.RegistrationEventListener) ``` Register a registrationEventListener that will be notified when Registration related events happen. **Parameters:** - `listener` - The RegistrationEventListener to register --- ### unregisterForRegistrationEvents ```kotlin abstract fun unregisterForRegistrationEvents(@NonNull listener: RegistrationManager.RegistrationEventListener) ``` Unregister a registrationEventListener **Parameters:** - `listener` - The RegistrationEventListener to unregister # RegistrationManager **Package:** `com.salesforce.marketingcloud.mobileappmessaging.registration` **Platform:** androidJvm **SDK Version:** 11.0.0 ## Overview ```kotlin interface RegistrationManager ``` An interface that manages device registration data within the MobileAppMessaging module. This interface provides access to device registration details, party identification information, and event notifications for registration updates. It serves as the primary API for registration-related operations. --- ## Nested Types ### RegistrationEventListener ```kotlin fun interface RegistrationEventListener ``` A functional interface for listening to registration events. --- ## Functions ### getDeviceId ```kotlin abstract fun getDeviceId(): String ``` Retrieves the device identifier. **Returns:** A `String` containing the device ID. --- ### registerForRegistrationEvents ```kotlin abstract fun registerForRegistrationEvents( listener: RegistrationManager.RegistrationEventListener ) ``` Registers a listener to receive registration update events. **Parameters:** - `listener` - The `RegistrationEventListener` to register for receiving events. --- ### unregisterForRegistrationEvents ```kotlin abstract fun unregisterForRegistrationEvents( listener: RegistrationManager.RegistrationEventListener ) ``` Removes a previously registered listener. **Parameters:** - `listener` - The `RegistrationEventListener` to unregister from receiving events. # RemoveFromCartEvent `Class` ## Package `com.salesforce.marketingcloud.sfmcsdk.components.events` ## Description An E-commerce event for when a user removes an item from their shopping cart. ## Platform - **Target:** androidJvm (Android/JVM) - **SDK Version:** 11.0.0 - **Module:** SFMC SDK v3.1.0 ## Declaration ```kotlin class RemoveFromCartEvent : CartEvent ``` ## Inheritance Hierarchy ``` Event (interface) └── EngagementEvent (sealed class) └── CartEvent (sealed class) └── RemoveFromCartEvent (class) ``` ## Overview `RemoveFromCartEvent` is part of the Salesforce Marketing Cloud Unified SDK's event tracking system for e-commerce applications. This event should be tracked when a user removes one or more items from their shopping cart. The event extends `CartEvent` and inherits all cart-related event functionality. ## Properties ### Inherited from CartEvent #### lineItems ```kotlin val lineItems: List ``` A list of line items representing the items being removed from the cart. Each line item describes a purchasable catalog object with quantity and optional pricing information. ### Inherited from EngagementEvent #### category ```kotlin open override var category: Event.Category ``` The Event category name. Contains a list of allowed values that classify the event type. #### priority ```kotlin open override val priority: Priority ``` Defines the priority level of the event for processing and handling by the SDK. ## Methods ### Inherited from EngagementEvent #### attributes() ```kotlin open override fun attributes(): Map ``` Returns the event attributes as a map of key-value pairs associated with this event. **Returns:** `Map` - A map containing the event attributes --- #### name() ```kotlin open override fun name(): String ``` Returns the name for the event. This value must match the Event Name used when creating the event in the Marketing Cloud UI for any action to result from tracking this event. **Returns:** `String` - The event name ## Related Classes ### LineItem Line items describe purchasable items for Cart and Order events. ```kotlin data class LineItem @JvmOverloads constructor( val catalogObjectType: String, val catalogObjectId: String, val quantity: Int, var price: Double? = null, var currency: String? = null, var attributes: Map = mapOf() ) ``` #### LineItem Parameters | Parameter | Type | Required | Default | Description | | ------------------- | ---------------- | -------- | ------- | --------------------------------------------------- | | `catalogObjectType` | String | Yes | - | Type name for the referenced catalog object | | `catalogObjectId` | String | Yes | - | Unique identifier for the referenced catalog object | | `quantity` | Int | Yes | - | Number of catalog objects in the line item | | `price` | Double? | No | null | Price of the referenced catalog object | | `currency` | String? | No | null | Currency code for the price field | | `attributes` | Map | No | mapOf() | User-supplied key-value pairs | ## Usage To track when items are removed from a cart, create a `RemoveFromCartEvent` with the appropriate line items and track it using the SDK's event tracking system. ### Example ```kotlin // Create line items for products being removed val lineItem1 = LineItem( catalogObjectType = "Product", catalogObjectId = "product_123", quantity = 1, price = 29.99, currency = "USD" ) val lineItem2 = LineItem( catalogObjectType = "Product", catalogObjectId = "product_456", quantity = 2, price = 15.50, currency = "USD" ) // Create the remove from cart event val removeEvent = RemoveFromCartEvent(listOf(lineItem1, lineItem2)) // Track the event through the SDK SFMCSdk.track(removeEvent) ``` ## Related Events - **`AddToCartEvent`** - E-commerce event for when a user adds an item to their shopping cart - **`ReplaceCartEvent`** - E-commerce event for when a user replaces their shopping cart with a list of items ## See Also - [CartEvent](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.events/-cart-event/index.html) - Parent sealed class for cart-related events - [EngagementEvent](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.events/-engagement-event/index.html) - Base sealed class for engagement events - [Events Package](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.events/index.html) - Complete events package documentation ## Notes - The event name must match the configuration in the Marketing Cloud UI to trigger associated actions - Line items support custom attributes for additional metadata - All cart events inherit from the sealed `CartEvent` class, ensuring type safety at compile time - Events are processed according to their priority level # removeTag Remove a tag from the device's registration. ## Syntax `MCCordovaPlugin.removeTag(tag, [successCallback], [errorCallback])` ## Kind Static method of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | ----------------------- | ---------- | ------------------------------------------------------------------------ | | `tag` | `string` | The tag to be removed from the list of tags in the registration. | | `successCallback` | `function` | | | `successCallback.saved` | `boolean` | Whether the value passed in for `tag` was cleared from the registration. | | `errorCallback` | `function` | | # removeTag Removes a tag from the device. ## Syntax ```dart Future removeTag(String tag) ``` ## Parameters - `tag` (String) - The tag to remove ## Returns - `Future` - Completes when the tag has been removed. ## Example ```dart try { await SfmcSdk.removeTag('premium_user'); print('Tag removed successfully'); } catch (e) { print('Failed to remove tag: $e'); } ``` ## Related Methods - [addTag()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_addTag.md) - [getTags()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getTags.md) # removeTag Removes a tag from the list of tags in the registration. ## Syntax ```javascript MCReactModule.removeTag(tag); ``` ## Parameters | Parameter | Type | Description | | --------- | -------- | ------------------------------------------------------------ | | `tag` | `string` | The tag to remove from the list of tags in the registration. | ## Returns - `void` - No return value. ## Example ```javascript import { MCReactModule } from "react-native-marketingcloudsdk"; const removeUserTag = () => { try { MCReactModule.removeTag("premium_user"); console.log("Tag removed successfully"); } catch (error) { console.error("Error removing tag:", error); } }; ``` ## See Also - [addTag() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_addTag.md) - [getTags() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_getTags.md) - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/MarketingCloudSdk/8.0/-marketing%20-cloud%20-s-d-k/com.salesforce.marketingcloud.registration/-registration-manager/-editor/remove-tag.html) - _SDK Reference for iOS_: [removeTag() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/ios-sdk-v11/mce-sdk/classes/marketingcloudsdk.md#removetag_) # ReplaceCartEvent ## Package `com.salesforce.marketingcloud.sfmcsdk.components.events` ## Overview ```kotlin class ReplaceCartEvent : CartEvent ``` An E-commerce event for when a user replaces their shopping cart with a list of items. ## Platform - **Target Platform:** androidJvm - **SDK Version:** 11.0.0 - **Available Since:** 10.0.0 ## Description The `ReplaceCartEvent` class represents a complete replacement of a user's shopping cart contents. This event is triggered when the entire cart is replaced with a new set of items, as opposed to incrementally adding or removing individual items (which would use `AddToCartEvent` or `RemoveFromCartEvent` respectively). ## Inheritance Hierarchy ``` Event (abstract) └── EngagementEvent (sealed) └── CartEvent (sealed) └── ReplaceCartEvent ``` ## Related Classes ### Parent: CartEvent `ReplaceCartEvent` extends the sealed class `CartEvent`, which provides cart-specific functionality for engagement events. ### Sibling Classes - **AddToCartEvent** - Event for adding items to the cart - **RemoveFromCartEvent** - Event for removing items from the cart ## Inherited Properties ### From CartEvent #### lineItems ```kotlin val lineItems: List ``` A list of line items associated with the cart event. Each `LineItem` represents a product or catalog object being replaced in the cart. ### From EngagementEvent #### category ```kotlin open override var category: Event.Category ``` The Event category Name. Category contains list of allowed values. #### priority ```kotlin open override val priority: Priority ``` Defines the priority level for this engagement event. ## Inherited Methods ### From EngagementEvent #### attributes() ```kotlin open override fun attributes(): Map ``` **Returns:** A map containing key-value pairs of event attributes. **Description:** The Event attributes for this event. #### name() ```kotlin open override fun name(): String ``` **Returns:** The event name as a String. **Description:** The name for the event. This value must match the Event Name used when creating the event in the Marketing Cloud UI for any action to result from tracking this event. ## Associated Types ### LineItem The `lineItems` property uses the `LineItem` data class to represent individual products in the cart. ```kotlin data class LineItem @JvmOverloads constructor( catalogObjectType: String, catalogObjectId: String, quantity: Int, price: Double? = null, currency: String? = null, attributes: Map = mapOf() ) ``` #### LineItem Properties | Property | Type | Description | Mutable | | ------------------- | ------------------ | ------------------------------------------------------------------------------- | ------- | | `catalogObjectType` | `String` | A type name representing the catalog object referenced in the line item | No | | `catalogObjectId` | `String` | A unique identifier representing the catalog object referenced in the line item | No | | `quantity` | `Int` | The number of catalog objects in this line item | No | | `price` | `Double?` | The price of the catalog object referenced in the line item (nullable) | Yes | | `currency` | `String?` | The currency for the price field (nullable) | Yes | | `attributes` | `Map` | A map of user-supplied values | Yes | ## Usage Notes - As `ReplaceCartEvent` extends the sealed class `CartEvent`, it can only be instantiated directly using its constructor - The event name returned by the `name()` method must correspond to event configurations in the Marketing Cloud UI to trigger associated actions - `ReplaceCartEvent` is part of the engagement tracking system and integrates with Salesforce Marketing Cloud for e-commerce analytics - When creating a `ReplaceCartEvent`, you must provide a list of `LineItem` objects representing the complete new contents of the cart # Request Runtime Notification Permission on Android Android 13 and later require a runtime permission to display notifications. This change impacts all applications that run on Android 13 or later. Your app can’t display notifications until the user grants this permission. For more information, see _Android Developers_: [Request runtime permissions](https://developer.android.com/training/permissions/requesting). After the user accepts the request to display notifications, notify the SDK by using this code. ```js SFMCSdk.requestSdk { sdk -> sdk.mp { it.pushMessageManager.enablePush() } } ``` # Request Runtime Notification Permission on Android Android 13 and later require a specific runtime permission to display notifications. Your app can’t display notifications until the user grants this permission. For more information, see Request runtime permissions on the Android Developers website. To notify the SDK that the user accepted the request to display notifications, use this code. ```java PushFeature.requestSdk { pushFeature -> pushFeature.getPushMessageManager().enablePush() } ``` # Required Methods for Button Actions Marketers can configure the action that occurs when an end user taps a button on an in-app message. The SDK handles actions for `Notification Settings` and `Location Settings`, while actions for `Web URL` and `App URL` require that you implement [`UrlHandler`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/common/com.salesforce.marketingcloud/-url-handler/index.html) as a new SDK initialization method. These examples show how to configure the SDK to handle button clicks in in-app messages. ::::::tabset{tabs='["SDK v11", "SDK v10", "SDK v8", "SDK v7"]'} :::::tab ```java SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { inAppMessagingFeatureModuleConfig = InAppMessagingFeatureConfig.builder().apply { // Other configuration options // Tell the SDK how to handle button clicks in an In-App Message setUrlHandler { context, url, _ -> getActivity( context, Random().nextInt(), Intent(Intent.ACTION_VIEW, url.toUri()), PendingIntent.FLAG_UPDATE_CURRENT ) } }.build() }) { // TODO handle initialization status } ``` ::::: :::::tab ```java SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { engagementModuleConfig = MarketingCloudConfig.builder().apply { // Other configuration options // Tell the SDK how to handle button clicks in an In-App Message setUrlHandler(UrlHandler { context, url, _ -> PendingIntent.getActivity( context, Random().nextInt(), Intent(Intent.ACTION_VIEW, url.toUri()), PendingIntent.FLAG_UPDATE_CURRENT ) }) }.build(applicationContext) }) { // TODO handle initialization status } ``` ::::: :::::tab ```java SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { pushModuleConfig = MarketingCloudConfig.builder().apply { setApplicationId("{mc_application_id}") setAccessToken("{mc_access_token}") setSenderId("{fcm_sender_id}") setMarketingCloudServerUrl("{marketing_cloud_url}") setMid("{mid}") setNotificationCustomizationOptions("{your instance of NotificationCustomizationOptions}") // Tell the SDK how to handle button clicks in an In-App Message setUrlHandler(UrlHandler { context, url, _ -> PendingIntent.getActivity( context, Random().nextInt(), Intent(Intent.ACTION_VIEW, Uri.parse(url)), PendingIntent.FLAG_UPDATE_CURRENT ) }) // Other configuration options }.build(applicationContext) }) { // TODO handle initialization status } ``` ::::: :::::tab ```java MarketingCloudSdk.init(applicationContext as Application, MarketingCloudConfig.builder().apply { setApplicationId("{mc_application_id}") setAccessToken("{mc_access_token}") setSenderId("{fcm_sender_id}") setMarketingCloudServerUrl("{marketing_cloud_url}") setMid("{mid}") setNotificationCustomizationOptions("{your instance of NotificationCustomizationOptions}") // Tell the SDK how to handle button clicks in an In-App Message setUrlHandler(UrlHandler { context, url, _ -> PendingIntent.getActivity( context, Random().nextInt(), Intent(Intent.ACTION_VIEW, Uri.parse(url)), PendingIntent.FLAG_UPDATE_CURRENT ) }) // Other configuration options }.build(applicationContext)) { // TODO handle initialization status } ``` ::::: :::::: # ReturnOrderEvent ## Package `com.salesforce.marketingcloud.sfmcsdk.components.events` ## Overview An E-commerce event to manage details of returning an order. ## Declaration ```kotlin class ReturnOrderEvent : OrderEvent ``` ## Platform - **Target:** androidJvm - **SDK Version:** SFMC SDK v3.1.0 - **API Documentation Version:** 11.0.0 ## Inheritance Hierarchy ``` Event └── EngagementEvent └── OrderEvent (sealed class) └── ReturnOrderEvent ``` ## Class Information `ReturnOrderEvent` is a concrete implementation of the sealed class `OrderEvent`. It inherits all properties and methods from its parent classes without adding additional members. ### Related Order Event Types The `OrderEvent` sealed class has the following inheritors: - `PurchaseOrderEvent` - `PreorderEvent` - `CancelOrderEvent` - `ShipOrderEvent` - `DeliverOrderEvent` - `ReturnOrderEvent` - `ExchangeOrderEvent` ## Inherited Properties ### From OrderEvent #### order ```kotlin val order: Order ``` The order data containing details about the order being returned. ### From EngagementEvent #### category ```kotlin open override var category: Event.Category ``` The Event category name. Category contains list of allowed values. #### priority ```kotlin open override val priority: Priority ``` The priority level of the event. ## Inherited Methods ### From EngagementEvent #### attributes() ```kotlin open override fun attributes(): Map ``` Returns the Event attributes for this event. **Returns:** A map containing event attributes. #### name() ```kotlin open override fun name(): String ``` Returns the name for the event. This value must match the Event Name used when creating the event in the Marketing Cloud UI for any action to result from tracking this event. **Returns:** The event name as a String. ## Order Data Class The `order` property uses the `Order` data class, which has the following structure: ### Declaration ```kotlin data class Order @JvmOverloads constructor( val id: String, val lineItems: List = listOf(), val totalValue: Double? = null, val currency: String? = null, val attributes: Map = mapOf() ) ``` ### Constructor Parameters | Parameter | Type | Default | Description | | ------------ | ------------------ | ---------- | ---------------------------------------------- | | `id` | `String` | required | A unique identifier representing the order. | | `lineItems` | `List` | `listOf()` | A list of Line Item Data values. | | `totalValue` | `Double?` | `null` | The total value of the order. | | `currency` | `String?` | `null` | The currency of the total value for the order. | | `attributes` | `Map` | `mapOf()` | A map of user-supplied values. | ### Properties #### id ```kotlin val id: String ``` A unique identifier representing the order. #### lineItems ```kotlin val lineItems: List ``` An list of Line Item Data values. #### totalValue ```kotlin val totalValue: Double? ``` The total value of the order. #### currency ```kotlin val currency: String? ``` The currency of the total value for the order. #### attributes ```kotlin val attributes: Map ``` A map of user-supplied values. ## Usage Example ```kotlin // Create an order with return details val returnOrder = Order( id = "ORDER-12345", lineItems = listOf( LineItem( catalogObjectType = "product", catalogObjectId = "PROD-789", quantity = 1, price = 49.99 ) ), totalValue = 49.99, currency = "USD", attributes = mapOf( "returnReason" to "Defective", "refundMethod" to "Original payment method" ) ) // Create a ReturnOrderEvent val returnEvent = ReturnOrderEvent() // Note: The actual constructor/initialization method would be // implementation-specific based on the parent OrderEvent class ``` ## Notes - `ReturnOrderEvent` is used specifically for tracking when customers return orders. - This event should be tracked when an order return is processed in your e-commerce system. - The event name configured in this event must match the Event Name defined in the Marketing Cloud UI to trigger any associated actions or automations. - The `@JvmOverloads` annotation on the Order constructor provides multiple constructor variants for Java interoperability. ## See Also - `OrderEvent` - The parent sealed class - `EngagementEvent` - The grandparent sealed class - `Event` - The root event interface - `LineItem` - Used to represent individual items in the order - `Order` - The data class containing order information # ReviewCatalogEvent **Package:** `com.salesforce.marketingcloud.sfmcsdk.components.events` **SDK Version:** 11.0.0 (SFMC SDK v3.1.0) **Platform:** androidJvm ## Overview ```kotlin class ReviewCatalogEvent : CatalogEvent ``` An event class used to capture when a user reviews a catalog object within the Salesforce Marketing Cloud ecosystem. ## Inheritance Hierarchy ``` Event (interface) ↳ EngagementEvent (sealed class) ↳ CatalogEvent (sealed class) ↳ ReviewCatalogEvent (class) ``` ## Description `ReviewCatalogEvent` extends `CatalogEvent` and is specifically designed to track user review interactions with catalog objects. This event is part of the SFMC SDK's comprehensive event tracking system for catalog-related user actions. ## Inherited Properties ### From CatalogEvent #### catalogObject ```kotlin val catalogObject: CatalogObject ``` Represents the catalog object associated with this event. ### From EngagementEvent #### category ```kotlin open override val category: Event.Category ``` The Event category Name. Category contains list of allowed values. #### priority ```kotlin open override val priority: Priority ``` Read-only property indicating the priority of the event. ## Inherited Methods ### From EngagementEvent #### attributes() ```kotlin fun attributes(): Map ``` Returns the Event attributes for this event. **Returns:** `Map` - A map containing event attributes #### name() ```kotlin fun name(): String ``` Returns the name for the event. This value must match the Event Name used when creating the event in the Marketing Cloud UI. **Returns:** `String` - The event name ## Related Types ### CatalogObject ```kotlin class CatalogObject @JvmOverloads constructor( type: String, id: String, attributes: Map = mapOf(), relatedCatalogObjects: Map> = mapOf() ) ``` Represents various items that can be tracked (e.g., a product, a blog post). **Properties:** - **type** (`String`) - A type name representing the catalog object - **id** (`String`) - A unique id representing the catalog object - **attributes** (`Map`) - A map of user-supplied values (default: empty map) - **relatedCatalogObjects** (`Map>`) - A map of related catalog objects (default: empty map) ## Related CatalogEvent Classes The SDK provides several other catalog event types: - `ViewCatalogEvent` - Capture when a user views a catalog object - `ViewCatalogDetailEvent` - Capture when a user views the details of a catalog object - `QuickViewCatalogEvent` - Capture when a user performs a quick view - `ShareCatalogEvent` - Capture when a user shares a catalog object - `CommentCatalogEvent` - Capture when a user comments on a catalog object - `FavoriteCatalogEvent` - Capture when a user marks a catalog object as a favorite ## Event Management Events are managed through the `EventManager`, which is initialized when `SFMCSdk.configure` is called. The EventManager handles event creation for each module. ## Notes - This class is part of the sealed `CatalogEvent` hierarchy, providing type safety for catalog-related events - All catalog events require a `CatalogObject` instance to track the item being interacted with - Event names should match those configured in the Marketing Cloud UI for proper tracking and analytics # RichButton **Package:** `com.salesforce.marketingcloud.pushmodels.rich.buttons` **Module:** Push Models Module v1.0.2 **Hierarchy:** `RichButtonTemplate` > `RichButton` ## Overview ```kotlin data class RichButton( val identifier: String, val title: Text? = null, val icon: String? = null, val style: Style? = null, val actions: List? = listOf(Action.OpenApp) ) : Parcelable, PushView ``` A data class representing a rich button component in the Salesforce Marketing Cloud Unified SDK. This class implements `Parcelable` for Android serialization and `PushView` for view representation. ## Constructors ### RichButton ```kotlin constructor( identifier: String, title: Text? = null, icon: String? = null, style: Style? = null, actions: List? = listOf(Action.OpenApp) ) ``` Creates a new RichButton instance with the specified parameters. ## Properties ### identifier ```kotlin val identifier: String ``` Unique identifier for the button. ### title ```kotlin val title: Text? ``` Optional text content for the button. ### icon ```kotlin val icon: String? ``` Optional icon resource identifier. ### style ```kotlin open override val style: Style? ``` Optional styling configuration (overrides `PushView`). ### actions ```kotlin open override val actions: List? ``` List of actions to execute when the button is pressed. Defaults to `listOf(Action.OpenApp)` (overrides `PushView`). ## Methods ### toJson ```kotlin fun toJson(): JSONObject ``` Converts the RichButton instance to a JSON object representation. **Returns:** `JSONObject` containing the serialized button data. ### toString ```kotlin open override fun toString(): String ``` Returns a string representation of the RichButton instance. **Returns:** `String` representation of the object. # RichButtonTemplate ## Overview A data class representing a template for displaying rich buttons in push notifications. Part of the Salesforce Marketing Cloud Unified SDK Push Models Module (v1.0.2). **Package:** `com.salesforce.marketingcloud.pushmodels.rich.buttons` **Inheritance:** Implements `Template` ## Class Declaration ```kotlin data class RichButtonTemplate( val items: List, val style: Style? = null ) : Template ``` ## Description A carousel template is used to display a list of items in a carousel. ## Constructor ### Primary Constructor ```kotlin constructor( items: List, style: Style? = null ) ``` **Parameters:** - `items`: List of `RichButton` objects to display - `style`: Optional styling configuration for the template ## Properties | Property | Type | Description | | ------------ | ------------------------------------- | ----------------------------------------------- | | `identifier` | `String?` | Override from Template, defaults to `null` | | `items` | `List` | The list of rich buttons to display | | `style` | `Style?` | Optional styling configuration | | `type` | `Template.Type` | Override from Template indicating template type | ## Nested Types ### RichButton ```kotlin data class RichButton( val identifier: String, val title: Text? = null, val icon: String? = null, val style: Style? = null, val actions: List? = listOf(Action.OpenApp) ) : Parcelable, PushView ``` **Properties:** - `identifier`: Unique identifier for the button - `title`: Optional text content for the button - `icon`: Optional icon resource string - `style`: Optional button-specific styling - `actions`: List of actions to perform; defaults to opening the app ### Companion ```kotlin object Companion ``` A companion object for the RichButtonTemplate class. ## Methods ### toString ```kotlin open override fun toString(): String ``` Returns a string representation of the RichButtonTemplate object. ## Related Types - `Template` - Parent interface - `Style` - Styling configuration class - `Action` - Action type for button interactions - `Text` - Text content class - `PushView` - Interface for push notification views --- **Source:** [MarketingCloudSDK-Android JavaDocs](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushmodelsmodule/com.salesforce.marketingcloud.pushmodels.rich.buttons/-rich-button-template/index.html) # RichFeatures ## Overview A data class representing rich notification features in the Salesforce Marketing Cloud Push Models Module. This class implements `Parcelable` for Android serialization. **Package:** `com.salesforce.marketingcloud.pushmodels.rich` **Module:** Push Models Module v1.0.2 **Version:** 11.0.0 **Platform:** androidJvm ## Class Declaration ```kotlin data class RichFeatures( val largeIcon: String? = null, val smallIcon: String? = null, val viewTemplate: Template? = null, val buttons: RichButtonTemplate? = null ) : Parcelable ``` ## Constructors ### Primary Constructor ```kotlin constructor( largeIcon: String? = null, smallIcon: String? = null, viewTemplate: Template? = null, buttons: RichButtonTemplate? = null ) ``` Creates an instance of RichFeatures with optional parameters for customizing rich push notification features. ## Properties ### largeIcon ```kotlin val largeIcon: String? ``` Optional URL or identifier for the large icon to be displayed in the notification. ### smallIcon ```kotlin val smallIcon: String? ``` Optional URL or identifier for the small icon to be displayed in the notification. ### viewTemplate ```kotlin val viewTemplate: Template? ``` Optional template configuration for the notification view layout. References `com.salesforce.marketingcloud.pushmodels.data.Template`. ### buttons ```kotlin val buttons: RichButtonTemplate? ``` Optional configuration for interactive buttons in the notification. References `com.salesforce.marketingcloud.pushmodels.rich.buttons.RichButtonTemplate`. ## Methods ### toJson ```kotlin fun toJson(): String? ``` Serializes the RichFeatures instance to a JSON string representation. **Returns:** A JSON string representation of the object, or null if serialization fails. ## Types ### Companion ```kotlin object Companion ``` Companion object for the RichFeatures class, likely containing factory methods or constants for creating instances. --- **Source:** https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushmodelsmodule/com.salesforce.marketingcloud.pushmodels.rich/-rich-features/index.html # Runtime Toggles Use runtime toggles to configure SDK features without reinitializing the SDK. Use runtime toggles to turn these features on or off: - Analytics services - Predictive intelligence (PI) analytics - Inbox messaging - Geolocation-based messaging - Proximity-based messaging Use runtime toggles to fine-tune the behavior of your app, adapt to changing requirements, and comply with privacy regulations. The SDK provides APIs for getting and setting the status of each feature. These code examples show how to use runtime toggles. ::::::tabset{tabs='["Android SDK v10+", "iOS SDK v10+", "Android SDK v8", "iOS SDK v8"]'} :::::tab For version 10 or later of the SDK for Android, use this code. ```java MarketingCloudSdk.requestSdk { engagementSdk -> // Analytics engagementSdk.analyticsManager.enableAnalytics() // or disableAnalytics() engagementSdk.analyticsManager.areAnalyticsEnabled() engagementSdk.analyticsManager.enablePiAnalytics() // or disablePiAnalytics() engagementSdk.analyticsManager.arePiAnalyticsEnabled() // Messaging engagementSdk.inboxMessageManager.enableInbox() // or disableInbox() engagementSdk.inboxMessageManager.isInboxEnabled() engagementSdk.regionMessageManager.enableGeofenceMessaging() // or disableGeofenceMessaging() engagementSdk.regionMessageManager.isGeofenceMessagingEnabled() engagementSdk.regionMessageManager.enableProximityMessaging() // or disableProximityMessaging() engagementSdk.regionMessageManager.isProximityMessagingEnabled() } ``` ::::: :::::tab For version 10 or later of the SDK for iOS, use this code. ```swift MarketingCloudSdk.requestSdk { mc in //Analytics mc?.setAnalyticsEnabled(_: Bool) mc?.isAnalyticsEnabled() mc?.setPiAnalyticsEnabled(_: Bool) mc?.isPiAnalyticsEnabled() //Messaging mc?.setLocationEnabled(_: Bool) mc?.isLocationEnabled() mc?.setInboxEnabled(_: Bool) mc?.isInboxEnabled() } ``` ::::: :::::tab For version 8 of the SDK for Android, use this code. ```java SFMCSdk.requestSdk { it.mp { push -> // Analytics push.analyticsManager.enableAnalytics() // or disableAnalytics() push.analyticsManager.areAnalyticsEnabled() push.analyticsManager.enablePiAnalytics() // or disablePiAnalytics() push.analyticsManager.arePiAnalyticsEnabled() // Messaging push.inboxMessageManager.enableInbox() // or disableInbox() push.inboxMessageManager.isInboxEnabled() push.regionMessageManager.enableGeofenceMessaging() // or disableGeofenceMessaging() push.regionMessageManager.isGeofenceMessagingEnabled() push.regionMessageManager.enableProximityMessaging() // or disableProximityMessaging() push.regionMessageManager.isProximityMessagingEnabled() } } ``` ::::: :::::tab For version 8 of the SDK for iOS, use this code. ```swift SFMCSdk.requestPushSdk { mp in //Analytics mp.setAnalyticsEnabled(_: Bool) mp.isAnalyticsEnabled() mp.setPIAnalyticsEnabled(_: Bool) mp.isPiAnalyticsEnabled() //Messaging mp.setLocationEnabled(_: Bool) isLocationEnabled() mp.setInboxEnabled(_: Bool) mp.isInboxEnabled() } ``` ::::: :::::: ## Analytics Runtime Toggle Considerations When you use the runtime toggle to turn off analytics, the SDK removes all non-billable analytics and stops recording new non-billable analytics. _Non-billable analytics_ include data used in reports that help you track messaging effectiveness, such as open rates for push notifications and inbox messages. _Billable analytics_ tell Marketing Cloud Engagement about billable actions without collecting user-specific information. Even when you turn off analytics, the SDK sends data for billable events only, with no user-related details from the device. ## See Also - [Analytics](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_analytics/mc_engagement_analytics.md) - [Inbox Messaging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_inbox_messages/mc_engagement_inbox_messages.md) - [Location Messaging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_location_messages/mc_engagement_location_messages.md) # Runtime Toggles To dynamically enable or disable specific functionalities of the SDK without reinitializing it, use Runtime Toggles, also known as Feature Toggles. Runtime Toggles help you fine-tune your application’s behavior and adapt to changing requirements. The Mobile App Messaging SDK supports runtime toggles for Analytics features. ## API Usage To interact with the Runtime Toggles, the SDK provides APIs for each feature to set and get the status of toggled feature. Use this code example to enable and disable analytics for Android apps. ```kotlin MobileAppMessaging.requestSdk { mamSdk -> mamSdk.getAnalyticsManager().areAnalyticsEnabled() mamSdk.getAnalyticsManager().enableAnalytics() mamSdk.getAnalyticsManager().disableAnalytics() } ``` Use this code example to enable and disable analytics for iOS apps. ```swift MobileAppMessaging.requestSdk { mam in //Analytics mam?.setAnalyticsEnabled(_: Bool) mam?.isAnalyticsEnabled() } ``` ## See Also - [Analytics](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_analytics/mc_next_analytics.md) # Salesforce Marketing Cloud Android SDK v11.0 This package contains the core components for the Salesforce Marketing Cloud Unified SDK, providing configuration and initialization functionality for Mobile App Messaging, Marketing Cloud Engagement, Personalization, and Data Cloud (CDP). ## Usage Pattern 1. Build configuration using `SFMCSdkModuleConfig` 2. Call `SFMCSdk.configure()` with the configuration 3. Register `SFMCSdkReadyListener` to receive SDK instance when ready 4. Use `InitializationListener` to monitor initialization status ## SFMCSdk Class **Package:** `com.salesforce.marketingcloud.sfmcsdk` **Since:** 1.0.0 ### Overview ```kotlin class SFMCSdk ``` The `SFMCSdk` class serves as the configuration entry point for Salesforce Marketing Cloud services including Mobile App Messaging, Marketing Cloud Engagement, Personalization, and Data Cloud (CDP). After configuration, it provides access to tracking and Identity management functionality. **Thread Safety:** The SDK is thread-safe and can be used from any thread, though initialization should occur on the main thread. ### Usage Example ```kotlin // Configure the SDK with desired modules SFMCSdk.configure(context, config) { status -> if (status.status == InitializationStatus.SUCCESS) { // SDK is ready to use SFMCSdk.requestSdk { sdk -> // Access SDK functionality sdk.track(Event("app_open")) sdk.identity.edit { setProfileId("123") } } } } ``` ### Properties #### config ```kotlin val config: SFMCSdkModuleConfig ``` The module configuration settings. #### identity ```kotlin var identity: Identity ``` Identity class for identity management operations. ### Methods #### getSdkState ```kotlin fun getSdkState(): JSONObject ``` **Returns:** The current state of all SDK modules as a JSONObject. ### Nested Types #### Companion ```kotlin object Companion ``` Companion object providing static methods for SDK initialization and operations. --- ## SFMCSdk.Companion **Package:** `com.salesforce.marketingcloud.sfmcsdk` ### Overview Companion object for the Salesforce Marketing Cloud Unified SDK, providing static methods for SDK initialization, configuration, and event tracking. ### Properties #### initializationState ```kotlin @JvmStatic val initializationState: InitializationState ``` Returns the current initialization state of the SDK. #### SDK_VERSION_NAME ```kotlin const val SDK_VERSION_NAME: String ``` The version name of the SDK. ### Methods #### configure ```kotlin @MainThread @JvmStatic @JvmOverloads fun configure( context: Context, config: SFMCSdkModuleConfig, listener: InitializationListener? = null ) ``` Initializes the SDK with the provided configuration. **Parameters:** - `context`: Android application context - `config`: SDK module configuration - `listener`: Optional callback notified when initialization completes **Annotations:** - `@MainThread`: Must be called on the main thread - `@JvmStatic`: Accessible from Java as a static method - `@JvmOverloads`: Provides overloaded versions for Java **Notes:** - Subsequent calls with identical config values are ignored - Callers of `requestSdk()` are notified before the `InitializationListener` #### requestSdk ```kotlin @JvmStatic fun requestSdk(listener: SFMCSdkReadyListener) ``` Asynchronously requests an instance of the SDK. **Parameters:** - `listener`: Callback that receives the SDK instance when ready **Behavior:** - Called immediately if SDK is already initialized - Called upon completion if `configure()` is in progress - **Not called** if initialization fails with `FAILURE` status - Listener list cleared on failure #### track ```kotlin @JvmStatic fun track(vararg events: Event?) ``` Tracks one or more events, dispatching them to all registered SDK modules. **Parameters:** - `events`: Variable number of Event objects to track #### sendImmediate ```kotlin @JvmStatic fun sendImmediate(event: Event) ``` Tracks a high-priority event and schedules immediate delivery of queued events. **Parameters:** - `event`: The event to track with high priority **Notes:** - Unlike `track()`, attempts prompt delivery rather than waiting for scheduled delivery #### flush ```kotlin @JvmStatic fun flush() ``` Schedules a flush of all queued events. **Notes:** - Subject to a 60-second throttling period between consecutive flush calls - Deferred requests wait until the throttle window elapses #### setLogging ```kotlin @JvmStatic fun setLogging( level: LogLevel, listener: LogListener?, vararg modules: ModuleLogger ) ``` Enables or disables logging in the SDK. **Parameters:** - `level`: The desired log level - `listener`: Optional callback for log events - `modules`: Variable number of module loggers to configure ## SFMCSdkModuleConfig **Package:** `com.salesforce.marketingcloud.sfmcsdk` ### Overview ```kotlin class SFMCSdkModuleConfig ``` A configuration class for building and managing module configurations supported by the Salesforce Marketing Cloud Unified SDK. This class is used to initialize the SDK through `SFMCSdk.configure()`. ### Description Class which helps in building all configs that SFMCSdk supports. The SDK is initialized only with configurations provided by this class. Callers can provide configurations only for modules that need to be initialized. ### Properties | Property | Type | Description | | ----------------------------------- | ------------------------------------ | ------------------------------------------ | | `cdpModuleConfig` | `CdpModuleConfig?` | Configuration for CDP module | | `engagementModuleConfig` | `EngagementModuleConfig?` | Configuration for Engagement module | | `inAppMessagingFeatureModuleConfig` | `InAppMessagingFeatureModuleConfig?` | Configuration for In-App Messaging feature | | `mamModuleConfig` | `MamModuleConfig?` | Configuration for MAM module | | `personalizationModuleConfig` | `PersonalizationModuleConfig?` | Configuration for Personalization module | | `pushFeatureModuleConfig` | `PushFeatureModuleConfig?` | Configuration for Push feature | ### Nested Types #### Builder ```kotlin class Builder ``` A builder class for creating various module configurations supported by the SDK. #### Companion ```kotlin object Companion ``` Companion object for `SFMCSdkModuleConfig`. --- ## SFMCSdkModuleConfig.Builder **Package:** `com.salesforce.marketingcloud.sfmcsdk` **Parent Class:** `SFMCSdkModuleConfig` ### Overview Builder class for creating configurations supported by `SFMCSdk`. Accepts configs implementing the `Config` interface, including `EngagementModuleConfig`, `PersonalizationModuleConfig`, and `CdpModuleConfig`. ### Constructor ```kotlin constructor() ``` Creates a new Builder instance. ### Properties #### cdpModuleConfig ```kotlin var cdpModuleConfig: CdpModuleConfig? ``` Configuration for the CDP module. #### engagementModuleConfig ```kotlin var engagementModuleConfig: EngagementModuleConfig? ``` Configuration for the Engagement module. #### inAppMessagingFeatureModuleConfig ```kotlin var inAppMessagingFeatureModuleConfig: InAppMessagingFeatureModuleConfig? ``` Configuration for the In-App Messaging feature module. #### mamModuleConfig ```kotlin var mamModuleConfig: MamModuleConfig? ``` Configuration for the MAM module. #### personalizationModuleConfig ```kotlin var personalizationModuleConfig: PersonalizationModuleConfig? ``` Configuration for the Personalization module. #### pushFeatureModuleConfig ```kotlin var pushFeatureModuleConfig: PushFeatureModuleConfig? ``` Configuration for the Push feature module. ### Methods #### build ```kotlin fun build(): SFMCSdkModuleConfig ``` Builds the `SFMCSdkModuleConfig` with the configured Builder. All module configs provided through the Builder are initialized. **Returns:** `SFMCSdkModuleConfig` --- ## InitializationStatus Interface **Package:** `com.salesforce.marketingcloud.sfmcsdk` ### Overview ```kotlin interface InitializationStatus ``` The initialization status interface for the Salesforce Marketing Cloud Unified SDK. ### Properties #### status ```kotlin abstract val status: Int ``` The status of the SDK's initialization result. ### Nested Types #### Companion ```kotlin object Companion ``` Companion object containing status constants. ### Constants (InitializationStatus.Companion) #### SUCCESS ```kotlin const val SUCCESS: Int = 1 ``` The SDK successfully initialized. #### FAILURE ```kotlin const val FAILURE: Int ``` The SDK failed to initialize successfully. ### Inheritors - `SFMCSdkInitializationStatus` --- ## SFMCSdkInitializationStatus **Package:** `com.salesforce.marketingcloud.sfmcsdk` ### Overview ```kotlin class SFMCSdkInitializationStatus : InitializationStatus ``` `SFMCSdkInitializationStatus` is a class that implements the `InitializationStatus` interface. It provides an implementation for tracking the SDK initialization state. ### Inheritance ``` InitializationStatus ↳ SFMCSdkInitializationStatus ``` ### Properties #### status ```kotlin open override val status: Int ``` The SDK's initialization status value. --- ## InitializationState Enum **Package:** `com.salesforce.marketingcloud.sfmcsdk` **Type:** `enum` ### Overview ```kotlin enum class InitializationState ``` An enumeration that represents the current initialization state of the Salesforce Marketing Cloud SDK. ### Enum Values | Value | Description | | -------------- | ------------------------------------------------------------------ | | `NONE` | SDK has not started initialization | | `INITIALIZING` | SDK is currently in the process of initializing | | `READY` | SDK has completed initialization successfully and is ready for use | | `ERROR` | SDK initialization failed due to an error | ### Properties #### entries ```kotlin val entries: EnumEntries ``` Returns an immutable list of all enum entries in declaration order. ### Methods #### valueOf ```kotlin fun valueOf(value: String): InitializationState ``` Returns the enum constant matching the specified name. The string must exactly match an enum constant identifier. **Parameters:** - `value`: The name of the enum constant **Returns:** The enum constant of this type with the specified name #### values ```kotlin fun values(): Array ``` Returns an array of all enum constants in declaration order. **Returns:** Array containing all enum constants --- ## Type Aliases ### InitializationListener ```kotlin typealias InitializationListener = (InitializationStatus) -> Unit ``` Observer function notified when SDK initialization completes. **Parameters:** - `InitializationStatus`: The status object containing initialization result ### SFMCSdkReadyListener ```kotlin interface SFMCSdkReadyListener ``` Functional interface that provides a valid `SFMCSdk` instance when ready. **Behavior:** - Called immediately if SDK is already initialized - Called upon completion if `configure()` is in progress - **Not called** if initialization fails with `FAILURE` status - Listener list cleared on failure # Salesforce Marketing Cloud iOS SDK v11 Complete API reference for all iOS SDK modules. ## SDK Modules ### [SFMC SDK (Foundation)](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/sfmc-sdk/sfmc-sdk_index.md) Foundation SDK providing core infrastructure for all Marketing Cloud iOS SDKs ### [MCE SDK (Marketing Cloud Engagement)](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/mce-sdk/mce-sdk_index.md) Marketing Cloud Engagement SDK for MobilePush, location, and inbox ### [MAM Core Module (Mobile App Messaging)](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/mam-core/mam-core_index.md) Mobile App Messaging SDK for registration, analytics, and in-app messages ### [IAM Feature Module (In-App Messaging)](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/iam-feature/iam-feature_index.md) In-App Messaging module with template rendering and frequency capping ### [Push Feature Module](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/push-feature/push-feature_index.md) Push notification module for token management and badge handling ### [Extension SDK (Rich Notifications)](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/extension-sdk/extension-sdk_index.md) Notification Service and Content Extensions for rich push notifications --- ## Requirements - **iOS:** 12.0+ - **Xcode:** 26+ - **Swift:** 5.0+ ## Installation ```ruby # Podfile pod 'MarketingCloud-SFMCSdk', '~> 4.0' pod 'MarketingCloudSDK', '~> 11.0' # or pod 'SFMobileAppMessagingSDK', '~> 2.0' ``` See individual module documentation for detailed installation instructions. ## Documentation - [Developer Guide](https://developer.salesforce.com/docs/marketing/mobilepush/guide) - [Release Notes](https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS/releases) ## Support - [Salesforce Stack Exchange](https://salesforce.stackexchange.com/) - [GitHub Issues](https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS/issues) # Segment Location Messages You can deliver location messages to a subset of your audience by using the Salesforce Engagement SDK. When a mobile device breaks a geofence or comes into proximity of a Bluetooth beacon, the SDK triggers a callback to your mobile app. This callback is used to evaluate whether to show the message. To determine whether to show the message, your app can apply criteria, including information within the message itself. For example, your app can: - Show the message if the user's my store location is within the geofence region. - Show the message if the user has items in the app shopping cart and if the message has an "abandonedCart":"true" custom key. - Show the message only when the store is open based on the app's store location list and the region and local time. - Don't show messages if the user isn't logged in to the app. - Show specific messages based on the user's customer profile. For example, customers who are coffee lovers get messages about coffee, but customers who prefer pastry receive a message to "add a coffee" when they're in the shop. ::::::tabset{tabs='["SDK v10+", "SDK v8", "SDK v7"]'} :::::tab ``` // Adopt the protocol in your app's class, which implements the // sfmc_shouldShowLocationMessage:forRegion: method class AppDelegate: UIResponder, UIApplicationDelegate, LocationDelegate ... // After configuring the SDK, set the location delegate to the class that // implements the sfmc_shouldShowLocationMessage:forRegion: method MarketingCloudSdk.requestSdk { mc in mc?.setLocationDelegate(self) } // Implement the method to evaluate app logic to determine if a message should // be shown. This example uses attributes and custom message keys to // implement simple matching logic. Your implementation will vary according to // your unique needs. func sfmc_shouldShowLocationMessage( _ message: [AnyHashable : Any], forRegion region: [AnyHashable : Any] ) -> Bool { var shouldShow = false var attributesLoyaltyLevel = "" // Get a contact attribute previously set by your app from the SDK // In this example, "loyaltyLevel" indicates a customer contact value that // your app uses. var attributes: [AnyHashable : Any]? = nil MarketingCloudSdk.requestSdk { mc in attributes = mc?.attributes() } if attributes?.index(forKey: "loyaltyLevel") != nil { attributesLoyaltyLevel = attributes!["loyaltyLevel"] as! String } // Get the custom keys for a location message if (message["keys"] != nil) { let customKeys = message["keys"] as! [AnyHashable : Any] // get the "loyaltyLevel" custom key's value let messageLoyaltyLevel = customKeys["loyaltyLevel"] as! String // in this example, if the customer contact attribute is set to "gold" // AND the message's custom key is "gold", return true - this message // is valid to show for this customer // the SDK will display the location message, as the critera passed if (attributesLoyaltyLevel == "gold" && messageLoyaltyLevel == "gold") { shouldShow = true } } return shouldShow } ``` ::::: :::::tab ``` // Adopt the protocol in your app's class, which implements the // sfmc_shouldShowLocationMessage:forRegion: method class AppDelegate: UIResponder, UIApplicationDelegate, LocationDelegate ... // After configuring the SDK, set the location delegate to the class that // implements the sfmc_shouldShowLocationMessage:forRegion: method SFMCSdk.requestPushSdk { mp in mp.setLocationDelegate(self) } ... // Implement the method to evaluate app logic to determine if a message should // be shown. This example uses attributes and message custom keys to // implement simple matching logic. Your implementation will vary according to // your unique needs. func sfmc_shouldShowLocationMessage( _ message: [AnyHashable : Any], forRegion region: [AnyHashable : Any] ) -> Bool { var shouldShow = false var attributesLoyaltyLevel = "" // Get a contact attribute previously set by your app from the SDK // In this example, "loyaltyLevel" indicates a customer contact value that // your app uses. var attributes: [AnyHashable : Any]? = nil SFMCSdk.requestPushSdk { mp in attributes = mp.attributes() } if attributes?.index(forKey: "loyaltyLevel") != nil { attributesLoyaltyLevel = attributes!["loyaltyLevel"] as! String } // Get the custom keys for a location message if (message["keys"] != nil) { let customKeys = message["keys"] as! [AnyHashable : Any] // get the "loyaltyLevel" custom key's value let messageLoyaltyLevel = customKeys["loyaltyLevel"] as! String // in this example, if the customer contact attribute is set to "gold" // AND the message's custom key is "gold", return true - this message // is valid to show for this customer // the SDK will display the location message, as the critera passed if (attributesLoyaltyLevel == "gold" && messageLoyaltyLevel == "gold") { shouldShow = true } } return shouldShow } ``` ::::: :::::tab ``` // adopt the protocol in your application's class which will implement the sfmc_shouldShowLocationMessage:forRegion: method class AppDelegate: UIResponder, UIApplicationDelegate, MarketingCloudSDKLocationDelegate ... // after configuring your SDK, set the location delegate to your class implementing the sfmc_shouldShowLocationMessage:forRegion: method MarketingCloudSDK.sharedInstance().sfmc_setLocationDelegate(self) ... // Implement the method to evaluate application logic to determine if a message should be shown. // This example uses attributes and message custom keys to implement simple matching logic. func sfmc_shouldShowLocationMessage(_ message: [AnyHashable : Any], forRegion region: [AnyHashable : Any]) -> Bool { var shouldShow = false var attributesLoyaltyLevel = "" // Get a contact attribute previously set by your app from the SDK. // In this example, "loyaltyLevel" indicates a customer contact value your solution uses. var attributes = MarketingCloudSDK.sharedInstance().sfmc_attributes() if attributes?.index(forKey: "loyaltyLevel") != nil { attributesLoyaltyLevel = attributes!["loyaltyLevel"] as! String } // Get the custom keys for the location message if (message["keys"] != nil) { let customKeys = message["keys"] as! [AnyHashable : Any] // get the "loyaltyLevel" custom key's value let messageLoyaltyLevel = customKeys["loyaltyLevel"] as! String // in this example, if the customer contact attribute is set to "gold" // AND the message's custom key is "gold", return true - this message // is valid to show for this customer // the SDK will display the location message, as the critera passed if (attributesLoyaltyLevel == "gold" && messageLoyaltyLevel == "gold") { shouldShow = true } } return shouldShow } ``` ::::: :::::: # Send a Test Push To test whether your app can receive a push directly from the Apple Push Notification service (APNs), follow these steps. 1. Get the push token from the SDK by calling the `deviceToken` method and send the result to yourself via email, alert, or another method. These code examples show how to call the `deviceToken` method. ::::::tabset{tabs='["SDK v10+", "SDK v8", "SDK v7"]'} :::::tab For SDK version 10 or later, use this code: ```swift PushFeature.requestSdk { pushFeature in print(pushFeature?.deviceToken() ?? "error: no token - was UIApplication.shared.registerForRemoteNotifications() called?") } ``` ::::: :::::tab For SDK version 8, use this code: ```swift print(SFMCSdk.mp.deviceToken() ?? "error: no token - was UIApplication.shared.registerForRemoteNotifications() called?") ``` ::::: :::::tab For SDK version 7, use this code: ```swift print(MarketingCloudSDK.sharedInstance().sfmc_deviceToken() ?? "error: no token - was UIApplication.shared.registerForRemoteNotifications() called?") ``` ::::: :::::: 2. Trigger the APNs API directly from the command line by running a bash script. The script you run depends on whether your app uses a .p8 key or a .p12 certificate. ::::::tabset{tabs='[".p8 Key", ".p12 Certificate"]'} :::::tab **note:** This bash script points to the `development` APNs service by default. To trigger push from the APNs production server, change the value of the `endpoint` variable to `https://api.push.apple.com`. ```bash #!/bin/bash # To get curl with HTTP/2 and openssl with ECDSA: run 'brew install curl-openssl' curl=/usr/local/opt/curl/bin/curl openssl=/usr/local/opt/openssl/bin/openssl -------------------------------------------------------------------------- deviceToken=YOUR_PUSH_TOKEN authKey=PATH_TO_YOUR_P8_FILE authKeyId=KEY_ID_FOR_YOUR_P8_FILE teamId=YOUR_TEAM_ID bundleId=YOUR_BUNDLE_ID endpoint=https://api.development.push.apple.com read -r -d '' payload <<-'EOF' { "aps": { "badge": 1, "alert": { "title": "TEST_PUSH_TITLE", "subtitle": "TEST_PUSH_SUBTITLE", "body": "TEST_PUSH_BODY" }, "_sid": "SFMC" } } EOF # -------------------------------------------------------------------------- base64() { $openssl base64 -e -A | tr -- '+/' '-_' | tr -d = } sign() { printf "$1"| $openssl dgst -binary -sha256 -sign "$authKey" | base64 } time=$(date +%s) header=$(printf '{ "alg": "ES256", "kid": "%s" }' "$authKeyId" | base64) claims=$(printf '{ "iss": "%s", "iat": %d }' "$teamId" "$time" | base64) jwt="$header.$claims.$(sign $header.$claims)" $curl --verbose \ --header "content-type: application/json" \ --header "authorization: bearer $jwt" \ --header "apns-topic: $bundleId" \ --data "$payload" \ $endpoint/3/device/$deviceToken ``` ::::: :::::tab ```bash #!/bin/sh export DEVICE_TOKEN=YOUR_PUSH_TOKEN export BUNDLE_ID=YOUR_APP_BUNDLE_ID export CERT_PATH=PATH_TO_YOUR_P12_FILE export CERT_PASSWORD=PASSWORD_FOR_YOUR_P12_FILE # sent your endpoint to prod or sandbox # sandbox MUST use a development push certificate # sandbox MUST use a push token from a debugging build of your app (run from # Xcode to a connected device) export ENDPOINT=https://api.push.apple.com/3/device #export ENDPOINT=https://api.sandbox.push.apple.com/3/device curl -v \ -d '{"_m": "TEST_MESSAGE_ID", "aps": {"alert": {"body": "TEST_PUSH_BODY", "title": "TEST_PUSH_TITLE", "subtitle": "TEST_PUSH_SUBTITLE"},"_sid": "SFMC"}}' \ -H "apns-topic: ${BUNDLE_ID}" \ --http2 \ --cert ${CERT_PATH}:${CERT_PASSWORD} \ --cert-type P12 \ ${ENDPOINT}/${DEVICE_TOKEN} ``` ::::: :::::: ## Send a Test Message by Using Marketing Cloud Engagement After you send a test message by using the API, you can also send a test by using the Marketing Cloud Engagement user interface. Make sure that you select the same environment MobilePush Administration page as you used to send the test message via the API. If you select **Development** on the MobilePush Administration page, Marketing Cloud Engagement contacts the `Sandbox` APNs server. If you select **Production**, it contacts the `Production` APNs server. # Send Custom Campaign Details to Google Analytics 4 Use Google Analytics 4 (GA4) to obtain metrics for your MobilePush apps. ## Prerequisites - Implement the Engagement SDK in your app. - Implement the Firebase SDK in your app and configure it for your app platform: - For iOS apps, see _Get Started with Firebase_: [Add Firebase to your Apple project](https://firebase.google.com/docs/ios/setup). - For Android apps, see _Get Started with Firebase_: [Add Firebase to your Android project](https://firebase.google.com/docs/android/setup). ## Log the AnalyticsEventCampaignDetails Event To log the `AnalyticsEventCampaignDetails` event: 1. Extract these parameters from the MobilePush message payload received from Marketing Cloud Engagement: - `sfmc_journey_id` - `sfmc_journey_name` - `sfmc_activity_id` - `sfmc_activity_name` - `sfmc_channel` - `sfmc_asset_id` - `sfmc_id` 2. Log an [AnalyticsEventCampaignDetails](https://firebase.google.com/docs/reference/swift/firebaseanalytics/api/reference/Constants#/c:FIREventNames.h@kFIREventCampaignDetails) event. **note:** The `campaign_details` event is the first event sent to Google Analytics after receiving the push notification from Marketing Cloud Engagement. Sending this event first ensures that all subsequent events sent to Google Analytics are associated with the campaign details. ## iOS Example This example demonstrates how to log the campaign details event in your iOS app using Swift, by extracting the necessary parameters from the `userInfo` dictionary and logging the `AnalyticsEventCampaignDetails` event. ```swift func logAnalyticsEvent(userInfo: [AnyHashable : Any]) -> Void { var params:[String: String] = [:] if let sfmc_journey_id = userInfo["sfmc_journey_id"] { params["sfmc_journey_id"] = sfmc_journey_id as? String ?? "" } if let sfmc_journey_name = userInfo["sfmc_journey_name"] { params["sfmc_journey_name"] = sfmc_journey_name as? String ?? "" } if let sfmc_activity_id = userInfo["sfmc_activity_id"] { params["sfmc_activity_id"] = sfmc_activity_id as? String ?? "" } if let sfmc_activity_name = userInfo["sfmc_activity_name"] { params["sfmc_activity_name"] = sfmc_activity_name as? String ?? "" } if let sfmc_channel = userInfo["sfmc_channel"] { params["sfmc_channel"] = sfmc_channel as? String ?? "" } if let sfmc_asset_id = userInfo["sfmc_asset_id"] { params["sfmc_asset_id"] = sfmc_asset_id as? String ?? "" } if let sfmc_id = userInfo["sfmc_id"] { params["sfmc_id"] = sfmc_id as? String ?? "" } if params.count > 0 { Analytics.logEvent(AnalyticsEventCampaignDetails, parameters:params) } } ``` ## See Also - _Salesforce Help_: [Manage Parameters](https://help.salesforce.com/s/articleView?id=mktg.mc_overview_parameter_management.htm) - _Salesforce Help_: [Configure Google Analytics App Tracking](https://help.salesforce.com/s/articleView?id=mktg.mc_gai_configure_app_tracking.htm) # Send Rich Notifications Include images, videos, titles, and subtitles in your push notifications to create more engaging messages. Rich notifications use mutable content that can include personalization in the title, subtitle, or body of your message. To use rich notifications, your app requires iOS 10 or later, a Notification Service Extension that handles mutable content, and registration for push notifications via the Salesforce Engagement SDK. The service extension downloads media from a URL, creates attachments, and handles fallback text if media fails to load. Skip these steps if you've already integrated the [Notification Service Extension](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_integrate_ios_extension/mc_engagement_integrate_ios_extension.md). 1. In Xcode, click **File** > **New** > **Target**. 2. Select **Notification Service Extension**. 3. Name and save the new extension. 4. In your project target’s **General** settings, confirm that the new extension is listed in the **Frameworks, Libraries, and Embedded Content** section. If it isn’t, add it. **important:** Sign the Notification Target with the same Xcode Managed Profile as the main project. This service extension checks for a `_mediaUrl` element in `request.content.userInfo`. If the extension finds this element, it tries to download the media from the URL, creates a thumbnail version, and then adds the attachment. The service extension also checks for a `_mediaAlt` element in `request.content.userInfo`. If found, the service extension uses the element for the body text if there are any problems downloading or creating the media attachment. A service extension can timeout if it’s unable to download. In this code sample, the service extension delivers the original content with the body text changed to the value in `_mediaAlt`. ::::::tabset{tabs='["Without Extension SDK", "With Extension SDK"]'} :::::tab ```swift import UserNotifications import CoreGraphics class MyNotificationService: UNNotificationServiceExtension { var contentHandler: ((UNNotificationContent) -> Void)? var bestAttemptContent: UNMutableNotificationContent? override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.contentHandler = contentHandler self.bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) self.addMedia(request) { self.contentHandler!(self.bestAttemptContent!) } } override func serviceExtensionTimeWillExpire() { // Called just before the extension is terminated by the system. // Use this as an opportunity to deliver your "best attempt" at modified content. Otherwise, the original push payload is used. // We took too long to download the media URL. Use the alternate text if provided. self.useAltText() // Tell the OS that the process is complete and the content is ready to be presented. self.contentHandler!(self.bestAttemptContent!) } private func useAltText() { if let mediaAltText = self.bestAttemptContent?.userInfo["_mediaAlt"] as? String { // alternative text to display if there are any issues loading the media URL if mediaAltText.isEmpty == false { self.bestAttemptContent?.body = mediaAltText } } } private func addMedia(_ request: UNNotificationRequest, completion: @escaping () -> Void) { guard let mediaUrlString = request.content.userInfo["_mediaUrl"] as? String, !mediaUrlString.isEmpty else { useAltText() completion() return } guard let mediaUrl = URL(string: mediaUrlString) else { useAltText() completion() return } let session = URLSession(configuration: URLSessionConfiguration.default) let downloadTask = session.downloadTask(with: mediaUrl) { [weak self] location, response, error in if let _ = error { self?.useAltText() completion() return } guard let theLocation = location else { self?.useAltText() completion() return } guard let theResponse = response as? HTTPURLResponse else { self?.useAltText() completion() return } let statusCode = theResponse.statusCode guard (statusCode >= 200 && statusCode <= 299) else { self?.useAltText() completion() return } let localMediaUrl = URL.init(fileURLWithPath: theLocation.path + mediaUrl.lastPathComponent) // Remove any existing file with the same name try? FileManager.default.removeItem(at: localMediaUrl) do { try FileManager.default.moveItem(at: theLocation, to: localMediaUrl) } catch { self?.useAltText() completion() return } guard let mediaAttachment = try? UNNotificationAttachment(identifier: "SomeAttachmentId", url: localMediaUrl) else { self?.useAltText() completion() return; } guard let theContent = self?.bestAttemptContent else { self?.useAltText() completion() return } theContent.attachments = [mediaAttachment] completion() } downloadTask.resume() } } ``` ::::: :::::tab ```swift // // NotificationService.swift // MyServiceExtension // // import UserNotifications import MCExtensionSDK class NotificationService: SFMCNotificationService { // Use this method to enable logging, change logging levels, etc. , if required. override func sfmcProvideConfig() -> SFNotificationServiceConfig { var logLevel: LogLevel = .none #if DEBUG logLevel = .debug #endif return SFNotificationServiceConfig(logLevel: logLevel) } // To perform custom processing for images, video downloads, or inserting custom keys in notification userInfo, use this method. // Don’t modify `mutableContent.request.content.userInfo` directly. Doing so can trigger an exception. // To add a custom key in notification userInfo, return a dictionary in the completion handler. // Like the `UNNotificationServiceExtension` method - func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) → Void), the system allows only a limited time for processing. override func sfmcDidReceive(_ request: UNNotificationRequest, mutableContent: UNMutableNotificationContent, withContentHandler contentHandler: @escaping ([AnyHashable : Any]?) -> Void) { // Your custom code here //... self.addMedia(mutableContent) { // Add custom key:value pairs in the userInfo object var customUserInfo: [AnyHashable : Any] = [:] customUserInfo["MyCustomKey"] = "MyCustomValue" // Finally, call the content handler to signal the end of your processing operation. contentHandler(customUserInfo) } } private func addMedia(_ mutableContent: UNMutableNotificationContent, completion: @escaping () -> Void) { guard let mediaUrlString = mutableContent.userInfo["_mediaUrl"] as? String, !mediaUrlString.isEmpty else { completion() return } guard let mediaUrl = URL(string: mediaUrlString) else { completion() return } let session = URLSession(configuration: URLSessionConfiguration.default) let downloadTask = session.downloadTask(with: mediaUrl) { [weak self] location, response, error in if let _ = error { completion() return } guard let theLocation = location else { completion() return } guard let theResponse = response as? HTTPURLResponse else { completion() return } let statusCode = theResponse.statusCode guard (statusCode >= 200 && statusCode <= 299) else { completion() return } let localMediaUrl = URL.init(fileURLWithPath: theLocation.path + mediaUrl.lastPathComponent) // Remove any existing file with the same name try? FileManager.default.removeItem(at: localMediaUrl) do { try FileManager.default.moveItem(at: theLocation, to: localMediaUrl) } catch { completion() return } guard let mediaAttachment = try? UNNotificationAttachment(identifier: "SomeAttachmentId", url: localMediaUrl) else { completion() return; } mutableContent.attachments = [mediaAttachment] completion() } downloadTask.resume() } } ``` ::::: :::::: # Send Rich Notifications Rich notifications include images, videos, titles, and subtitles from Marketing Cloud Next and mutable content. Mutable content can include personalization in the title, subtitle, or body of your message. ## Prerequisites - Make sure that your app is built for iOS version 10 or later. - Include a service extension for your app that can handle mutable content. See _Apple Developer Documentation_: [Modifying and Presenting Notifications](https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/ModifyingNotifications.html). - Make sure that your app is registered to send push notifications in Marketing Cloud Next. ## Create a Notification Service Extension Skip these steps if you’ve already integrated Notification Service Extension when you integrated the Mobile App Messaging SDK with your app. 1. Click **File** > **New** > **Target**. 2. Select **Notification Service Extension**. 3. Name and save the new extension. 4. In your project target’s **General** settings, confirm that the new extension is listed in the **Frameworks, Libraries, and Embedded Content** section. If not, add it. **important:** The Notification Target must be signed with the same Xcode Managed Profile as the main project. This service extension checks for a `_mediaUrl` element in `request.content.userInfo`. If found, the extension attempts to download the media from the URL, creates a thumbnail-size version, and then adds the attachment. The service extension also checks for a `_mediaAlt` element in `request.content.userInfo`. If found, the service extension uses the element for the body text if there are any problems downloading or creating the media attachment. A service extension can timeout if it’s unable to download. In this code sample, the service extension delivers the original content with the body text changed to the value in `_mediaAlt`. This code example assumes your app is using the Mobile App Messaging SDK without the Extension SDK integration. ``` import UserNotifications import CoreGraphics class MyNotificationService: UNNotificationServiceExtension { var contentHandler: ((UNNotificationContent) -> Void)? var bestAttemptContent: UNMutableNotificationContent? override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.contentHandler = contentHandler self.bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) self.addMedia(request) { self.contentHandler!(self.bestAttemptContent!) } } override func serviceExtensionTimeWillExpire() { // Called just before the extension is terminated by the system. // Use this as an opportunity to deliver your "best attempt" at modified content. Otherwise, the original push payload will be used. // We took too long to download the media URL. Use the alternate text if provided. self.useAltText() // Tell the OS that the process is complete and the content is ready to be presented. self.contentHandler!(self.bestAttemptContent!) } private func useAltText() { if let mediaAltText = self.bestAttemptContent?.userInfo["_mediaAlt"] as? String { // alternative text to display if there are any issues loading the media URL if mediaAltText.isEmpty == false { self.bestAttemptContent?.body = mediaAltText } } } private func addMedia(_ request: UNNotificationRequest, completion: @escaping () -> Void) { guard let mediaUrlString = request.content.userInfo["_mediaUrl"] as? String, !mediaUrlString.isEmpty else { useAltText() completion() return } guard let mediaUrl = URL(string: mediaUrlString) else { useAltText() completion() return } let session = URLSession(configuration: URLSessionConfiguration.default) let downloadTask = session.downloadTask(with: mediaUrl) { [weak self] location, response, error in if let _ = error { self?.useAltText() completion() return } guard let theLocation = location else { self?.useAltText() completion() return } guard let theResponse = response as? HTTPURLResponse else { self?.useAltText() completion() return } let statusCode = theResponse.statusCode guard (statusCode >= 200 && statusCode <= 299) else { self?.useAltText() completion() return } let localMediaUrl = URL.init(fileURLWithPath: theLocation.path + mediaUrl.lastPathComponent) // Remove any existing file with the same name try? FileManager.default.removeItem(at: localMediaUrl) do { try FileManager.default.moveItem(at: theLocation, to: localMediaUrl) } catch { self?.useAltText() completion() return } guard let mediaAttachment = try? UNNotificationAttachment(identifier: "SomeAttachmentId", url: localMediaUrl) else { self?.useAltText() completion() return; } guard let theContent = self?.bestAttemptContent else { self?.useAltText() completion() return } theContent.attachments = [mediaAttachment] completion() } downloadTask.resume() } } ``` If your app uses the Mobile App Messaging SDK with the Extension SDK integration, use this code example instead. ``` // NotificationService.swift // MyServiceExtension import UserNotifications import MCExtensionSDK class NotificationService: SFMCNotificationService { // Use this method to enable logging, change logging levels, etc. , if required. override func sfmcProvideConfig() -> SFNotificationServiceConfig { var logLevel: LogLevel = .none #if DEBUG logLevel = .debug #endif return SFNotificationServiceConfig(logLevel: logLevel) } // Use this method only if you need to perform any custom processing for // images, video downloads, inserting custom keys in notification userInfo, etc. // Don’t modify mutableContent.request.content.userInfo directly. To add any // custom key in notification userInfo, return a dictionary in the // completion handler. // Like the `UNNotificationServiceExtension` method - func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) → Void), you'll only have limited time from the system for processing. override func sfmcDidReceive(_ request: UNNotificationRequest, mutableContent: UNMutableNotificationContent, withContentHandler contentHandler: @escaping ([AnyHashable : Any]?) -> Void) { // Your custom code here //... self.addMedia(mutableContent) { // To add any custom key:value pair(s) in notifications userInfo object, then var customUserInfo: [AnyHashable : Any] = [:] customUserInfo["MyCustomKey"] = "MyCustomValue" // Finally, call the content handler to signal the end of your processing operation. // contentHandler(customUserInfo) } } private func addMedia(_ mutableContent: UNMutableNotificationContent, completion: @escaping () -> Void) { guard let mediaUrlString = mutableContent.userInfo["_mediaUrl"] as? String, !mediaUrlString.isEmpty else { completion() return } guard let mediaUrl = URL(string: mediaUrlString) else { completion() return } let session = URLSession(configuration: URLSessionConfiguration.default) let downloadTask = session.downloadTask(with: mediaUrl) { [weak self] location, response, error in if let _ = error { completion() return } guard let theLocation = location else { completion() return } guard let theResponse = response as? HTTPURLResponse else { completion() return } let statusCode = theResponse.statusCode guard (statusCode >= 200 && statusCode <= 299) else { completion() return } let localMediaUrl = URL.init(fileURLWithPath: theLocation.path + mediaUrl.lastPathComponent) // Remove any existing file with the same name try? FileManager.default.removeItem(at: localMediaUrl) do { try FileManager.default.moveItem(at: theLocation, to: localMediaUrl) } catch { completion() return } guard let mediaAttachment = try? UNNotificationAttachment(identifier: "SomeAttachmentId", url: localMediaUrl) else { completion() return; } mutableContent.attachments = [mediaAttachment] completion() } downloadTask.resume() } } ``` # Set an Event Delegate Receive notifications about the in-app message display lifecycle by setting an event delegate. By implementing the event delegate, you can track when an in-app message is shown or closed, control whether an in-app message can be displayed based on your app’s state, and manage the view hierarchy for your app when an in-app message appears. Make your application a delegate of the SDK’s in-app messaging functionality by using the `setEventDelegate` method. Set the delegate early in your class’s initialization to make sure that your app can respond to in-app message events. ::::::tabset{tabs='["SDK v11", "SDK v10", "SDK v8.1", "SDK v8.0", "SDK v7"]'} :::::tab Use this code to set the event delegate in version 11 of the SDK for iOS. 1. Add the `InAppMessageEventDelegate` protocol to your class declaration. 2. Set your class as the delegate of the SDK for in-app message events early in your class’s initialization. ```swift // Add the InAppMessageEventDelegate protocol to your class declaration class MyViewController: UIViewController, InAppMessageEventDelegate { override func viewDidLoad() { super.viewDidLoad() // Set your class as the delegate of the SDK for in-app message events InAppMessagingFeature.requestSdk { iam in iam?.setEventDelegate(self) } } } ``` ::::: :::::tab Use this code to set the event delegate in version 10 of the SDK for iOS. 1. Add the `InAppMessageEventDelegate` protocol to your class declaration. 2. Set your class as the delegate of the SDK for in-app message events early in your class’s initialization. ```swift // Add the InAppMessageEventDelegate protocol to your class declaration class MyViewController: UIViewController, InAppMessageEventDelegate { override func viewDidLoad() { super.viewDidLoad() // Set your class as the delegate of the SDK for in-app message events MarketingCloudSdk.requestSdk { mc in mc?.setEventDelegate(self) } } } ``` ::::: :::::tab Use this code to set the event delegate in version 8.1 of the SDK for iOS. 1. Add the `InAppMessageEventDelegate` protocol to your class declaration. 2. Set your class as the delegate of the SDK for in-app message events early in your class’s initialization. ```swift // Add the InAppMessageEventDelegate protocol to your class declaration class MyViewController: UIViewController, InAppMessageEventDelegate { override func viewDidLoad() { super.viewDidLoad() // Set your class as the delegate of the SDK for in-app message events SFMCSdk.requestPushSdk { mp in mp.setEventDelegate(self) } } } ``` ::::: :::::tab Use this code to set the event delegate in version 8.0 of the SDK for iOS. 1. Add the `InAppMessageEventDelegate` protocol to your class declaration. 2. Set your class as the delegate of the SDK for in-app message events after the SDK is initialized successfully and is operational. ```swift // Add the InAppMessageEventDelegate protocol to your class declaration class MyViewController: UIViewController, InAppMessageEventDelegate { override func viewDidLoad() { super.viewDidLoad() // Set your class as the delegate of the SDK for in-app message events // Make sure that the SDK is operational SFMCSdk.mp.setEventDelegate(self) } } ``` ::::: :::::tab Use this code to set the event delegate in version 7 of the SDK for iOS. 1. Add the `MarketingCloudSDKEventDelegate` protocol to your class declaration. 2. Set your class as the delegate of the SDK for in-app message events early in your class’s initialization. ```swift // Add the MarketingCloudSDKEventDelegate protocol to your class declaration class MyViewController: UIViewController, MarketingCloudSDKEventDelegate { override func viewDidLoad() { super.viewDidLoad() // Set your class as the delegate of the SDK for in-app message events MarketingCloudSDK.sharedInstance().sfmc_setEventDelegate(self) } } ``` ::::: :::::: After you set the event delegate, implement the delegate methods to respond to in-app message events: - [Track Message View States](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_in-app_messages_ios_track_view_states.md) - Respond when messages are shown or closed. - [Prevent or Delay Message Display](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_in-app_messages_ios_prevent_delay_display.md) - Control when messages can be displayed. # Set Contact Attributes and Tags Attributes are key-value pairs that you can use to segment your audience and personalize your messages. Examples of attributes include first name, last name, loyalty level, channel preference, signup date, birthday, ZIP code, or a unique identifier. Tags are categories that let your audience express their interests or preferences and what they want to receive notifications about. For example, a news app can offer article categories, or tags, for users to follow, such as sports, headlines, and entertainment. App users select the tags they’re interested in. ## Decide on Your Segmentation and Personalization Strategy When you determine your segmentation and personalization strategy, it’s important to understand the roles of tags and attributes in Marketing Cloud Engagement. Attributes are the common standard for segmentation and personalization across all channel types. Attributes are more descriptive than tags and are the primary way to segment demographic data. You can change and update attributes. Before you set attributes, first define them in Contact Builder. The SDK rejects registrations that include attributes that aren’t defined in Contact Builder. Tags are a complement to attributes. Tags are a device-specific way to collect small amounts of information to use for segmentation. Unlike attributes, it isn’t necessary to define tags in Marketing Cloud before the SDK submits values for them. Tags are registered to the MobilePush Tags table in Contact Builder. ## Create Custom Attributes If you want your app to use custom attributes, create and define them in Marketing Cloud Engagement. The **MobilePush Demographics** table is tied to your organization’s data model. Before making any changes, consult with your marketing team. 1. In Contact Builder, select the **Data Designer** tab. 2. In Data Designer, select the **MobilePush Data** attribute group. 3. Review the **MobilePush Demographics** table for available attributes. 4. Select an attribute to review its schema or data type. 5. To add an attribute, click **Create Attribute**. **tip:** As a best practice, create an attribute that represents the ContactKey and have the SDK set a value for it. You can then query, join, or segment against it. See [Set or Clear Attributes](#set-or-clear-attributes). ## Set or Clear Attributes Only the SDK can set or clear attribute key-value pairs; you can’t set or clear them in Engagement. The attribute key can’t be a [reserved word](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_register_contacts_devices_attributes_manage.md#reserved-words), empty, or null. The attribute value can’t be null. The SDK trims whitespace from the beginning and end of the key and the value. ### Attribute Requirements Keep these requirements in mind when you set or clear attributes. - Specify dates in ISO 8601 format, such as `2024-05-07T13:28:31+00:00`. - If you set an attribute to a datetime stamp after the SDK successfully initializes, the registration record is updated every time the SDK initializes. - Don't create an attribute with a datetime value that constantly changes. For example, never set an attribute that tracks `LastUserInteraction`. Constantly changing attribute values negatively impacts performance. ### Manage Attributes in the SDK for Android This code example shows how to set or clear attributes in the SDK for Android. ``` SFMCSdk.requestSdk { sfmcSdk -> // GIVEN val attributesMap = mutableMapOf() attributesMap["firstName"] = "Salesforce" attributesMap["lastName"] = "Developer" val attributesToClear: List = getAttributesToClear() sfmcSdk.identity.edit { // Set Attributes attributes.put("key1", "value1") attributes.putAll(attributesMap) attributes.set(attributesMap) // Clear Attributes attributes.clear("key1") attributes.clear("key1", "key2") attributes.clear(attributesToClear) attributes.clearAll() } // Get Attributes val attributes = sfmcSdk.identity.attributes } ``` This code example shows how to set or clear attributes in the Salesforce Engagement SDK for Android apps that use SDK version 8. ``` SFMCSdk.requestSdk { sdk -> // GIVEN val attributesMap = mutableMapOf() attributesMap["firstName"] = "Salesforce" attributesMap["lastName"] = "Developer" val attributesToClear: List = getAttributesToClear() sdk.identity.run { // Setting Attributes setProfileAttribute("favoriteCRM", "Salesforce") // Set individual attributes setProfileAttributes(attributesMap) // Set multiple attributes // Clearing Attributes clearProfileAttribute("favoriteCRM") // Clear individual attributes clearProfileAttributes(attributesToClear) // Clear multiple attributes } // Getting Attributes sdk.mp { push -> val attributes = push.registrationManager.attributes } } ``` ### Manage Attributes in the SDK for iOS This code example shows how to set or clear attributes in the Salesforce Engagement SDK for iOS that use SDK version 10 or higher. ``` // Set a single attribute SFMCSdk.identity.edit { [self] model in model.addAttribute(key: "FavoriteTeamName", value: "favoriteTeamName") return model } // Set multiple attributes SFMCSdk.identity.edit { [self] model in model.addAttributes(attributes: ["FavoriteTeamName": "favoriteTeamName"]) return model } // Clear a single attribute SFMCSdk.identity.edit { [self] model in model.clearAttribute(key: "AttributeKey") return model } // Clear multiple attributes SFMCSdk.identity.edit { [self] model in model.clearAttributes(attributes: ["AttributeKey1", "AttributeKey2"]) return model } // Get all attributes let attributes = SFMCSdk.identity.get()?.attributes ``` For earlier versions of the SDK, use this code. ``` // Set an attribute for all modules let success = SFMCSdk.identity.setProfileAttributes(["FavoriteTeamName": "favoriteTeamName"]) // Set attributes for Mobile Push Module only let success = SFMCSdk.identity.setProfileAttributes([ModuleName.push: ["FavoriteTeamName": "favoriteTeamName"]]) // Set attributes individually for all modules let success = SFMCSdk.identity.setProfileAttribute("FavoriteTeamName", "favoriteTeamName") // Set attributes individually for Mobile Push Module only let success = SFMCSdk.identity.setProfileAttribute("FavoriteTeamName", "favoriteTeamName", [ModuleName.push]) // Clear a single attribute SFMCSdk.identity.clearProfileAttribute(key: "AttributeKey") // Clear multiple attributes SFMCSdk.identity.clearProfileAttributes(keys: ["AttributeKey1", "AttributeKey2"]) // Get all attributes SFMCSdk.requestPushSdk { mp in let attributes = mp.attributes() } ``` ## Manage Tags If you want your app to use tags, use the SDK to add or remove them. Tags can’t be empty or `null`. The SDK trims whitespace from the beginning and end of the tag. This code example shows how to add or remove tags in the SDK for Android. ``` MarketingCloudSdk.requestSdk { engagementSdk -> // GIVEN val tagsToAdd: List = getTagsToAdd() val tagsToRemove: List = getTagsToRemove() engagementSdk.registrationManager.edit().run { // Adding Tags addTags("tag1") addTags("tag2", "tag3") addTags(tagsToAdd) // Removing Tags removeTags("tag1") removeTags("tag2", "tag3") removeTags(tagsToRemove) clearTags() // Commit changes commit() } // Getting Tags val tags = engagementSdk.registrationManager.tags } ``` This code example shows how to add or remove tags in the SDK for Android apps that use SDK version 8. ``` SFMCSdk.requestSdk { sdk -> // GIVEN val tagsToAdd: List = getTagsToAdd() val tagsToRemove: List = getTagsToRemove() sdk.mp { it.registrationManager.edit().run { // Adding Tags addTags("tag1", "tag2", "tag3") addTags(tagsToAdd) // Removing Tags removeTags("tag1", "tag2") removeTags(tagsToRemove) clearTags() // Commit changes commit() } // Getting Tags val tags = it.registrationManager.tags } } ``` This code example shows how to add or remove tags in the SDK for iOS version 10 or higher. ``` MarketingCloudSdk.requestSdk { mc in // Add a tag mc?.addTag("Hiking Supplies") // Remove a tag mc?.removeTag("Boating Gear") // Get all tags let tags = mc?.tags() } ``` This code example shows how to add or remove tags on earlier versions of the SDK for iOS. ``` SFMCSdk.requestPushSdk { mp in // Add a tag mp.addTag("Hiking Supplies") // Remove a tag mp.removeTag("Boating Gear") // Get all tags let tags = mp.tags() } ``` # Set Contact Attributes in Android Apps that use SDK Version 10 The process for setting contact attributes has been updated in version 10 of the SDK. To upgrade your app to version 10 of the SDK, first [update the initialization code](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v10.md). Then, use this code example to update the contact attribute setting code in your app. ```kotlin SFMCSdk.requestSdk { sfmcSdk - > // GIVEN val attributesMap = mutableMapOf < String, String > () attributesMap["firstName"] = "Salesforce" attributesMap["lastName"] = "Developer" val attributesToClear: List < String > = getAttributesToClear() sfmcSdk.identity.edit { // Setting Attributes attributes.put("key1", "value1") attributes.putAll(attributesMap) attributes.set(attributesMap) // Clearing Attributes attributes.clear("key1") attributes.clear("key1", "key2") attributes.clear(attributesToClear) attributes.clearAll() } // Getting Attributes val attributes = sfmcSdk.identity.attributes } ``` # Set Contact Attributes in iOS Apps that use SDK Version 10 The process for setting contact attributes has been updated in version 10 of the SDK. To upgrade your app to version 10 of the SDK, first [update the initialization code](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v10.md). Then, use this code example to update the contact attribute setting code in your app. ```swift // Set a single attribute SFMCSdk.identity.edit { [self] model in model.addAttribute(key: "FavoriteTeamName", value: "favoriteTeamName") return model } // Set multiple attributes SFMCSdk.identity.edit { [self] model in model.addAttributes(attributes: ["FavoriteTeamName": "favoriteTeamName"]) return model } // Clear a single attribute SFMCSdk.identity.edit { [self] model in model.clearAttribute(key: "AttributeKey") return model } // Clear multiple attributes SFMCSdk.identity.edit { [self] model in model.clearAttributes(attributes: ["AttributeKey1", "AttributeKey2"]) return model } // Get all attributes let attributes = SFMCSdk.identity.get()?.attributes ``` # Set Contact Tags in Android Apps that Use SDK Version 10 The process for setting contact tags has been updated in version 10 of the SDK. To upgrade your app to version 10 of the SDK, first [update the initialization code](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v10.md) -->. Then, use this code example to update the contact tag setting code in your app. ```kotlin MarketingCloudSdk.requestSdk { engagementSdk - > // GIVEN val tagsToAdd: List < String > = getTagsToAdd() val tagsToRemove: List < String > = getTagsToRemove() engagementSdk.registrationManager.edit().run { // Adding Tags addTags("tag1") addTags("tag2", "tag3") addTags(tagsToAdd) // Removing Tags removeTags("tag1") removeTags("tag2", "tag3") removeTags(tagsToRemove) clearTags() // Commit changes commit() } // Getting Tags val tags = engagementSdk.registrationManager.tags } ``` # Set Contact Tags in iOS Apps that use SDK Version 10 The process for setting contact tags has been updated in version 10 of the SDK. To upgrade your app to version 10 of the SDK, first [update the initialization code](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v10.md). Then, use this code example to update the contact tag setting code in your app. ```swift MarketingCloudSdk.requestSdk { mc in // Add a tag mc?.addTag("Hiking Supplies") // Remove a tag mc?.removeTag("Boating Gear") // Get all tags let tags = mc?.tags() } ``` # Set Individual Attributes Attributes are key-value pairs that you can use to segment your audience and personalize your messages. Examples of attributes include first name, last name, loyalty level, channel preference, signup date, birthday, ZIP code, or a unique identifier. ## Manage Attributes in the Mobile App Messaging SDK for Android This code example shows how to set, clear, and retrieve attributes in the Mobile App Messaging SDK for Android. ```javascript SFMCSdk.requestSdk { sfmcSdk -> // Set/Update values in identity sfmcSdk.identity.edit { // add/update attributes to identity attributes.put("key", "value") attributes.putAll(mapOf("key1".to("value1"), "key2".to("value2"))) // set/replace attributes in identity attributes.set("key3", "value3") attributes.set(mapOf("key1".to("value1"), "key2".to("value2"))) // clearing attributes in identity attributes.clear("key") attributes.clear("key", "key1") attributes.clearAll() } // Read values from Identity val attributes = sfmcSdk.identity.attributes } ``` ## Manage Attributes in the Mobile App Messaging SDK for iOS This code example shows how to set, clear, and retrieve attributes in the Mobile App Messaging SDK for iOS. ```swift // Set a single attribute SFMCSdk.identity.edit { [self] model in model.addAttribute(key: "FavoriteTeamName", value: "favoriteTeamName") return model } // Set multiple attributes SFMCSdk.identity.edit { [self] model in model.addAttributes(attributes: ["FavoriteTeamName": "favoriteTeamName"]) return model } // Clear a single attribute SFMCSdk.identity.edit { [self] model in model.clearAttribute(key: "AttributeKey") return model } // Clear multiple attributes SFMCSdk.identity.edit { [self] model in model.clearAttributes(attributes: ["AttributeKey1", "AttributeKey2"]) return model } // Get all attributes let attributes = SFMCSdk.identity.get()?.attributes ``` # Set or Clear Attributes Use the Salesforce Engagement SDK to set or clear attribute key-value pairs. ::::::tabset{tabs='["Android SDK v10+", "iOS SDK v10+", "Android SDK v8", "iOS SDK v8"]'} :::::tab This code example shows how to set or clear attributes in the SDK for Android. ```java SFMCSdk.requestSdk { sfmcSdk -> // GIVEN val attributesMap = mutableMapOf() attributesMap["firstName"] = "Salesforce" attributesMap["lastName"] = "Developer" val attributesToClear: List = getAttributesToClear() sfmcSdk.identity.edit { // Set Attributes attributes.put("key1", "value1") attributes.putAll(attributesMap) attributes.set(attributesMap) // Clear Attributes attributes.clear("key1") attributes.clear("key1", "key2") attributes.clear(attributesToClear) attributes.clearAll() } // Get Attributes val attributes = sfmcSdk.identity.attributes } ``` ::::: :::::tab This code example shows how to set or clear attributes in the SDK for iOS version 10 and later. ```swift // Set a single attribute SFMCSdk.identity.edit { [self] model in model.addAttribute(key: "FavoriteTeamName", value: "favoriteTeamName") return model } // Set multiple attributes SFMCSdk.identity.edit { [self] model in model.addAttributes(attributes: ["FavoriteTeamName": "favoriteTeamName"]) return model } // Clear a single attribute SFMCSdk.identity.edit { [self] model in model.clearAttribute(key: "AttributeKey") return model } // Clear multiple attributes SFMCSdk.identity.edit { [self] model in model.clearAttributes(attributes: ["AttributeKey1", "AttributeKey2"]) return model } // Get all attributes let attributes = SFMCSdk.identity.get()?.attributes ``` ::::: :::::tab This code example shows how to set or clear attributes in the SDK for Android version 8. ```java SFMCSdk.requestSdk { sdk -> // GIVEN val attributesMap = mutableMapOf() attributesMap["firstName"] = "Salesforce" attributesMap["lastName"] = "Developer" val attributesToClear: List = getAttributesToClear() sdk.identity.run { // Setting Attributes setProfileAttribute("favoriteCRM", "Salesforce") // Set individual attributes setProfileAttributes(attributesMap) // Set multiple attributes // Clearing Attributes clearProfileAttribute("favoriteCRM") // Clear individual attributes clearProfileAttributes(attributesToClear) // Clear multiple attributes } // Getting Attributes sdk.mp { push -> val attributes = push.registrationManager.attributes } } ``` ::::: :::::tab For earlier versions of the SDK for iOS, use this code. ```swift // Set an attribute for all modules let success = SFMCSdk.identity.setProfileAttributes(["FavoriteTeamName": "favoriteTeamName"]) // Set attributes for Mobile Push Module only let success = SFMCSdk.identity.setProfileAttributes([ModuleName.push: ["FavoriteTeamName": "favoriteTeamName"]]) // Set attributes individually for all modules let success = SFMCSdk.identity.setProfileAttribute("FavoriteTeamName", "favoriteTeamName") // Set attributes individually for Mobile Push Module only let success = SFMCSdk.identity.setProfileAttribute("FavoriteTeamName", "favoriteTeamName", [ModuleName.push]) // Clear a single attribute SFMCSdk.identity.clearProfileAttribute(key: "AttributeKey") // Clear multiple attributes SFMCSdk.identity.clearProfileAttributes(keys: ["AttributeKey1", "AttributeKey2"]) // Get all attributes SFMCSdk.requestPushSdk { mp in let attributes = mp.attributes() } ``` ::::: :::::: ## Considerations for Managing Attributes Keep these requirements in mind when you set or clear attributes. - The attribute key can’t be a [reserved word](#reserved-words), empty, or null. - The attribute value can’t be null. - The SDK trims whitespace from the beginning and end of the key and the value. - Specify dates in ISO 8601 format, such as `2024-05-07T13:28:31+00:00`. - If you set an attribute to a datetime stamp after the SDK successfully initializes, the registration record is updated every time the SDK initializes. - Don't create an attribute with a datetime value that changes regularly. For example, don’t set an attribute that tracks `LastUserInteraction`. Frequently changing attribute values has a negative impact on performance. ## Reserved Words Some words are reserved and can’t be used as attribute names. The SDK ignores attempts to set or clear attributes that contain any of these words. - `addressId` - `alias` - `apId` - `backgroundRefreshEnabled` - `badge` - `channel` - `contactId` - `contactKey` - `createdBy` - `createdDate` - `customObjectKey` - `device` - `deviceId` - `deviceType` - `gcmSenderId` - `hardwareId` - `hwid` - `isHonorDst` - `lastAppOpen` - `lastMessageOpen` - `lastSend` - `locationEnabled` - `messageOpenCount` - `modifiedBy` - `modifiedDate` - `optInDate` - `optInMethodId` - `optInStatusId` - `optOutDate` - `optOutMethodId` - `optOutStatusId` - `platform` - `platformVersion` - `providerToken` - `proximityEnabled` - `pushAddressExtensionId` - `pushApplicationId` - `quietPushEnabled` - `sdkVersion` - `sendCount` - `signedString` - `source` - `sourceObjectId` - `status` - `systemToken` - `timezone` - `utcOffset` # Set Runtime Toggles in Android Apps that Use SDK Version 10 The process of modifying runtime toggles has changed in version 10 of the SDK. To upgrade your app to version 10 of the SDK, first [update the initialization code](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v10.md) -->. Then, use this code example to update the runtime toggles code in your app. ```kotlin MarketingCloudSdk.requestSdk { engagementSdk -> /*************/ /* Analytics */ /*************/ // Enable analytics engagementSdk.analyticsManager.enableAnalytics() // Disable analytics engagementSdk.analyticsManager.disableAnalytics() // Check if analytics is enabled engagementSdk.analyticsManager.areAnalyticsEnabled() /*************************************/ /* Predictive Intelligence Analytics */ /*************************************/ // Enable predictive intelligence analytics engagementSdk.analyticsManager.enablePiAnalytics() // Disable predictive intelligence analytics engagementSdk.analyticsManager.disablePiAnalytics() // Check if predictive intelligence analytics is enabled engagementSdk.analyticsManager.arePiAnalyticsEnabled() /*******************/ /* Inbox Messaging */ /*******************/ // Enable inbox messaging engagementSdk.inboxMessageManager.enableInbox() // Disable inbox messaging engagementSdk.inboxMessageManager.disableInbox() // Check if inbox messaging is enabled engagementSdk.inboxMessageManager.isInboxEnabled() /**********************/ /* Geofence Messaging */ /**********************/ // Enable geofence messaging engagementSdk.regionMessageManager.enableGeofenceMessaging() // Disable geofence messaging engagementSdk.regionMessageManager.disableGeofenceMessaging() // Check if geofence messaging is enabled engagementSdk.regionMessageManager.isGeofenceMessagingEnabled() /**********************/ /* Proximity Messaging */ /**********************/ // Enable proximity messaging engagementSdk.regionMessageManager.enableProximityMessaging() // Disable proximity messaging engagementSdk.regionMessageManager.disableProximityMessaging() // Check if proximity messaging is enabled engagementSdk.regionMessageManager.isProximityMessagingEnabled() } ``` # Set Runtime Toggles in iOS Apps that use SDK Version 10 The process of modifying runtime toggles has changed in version 10 of the SDK. To upgrade your app to version 10 of the SDK, first [update the initialization code](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v10.md). Then, use this code example to update the runtime toggles code in your app. ```swift MarketingCloudSdk.requestSdk { mc in //Analytics mc?.setAnalyticsEnabled(_: Bool) mc?.isAnalyticsEnabled() mc?.setPiAnalyticsEnabled(_: Bool) mc?.isPiAnalyticsEnabled() //Messaging mc?.setLocationEnabled(_: Bool) mc?.isLocationEnabled() mc?.setInboxEnabled(_: Bool) mc?.isInboxEnabled() } ``` # Set Status Bar Color Configure your app so that the Android OS matches the color scheme of your app. The SDK doesn’t use [AppCompatActivity](https://developer.android.com/reference/androidx/appcompat/app/AppCompatActivity). As a result, the OS doesn’t inherit the status bar of your app color automatically. Instead, you must define a custom status bar color. The SDK applies this color on Android 5 (Lollipop) and later. ::::::tabset{tabs='["SDK v11", "SDK v10", "SDK v8", "SDK v7"]'} :::::tab Use this code to set the status bar color in version 11 of the SDK for Android. ```java // set at configuration time SFMCSdk.configure(applicationContext as Application, SFMCSdkModuleConfig.build { inAppMessagingFeatureModuleConfig = InAppMessagingFeatureConfig.builder().apply { setStatusBarColor( ContextCompat.getColor(this as Context, R.color.colorPrimary) ) }.build() }) // OR set after configuration time InAppMessagingFeature.requestSdk { inAppMessagingFeatureModule -> inAppMessagingFeatureModule.getInAppMessageManager().setStatusBarColor( ContextCompat.getColor(this as Context, R.color.colorPrimary) ) } ``` ::::: :::::tab Use this code to set the status bar color in version 10 of the SDK for Android. ```java MarketingCloudSdk.requestSdk { engagementSdk -> engagementSdk.inAppMessageManager.setStatusBarColor( ContextCompat.getColor(this as Context, R.color.colorPrimary) ) } ``` ::::: :::::tab Use this code to set the status bar color in version 8 of the SDK for Android. ```java SFMCSdk.requestSdk { sdk -> sdk.mp { it.inAppMessageManager.setStatusBarColor( ContextCompat.getColor(this as Context, R.color.colorPrimary) ) } } ``` ::::: :::::tab Use this code to set the status bar color in version 7 of the SDK for Android. ```java MarketingCloudSdk.requestSdk { sdk-> sdk.inAppMessageManager.setStatusBarColor( ContextCompat.getColor(this as Context, R.color.colorPrimary) ) } ``` ::::: :::::: # Set the Contact Key To set the contact key, add the appropriate request to your app. In these code examples, replace `user@example.com` with the contact key you want to use. **note:** To send messages to anonymous users only, skip this step. The contact key for an anonymous user is a random GUID. ::::::tabset{tabs='["Android SDK v10+", "iOS SDK 10+", "Earlier Android SDKs", "Earlier iOS SDKs"]'} :::::tab If you use version 10 or later of the SDK, use this code. ```java SFMCSdk.requestSdk { sfmcSdk -> // Set contact key/profileId for all modules sfmcSdk.identity.edit { profileId = "uniquelyIdentifyingKey" } // Retrieve the contact key val profileId = sfmcSdk.identity.profileId } ``` ::::: :::::tab For version 10 or later of the iOS SDK, use this code. ```swift // Set contact key for mobile push module SFMCSdk.identity.edit { [self] model in model.profileId = "user@example.com" return model } // Retrieve the contact key SFMCSdk.identity.get()?.profileId ``` ::::: :::::tab For earlier versions of the Android SDK, use this code. ```java SFMCSdk.requestSdk { sfmcSdk -> // Set contact key for all modules sfmcSdk.identity.setProfileId("uniquelyIdentifyingKey") // OR set contact key only for the Mobile Push module sfmcSdk.identity.setProfileId("uniquelyIdentifyingKey", ModuleIdentifier.PUSH) // Retrieve the contact key sfmcSdk.mp { val contactKey = it.moduleIdentity.profileId } } ``` ::::: :::::tab For earlier versions of the iOS SDK, use this code. ```swift // Set contact key for all modules SFMCSdk.identity.setProfileId("user@example.com") // OR set contact key only for the Mobile Push module SFMCSdk.identity.setProfileId([ModuleName.push: "user@example.com"]) // Retrieve the contact key SFMCSdk.requestPushSdk { mp in let contactKey = mp.contactKey() } ``` ::::: :::::: # Set the Party Identifier The party identifier is a unique identifier that represents an individual in Marketing Cloud. It can be a customer ID, mobile number, email address, loyalty number, or another value. **note:** Skip this step if you want to send only to anonymous users. For an anonymous user, the party identifier is a random GUID. To set the party identifier for Android apps, use this code example. ```java SFMCSdk.requestSdk { sfmcSdk -> // Set/Update values in identity sfmcSdk.identity.edit { partyIdentificationNumber = "uniquelyIdentifyingNumber" partyIdentificationName = "uniquelyIdentifyingName" partyIdentificationType = "uniquelyIdentifyingType" } // Read values from Identity val partyIdentificationNumber = sfmcSdk.identity.partyIdentificationNumber val partyIdentificationName = sfmcSdk.identity.partyIdentificationName val partyIdentificationType = sfmcSdk.identity.partyIdentificationType } ``` To set the party identifier for iOS apps, use this code example. ```swift // Set party details for all modules SFMCSdk.identity.edit { [self] model in model.partyIdentificationNumber = "uniquelyIdentifyingNumber" model.partyIdentificationName = "uniquelyIdentifyingName" model.partyIdentificationType = "uniquelyIdentifyingType" return model } // Retrieve the party details let partyIdentificationNumber = SFMCSdk.identity.get()?.partyIdentificationNumber let partyIdentificationName = SFMCSdk.identity.get()?.partyIdentificationName let partyIdentificationType = SFMCSdk.identity.get()?.partyIdentificationType ``` **tip:** Optimize API calls to Marketing Cloud Next by updating the locally stored Individual record only when your app is in the foreground. If your app is in the background, the SDK initializes to show a notification or to pre-cache messages, resulting in unnecessary communication with Marketing Cloud Next. # setAnalyticsEnabled Enables or disables analytics in the native MobilePush SDK. ## Syntax `MCCordovaPlugin.setAnalyticsEnabled(enabled, [successCallback], [errorCallback])` ## Kind Static method of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | ----------------- | ---------- | --------------------------- | | `enabled` | `boolean` | Whether to enable analytics | | `successCallback` | `function` | | | `errorCallback` | `function` | | # setAnalyticsEnabled Enables or disables analytics tracking for the SDK. ## Syntax ```dart Future setAnalyticsEnabled(bool analyticsEnabled) ``` ## Parameters - `analyticsEnabled` (bool) - `true` to enable analytics, `false` to disable ## Returns - `Future` - Completes when the analytics setting has been updated. ## Example ```dart try { await SfmcSdk.setAnalyticsEnabled(true); print('Analytics enabled'); } catch (e) { print('Failed to set analytics: $e'); } ``` ## Related Methods - [isAnalyticsEnabled()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_isAnalyticsEnabled.md) # setAnalyticsEnabled Enables or disables analytics in the MobilePush SDK. ## Syntax ```javascript MCReactModule.setAnalyticsEnabled(analyticsEnabled); ``` ## Parameters | Parameter | Type | Description | | ------------------ | --------- | ---------------------------------------------- | | `analyticsEnabled` | `boolean` | A flag indicating whether to enable analytics. | ## Returns - `void` - No return value. ## Example ```javascript import { MCReactModule } from "react-native-marketingcloudsdk"; const toggleAnalytics = (enabled) => { try { MCReactModule.setAnalyticsEnabled(enabled); console.log(`Analytics ${enabled ? "enabled" : "disabled"}`); } catch (error) { console.error("Error setting analytics:", error); } }; ``` ## See Also - [Runtime Toggles](/docs/marketing/mobilepush/guide/runtime-toggles.html) ## Related Methods - [isAnalyticsEnabled()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_isAnalyticsEnabled.md) # setAttribute Sets the value of an attribute in the registration. ## Syntax `MCCordovaPlugin.setAttribute(key, value, [successCallback], [errorCallback])` ## Kind Static method of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | ----------------------- | ---------- | --------------------------------------------------------------- | | `key` | `string` | The name of the attribute to be set in the registration. | | `value` | `string` | The value of the `key` attribute to be set in the registration. | | `successCallback` | `function` | | | `successCallback.saved` | `boolean` | Whether the attribute value was set in the registration. | | `errorCallback` | `function` | | # setAttribute Sets a custom attribute for the device. ## Syntax ```dart Future setAttribute(String key, Object? value) ``` ## Parameters - `key` (String) - The attribute key - `value` (Object?) - The attribute value ## Returns - `Future` - Completes when the attribute has been set. ## Example ```dart try { await SfmcSdk.setAttribute('userType', 'premium'); await SfmcSdk.setAttribute('lastLogin', DateTime.now().toIso8601String()); print('Attributes set successfully'); } catch (e) { print('Failed to set attribute: $e'); } ``` ## Related Methods - [getAttributes()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getAttributes.md) - [clearAttribute()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_clearAttribute.md) # setAttribute Sets the value of an attribute in the registration. ## Syntax ```javascript MCReactModule.setAttribute(key, value); ``` ## Parameters | Parameter | Type | Description | | --------- | -------- | --------------------------------------------------------------- | | `key` | `string` | The name of the attribute to be set in the registration. | | `value` | `string` | The value of the `key` attribute to be set in the registration. | ## Returns - `void` - No return value. ## Example ```javascript import { MCReactModule } from "react-native-marketingcloudsdk"; const setUserAttribute = () => { try { MCReactModule.setAttribute("userType", "premium"); MCReactModule.setAttribute("lastLogin", new Date().toISOString()); console.log("Attributes set successfully"); } catch (error) { console.error("Error setting attribute:", error); } }; ``` ## See Also - [getAttributes() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_getAttributes.md) - [clearAttribute() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_clearAttribute.md) - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/8.0/-s-f-m-c%20-s-d-k/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity/set-profile-attribute.html) - _SDK Reference for iOS_: [Identity Class](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/ios-sdk-v11/sfmc-sdk/classes/identity.md) # setContactKey Sets the contact key for the device's user. ## Syntax `MCCordovaPlugin.setContactKey(contactKey, [successCallback], [errorCallback])` ## Kind Static method of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | ----------------------- | ---------- | --------------------------------------------------------------------------- | | `contactKey` | `string` | The value to be set as the contact key of the device's user. | | `successCallback` | `function` | | | `successCallback.saved` | `boolean` | Whether the value passed in for `contactKey` was saved in the registration. | | `errorCallback` | `function` | | # setContactKey Sets the contact key for the device to associate it with a specific contact in Marketing Cloud. ## Syntax ```dart Future setContactKey(String contactKey) ``` ## Parameters - `contactKey` (String) - The unique identifier for the contact ## Returns - `Future` - Completes when the contact key has been set. ## Example ```dart try { await SfmcSdk.setContactKey('user123@example.com'); print('Contact key set successfully'); } catch (e) { print('Failed to set contact key: $e'); } ``` ## Related Methods - [getContactKey()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_getContactKey.md) # setContactKey Sets the contact key for the device's user. ## Syntax ```javascript MCReactModule.setContactKey(contactKey); ``` ## Parameters | Parameter | Type | Description | | ------------ | -------- | ------------------------------------------------------------ | | `contactKey` | `string` | The value to be set as the contact key of the device's user. | ## Returns - `void` - No return value. ## Example ```javascript import { MCReactModule } from "react-native-marketingcloudsdk"; const setUserContactKey = () => { try { MCReactModule.setContactKey("user123@example.com"); console.log("Contact key set successfully"); } catch (error) { console.error("Error setting contact key:", error); } }; ``` ## See Also - [getContactKey() Method](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_getContactKey.md) - _SDK Reference for Android_:[Identity Class](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/8.0/-s-f-m-c%20-s-d-k/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity/set-profile-id.html) - _SDK Reference for iOS_: [Identity Class](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/ios-sdk-v11/sfmc-sdk/classes/identity.md) # setMessageRead Marks a specific inbox message as read. ## Syntax ```dart Future setMessageRead(String messageId) ``` ## Parameters - `messageId` (String) - The unique identifier of the message to mark as read ## Returns - `Future` - Completes when the message has been marked as read. ## Example ```dart try { await SfmcSdk.setMessageRead('msg123'); print('Message marked as read'); } catch (e) { print('Failed to mark message as read: $e'); } ``` ## Related Methods - [deleteMessage()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_deleteMessage.md) - [markAllMessagesRead()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_markAllMessagesRead.md) # setOnNotificationOpenedListener Sets a listener for notification opened events. **note:** This method is available in MobilePush SDK version 6.1.0 and later. ## Syntax `MCCordovaPlugin.setOnNotificationOpenedListener(notificationOpenedListener)` ## Kind Static method of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | ---------------------------------- | ------------------------------------------ | ----------- | | `notificationOpenedListener` | function | | | `notificationOpenedListener.event` | MCCordovaPlugin~notificationOpenedCallback | | # setOnUrlActionListener Sets a listener for URL actions. **note:** This method is available in MobilePush SDK version 6.3.0 and later. ## Syntax `MCCordovaPlugin.setOnUrlActionListener(urlActionListener)` ## Kind Static method of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | ------------------------- | ----------------------------------- | ----------- | | `urlActionListener` | `function` | | | `urlActionListener.event` | `MCCordovaPlugin~urlActionCallback` | | # setPiAnalyticsEnabled Enables or disables Predictive Intelligence (PI) analytics in the native MobilePush SDK. ## Syntax `MCCordovaPlugin.setPiAnalyticsEnabled(enabled, [successCallback], [errorCallback])` ## Kind Static method of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | ----------------- | ---------- | -------------------------------------------------------- | | `enabled` | `boolean` | Whether to enable Predictive Intelligence (PI) analytics | | `successCallback` | `function` | | | `errorCallback` | `function` | | # setPiAnalyticsEnabled Enables or disables PI (Predictive Intelligence) analytics tracking for the SDK. ## Syntax ```dart Future setPiAnalyticsEnabled(bool analyticsEnabled) ``` ## Parameters - `analyticsEnabled` (bool) - `true` to enable PI analytics, `false` to disable ## Returns - `Future` - Completes when the PI analytics setting has been updated. ## Example ```dart try { await SfmcSdk.setPiAnalyticsEnabled(true); print('PI Analytics enabled'); } catch (e) { print('Failed to set PI analytics: $e'); } ``` ## Related Methods - [isPiAnalyticsEnabled()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_isPiAnalyticsEnabled.md) # setPiAnalyticsEnabled Enables or disables Predictive Intelligence (PI) analytics in the MobilePush SDK. ## Syntax ```javascript MCReactModule.setPiAnalyticsEnabled(analyticsEnabled); ``` ## Parameters | Parameter | Type | Description | | ------------------ | --------- | ------------------------------------------------- | | `analyticsEnabled` | `boolean` | A flag indicating whether to enable PI analytics. | ## Returns - `void` - No return value. ## Example ```javascript import { MCReactModule } from "react-native-marketingcloudsdk"; const togglePiAnalytics = (enabled) => { try { MCReactModule.setPiAnalyticsEnabled(enabled); console.log(`PI Analytics ${enabled ? "enabled" : "disabled"}`); } catch (error) { console.error("Error setting PI analytics:", error); } }; ``` ## See Also - [Runtime Toggles](/docs/marketing/mobilepush/guide/runtime-toggles.html) ## Related Methods - [isPiAnalyticsEnabled()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react_isPiAnalyticsEnabled.md) # SFContentExtensionConfig `Class` The configuration class for content extensions. `SFContentExtensionConfig` provides settings to control logging behavior and request timeouts within the content extension. ## Declaration ```swift @objc(SFMCContentExtensionConfig) public final class SFContentExtensionConfig : NSObject @objc public let logLevel: LogLevel @objc public let timeoutIntervalForRequest: TimeInterval @objc public init(logLevel: LogLevel = .none, timeoutIntervalForRequest: TimeInterval) ``` ## Cases ### `logLevel` This determines the verbosity of log messages generated within the content extension. Default value is `.none` @see LogLevel. ```swift @objc public let logLevel: LogLevel ``` --- ### `timeoutIntervalForRequest` The timeout interval for network requests. Default value is 15 seconds. ```swift @objc public let timeoutIntervalForRequest: TimeInterval ``` --- ### `init(logLevel:timeoutIntervalForRequest:)` Initializes the content extension configuration. ```swift @objc public init(logLevel: LogLevel = .none, timeoutIntervalForRequest: TimeInterval) ``` --- # SFMC Core This section provides API reference details for the SFMC Core module in the Flutter unified plugin. ## setProfileId Sets the profile identifier for the device's user. ### Syntax ```dart SFMCSdkModule.setProfileId(profileId); ``` ### Parameters | Parameter | Type | Description | | ----------- | -------- | -------------------------------------------------------- | | `profileId` | `String` | The value to set as the profile ID of the device's user. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_core/sfmc_core.dart'; await SFMCSdkModule.requestSdk(); await SFMCSdkModule.setProfileId('user-1234'); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity-editor/profile-id.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityModifier.html#/c:@M@SFMCSDK@objc(pl)SFIdentityModifier(py)profileId>) ## getProfileId Returns the profile identifier for the device. ### Syntax ```dart SFMCSdkModule.getProfileId(); ``` ### Returns - `Future` - A future that completes with the current profile ID. ### Example ```dart import 'package:sfmc_core/sfmc_core.dart'; await SFMCSdkModule.requestSdk(); final profileId = await SFMCSdkModule.getProfileId(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity/profile-id.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityInfo.html#/c:@M@SFMCSDK@objc(pl)SFIdentityInfo(py)profileId>) ## setAttribute Sets the value of an attribute in the identity. ### Syntax ```dart SFMCSdkModule.setAttribute(key, value); ``` ### Parameters | Parameter | Type | Description | | --------- | -------- | ---------------------------------- | | `key` | `String` | The name of the attribute to set. | | `value` | `String` | The value of the attribute to set. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_core/sfmc_core.dart'; await SFMCSdkModule.requestSdk(); await SFMCSdkModule.setAttribute('email', 'sample@example.com'); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-attributes-editor/put.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityModifier.html#/c:@M@SFMCSDK@objc(pl)SFIdentityModifier(im)addAttributeWithKey:value:>) ## clearAttribute Clears the value of an attribute in the identity. ### Syntax ```dart SFMCSdkModule.clearAttribute(key); ``` ### Parameters | Parameter | Type | Description | | --------- | -------- | ------------------------------------------------ | | `key` | `String` | The name of the attribute to clear the value of. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_core/sfmc_core.dart'; await SFMCSdkModule.requestSdk(); await SFMCSdkModule.clearAttribute('email'); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-attributes-editor/clear.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityModifier.html#/c:@M@SFMCSDK@objc(pl)SFIdentityModifier(im)clearAttributeWithKey:>) ## setAttributes Sets multiple attributes in the identity in one call. ### Syntax ```dart SFMCSdkModule.setAttributes(attributes); ``` ### Parameters | Parameter | Type | Description | | ------------ | --------------------- | -------------------------------- | | `attributes` | `Map` | A map of key-value pairs to set. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_core/sfmc_core.dart'; await SFMCSdkModule.requestSdk(); await SFMCSdkModule.setAttributes({ 'email': 'sample@example.com', 'tier': 'gold', }); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-attributes-editor/set.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityModifier.html#/c:@M@SFMCSDK@objc(pl)SFIdentityModifier(im)addAttributesWithAttributes:>) ## getAttributes Returns a map of attributes for the identity. ### Syntax ```dart SFMCSdkModule.getAttributes(); ``` ### Returns - `Future?>` - A future that completes with the current attribute map. ### Example ```dart import 'package:sfmc_core/sfmc_core.dart'; await SFMCSdkModule.requestSdk(); final attributes = await SFMCSdkModule.getAttributes(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity/attributes.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityInfo.html#/c:@M@SFMCSDK@objc(pl)SFIdentityInfo(py)attributes>) ## clearAllAttributes Clears all attributes from the identity. ### Syntax ```dart SFMCSdkModule.clearAllAttributes(); ``` ### Returns - `Future` ### Example ```dart import 'package:sfmc_core/sfmc_core.dart'; await SFMCSdkModule.requestSdk(); await SFMCSdkModule.clearAllAttributes(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity/-builder/clear-attributes.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityModifier.html#/c:@M@SFMCSDK@objc(pl)SFIdentityModifier(im)clearAllAttributes>) ## getPartyIdentificationName Returns the party identification name currently for the device. ### Syntax ```dart SFMCSdkModule.getPartyIdentificationName(); ``` ### Returns - `Future` - A future that completes with the current party identification name. ### Example ```dart import 'package:sfmc_core/sfmc_core.dart'; await SFMCSdkModule.requestSdk(); final partyName = await SFMCSdkModule.getPartyIdentificationName(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity/party-identification-name.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityInfo.html#/c:@M@SFMCSDK@objc(pl)SFIdentityInfo(py)partyIdentificationName>) ## setPartyIdentificationName Sets the party identification name for the device's user. ### Syntax ```dart SFMCSdkModule.setPartyIdentificationName(name); ``` ### Parameters | Parameter | Type | Description | | --------- | -------- | ------------------------------------------ | | `name` | `String` | The display name or full name of the user. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_core/sfmc_core.dart'; await SFMCSdkModule.requestSdk(); await SFMCSdkModule.setPartyIdentificationName('Jane Doe'); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity-editor/party-identification-name.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityModifier.html#/c:@M@SFMCSDK@objc(pl)SFIdentityModifier(py)partyIdentificationName>) ## getPartyIdentificationNumber Returns the party identification number of the device. ### Syntax ```dart SFMCSdkModule.getPartyIdentificationNumber(); ``` ### Returns - `Future` - A future that completes with the current party identification number. ### Example ```dart import 'package:sfmc_core/sfmc_core.dart'; await SFMCSdkModule.requestSdk(); final partyNumber = await SFMCSdkModule.getPartyIdentificationNumber(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity/party-identification-number.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityInfo.html#/c:@M@SFMCSDK@objc(pl)SFIdentityInfo(py)partyIdentificationNumber>) ## setPartyIdentificationNumber Sets the party identification number for the device's user. ### Syntax ```dart SFMCSdkModule.setPartyIdentificationNumber(number); ``` ### Parameters | Parameter | Type | Description | | --------- | -------- | ---------------------------------------- | | `number` | `String` | A unique identifier number for the user. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_core/sfmc_core.dart'; await SFMCSdkModule.requestSdk(); await SFMCSdkModule.setPartyIdentificationNumber('PID-1001'); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity-editor/party-identification-number.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityModifier.html#/c:@M@SFMCSDK@objc(pl)SFIdentityModifier(py)partyIdentificationNumber>) ## getPartyIdentificationType Returns the party identification type currently set on the device. ### Syntax ```dart SFMCSdkModule.getPartyIdentificationType(); ``` ### Returns - `Future` - A future that completes with the current party identification type. ### Example ```dart import 'package:sfmc_core/sfmc_core.dart'; await SFMCSdkModule.requestSdk(); final partyType = await SFMCSdkModule.getPartyIdentificationType(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity/party-identification-type.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityInfo.html#/c:@M@SFMCSDK@objc(pl)SFIdentityInfo(py)partyIdentificationType>) ## setPartyIdentificationType Sets the party identification type for the device's user. ### Syntax ```dart SFMCSdkModule.setPartyIdentificationType(type); ``` ### Parameters | Parameter | Type | Description | | --------- | -------- | -------------------------------------------- | | `type` | `String` | The category or classification for the user. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_core/sfmc_core.dart'; await SFMCSdkModule.requestSdk(); await SFMCSdkModule.setPartyIdentificationType('customer'); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity-editor/party-identification-type.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityModifier.html#/c:@M@SFMCSDK@objc(pl)SFIdentityModifier(py)partyIdentificationType>) ## track Tracks an event, which could result in actions such as an in-app message being displayed. ### Syntax ```dart SFMCSdkModule.track(event); ``` ### Parameters | Parameter | Type | Description | | --------- | ----------- | ----------------------------------------------------------------------- | | `event` | `SFMCEvent` | An `SFMCEvent` instance to track, such as `CustomEvent` or `CartEvent`. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_core/sfmc_core.dart'; await SFMCSdkModule.requestSdk(); await SFMCSdkModule.track(CustomEvent(name: 'purchase', attributes: {'item': 'shoes'})); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk/-s-f-m-c-sdk/-companion/track.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Classes/SFMCSdk.html#/c:@CM@SFMCSDK@objc(cs)SFMCSdk(cm)trackWithEvent:>) ## sendImmediate Tracks an event and sends it immediately without waiting for the next batch cycle. ### Syntax ```dart SFMCSdkModule.sendImmediate(event); ``` ### Parameters | Parameter | Type | Description | | --------- | ----------- | ---------------------------------------------------------------------------------- | | `event` | `SFMCEvent` | An `SFMCEvent` instance to send immediately, such as `CustomEvent` or `CartEvent`. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_core/sfmc_core.dart'; await SFMCSdkModule.requestSdk(); await SFMCSdkModule.sendImmediate(CustomEvent(name: 'purchase', attributes: {'item': 'shoes'})); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk/-s-f-m-c-sdk/-companion/send-immediate.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Classes/SFMCSdk.html#/c:@CM@SFMCSDK@objc(cs)SFMCSdk(cm)sendImmediateWithEvent:>) ## flush Flushes all queued events to the Marketing Cloud servers immediately. ### Syntax ```dart SFMCSdkModule.flush(); ``` ### Returns - `Future` ### Example ```dart import 'package:sfmc_core/sfmc_core.dart'; await SFMCSdkModule.requestSdk(); await SFMCSdkModule.flush(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk/-s-f-m-c-sdk/-companion/flush.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Classes/SFMCSdk.html#/c:@CM@SFMCSDK@objc(cs)SFMCSdk(cm)flush>) ## setLogging Sets the log level for the native Marketing Cloud SDK. ### Syntax ```dart SFMCSdkModule.setLogging(level); ``` ### Parameters | Parameter | Type | Description | | --------- | ---------- | ------------------------------------------------------------------------------------------------------------- | | `level` | `LogLevel` | The SDK log level. Valid values are `LogLevel.debug`, `LogLevel.warn`, `LogLevel.error`, and `LogLevel.none`. | ### Returns - `Future` ### Example ```dart import 'package:sfmc_core/sfmc_core.dart'; await SFMCSdkModule.requestSdk(); await SFMCSdkModule.setLogging(LogLevel.debug); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.logging/-log-level/index.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Classes/SFMCSdk.html#/c:@M@SFMCSDK@objc(cs)SFMCSdk(cm)setLoggerWithLogLevel:logOutputter:>) ## getSdkState Returns the SDK state for diagnostics. ### Syntax ```dart SFMCSdkModule.getSdkState(); ``` ### Returns - `Future` - A future that completes with the state of the SDK. The state is usually returned as a `Map` object, but the native SDK can emit non-strict JSON that fails to parse. In this situation, the SDK returns the raw JSON string instead. Parse the result in a way that can handle both object types. ### Example ```dart import 'package:sfmc_core/sfmc_core.dart'; await SFMCSdkModule.requestSdk(); final state = await SFMCSdkModule.getSdkState(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk/-s-f-m-c-sdk/get-sdk-state.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Classes/SFMCSdk.html#/c:@M@SFMCSDK@objc(cs)SFMCSdk(cm)state>) # SFMC Core This section provides API reference details for SFMC Core module in React Native unified plugin. ## setProfileId Sets the profile identifier for the device user. ### Syntax ```javascript SFMCSdkModule.setProfileId(profileId); ``` ### Parameters | Parameter | Type | Description | | ----------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `profileId` | `string` | The profile ID (contact key) for the device user. Use a stable identifier, such as a CRM user ID or email-based key, so the same user is recognized across sessions. | ### Returns - `void` ### Example ```javascript import { SFMCSdkModule } from "@sfmc/react-native-sfmc-core"; import type { SFMCSdkApi } from "@sfmc/react-native-sfmc-core"; const sfmc: SFMCSdkApi = await SFMCSdkModule.requestSdk(); sfmc.setProfileId("user-1234"); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity-editor/profile-id.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityModifier.html#/c:@M@SFMCSDK@objc(pl)SFIdentityModifier(py)profileId>) ## getProfileId Returns the profile identifier currently set on the device. ### Syntax ```javascript SFMCSdkModule.getProfileId(); ``` ### Returns - `Promise` - A promise that resolves to the current profile ID. ### Example ```javascript import { SFMCSdkModule } from "@sfmc/react-native-sfmc-core"; import type { SFMCSdkApi } from "@sfmc/react-native-sfmc-core"; const sfmc: SFMCSdkApi = await SFMCSdkModule.requestSdk(); const profileId = await sfmc.getProfileId(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity/profile-id.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityInfo.html#/c:@M@SFMCSDK@objc(pl)SFIdentityInfo(py)profileId>) ## setAttribute Sets an attribute value in the device user's registration profile. ### Syntax ```javascript SFMCSdkModule.setAttribute(key, value); ``` ### Parameters | Parameter | Type | Description | | --------- | -------- | ------------------------------------------------------------------- | | `key` | `string` | The attribute name in the registration profile. | | `value` | `string` | The attribute value to assign to `key` in the registration profile. | ### Returns - `void` ### Example ```javascript import { SFMCSdkModule } from "@sfmc/react-native-sfmc-core"; import type { SFMCSdkApi } from "@sfmc/react-native-sfmc-core"; const sfmc: SFMCSdkApi = await SFMCSdkModule.requestSdk(); sfmc.setAttribute("email", "sample@example.com"); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-attributes-editor/put.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityModifier.html#/c:@M@SFMCSDK@objc(pl)SFIdentityModifier(im)addAttributeWithKey:value:>) ## setAttributes Sets multiple attribute values in the device user's registration profile in one call. ### Syntax ```javascript SFMCSdkModule.setAttributes(attributes); ``` ### Parameters | Parameter | Type | Description | | ------------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------- | | `attributes` | `object` | The key-value map of identity attributes to set in one call. Each key is an attribute name and each value is a string attribute value. | ### Returns - `void` ### Example ```javascript import { SFMCSdkModule } from "@sfmc/react-native-sfmc-core"; import type { SFMCSdkApi } from "@sfmc/react-native-sfmc-core"; const sfmc: SFMCSdkApi = await SFMCSdkModule.requestSdk(); sfmc.setAttributes({ email: "sample@example.com", tier: "gold", }); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-attributes-editor/set.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityModifier.html#/c:@M@SFMCSDK@objc(pl)SFIdentityModifier(im)addAttributesWithAttributes:>) ## clearAttribute Clears an attribute value from the device user's registration profile. ### Syntax ```javascript SFMCSdkModule.clearAttribute(key); ``` ### Parameters | Parameter | Type | Description | | --------- | -------- | ------------------------------------------------------------------------ | | `key` | `string` | The attribute name whose value is cleared from the registration profile. | ### Returns - `void` ### Example ```javascript import { SFMCSdkModule } from "@sfmc/react-native-sfmc-core"; import type { SFMCSdkApi } from "@sfmc/react-native-sfmc-core"; const sfmc: SFMCSdkApi = await SFMCSdkModule.requestSdk(); sfmc.clearAttribute("email"); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-attributes-editor/clear.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityModifier.html#/c:@M@SFMCSDK@objc(pl)SFIdentityModifier(im)clearAttributeWithKey:>) ## clearAllAttributes Clears all attributes from the device user's registration profile. ### Syntax ```javascript SFMCSdkModule.clearAllAttributes(); ``` ### Returns - `void` ### Example ```javascript import { SFMCSdkModule } from "@sfmc/react-native-sfmc-core"; import type { SFMCSdkApi } from "@sfmc/react-native-sfmc-core"; const sfmc: SFMCSdkApi = await SFMCSdkModule.requestSdk(); sfmc.clearAllAttributes(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity/-builder/clear-attributes.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityModifier.html#/c:@M@SFMCSDK@objc(pl)SFIdentityModifier(im)clearAllAttributes>) ## getAttributes Returns the attributes currently set in the device user's registration profile. ### Syntax ```javascript SFMCSdkModule.getAttributes(); ``` ### Returns - `Promise` - A promise that resolves to the attribute key-value map. ### Example ```javascript import { SFMCSdkModule } from "@sfmc/react-native-sfmc-core"; import type { SFMCSdkApi } from "@sfmc/react-native-sfmc-core"; const sfmc: SFMCSdkApi = await SFMCSdkModule.requestSdk(); const attributes = await sfmc.getAttributes(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity/attributes.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityInfo.html#/c:@M@SFMCSDK@objc(pl)SFIdentityInfo(py)attributes>) ## setPartyIdentificationName Sets the party identification name in the device user's identity profile. ### Syntax ```javascript SFMCSdkModule.setPartyIdentificationName(name); ``` ### Parameters | Parameter | Type | Description | | --------- | -------- | -------------------------------------------------- | | `name` | `string` | The party identification name for the device user. | ### Returns - `void` ### Example ```javascript import { SFMCSdkModule } from "@sfmc/react-native-sfmc-core"; import type { SFMCSdkApi } from "@sfmc/react-native-sfmc-core"; const sfmc: SFMCSdkApi = await SFMCSdkModule.requestSdk(); sfmc.setPartyIdentificationName("Jane Doe"); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity-editor/party-identification-name.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityModifier.html#/c:@M@SFMCSDK@objc(pl)SFIdentityModifier(py)partyIdentificationName>) ## setPartyIdentificationNumber Sets the party identification number in the device user's identity profile. ### Syntax ```javascript SFMCSdkModule.setPartyIdentificationNumber(numberValue); ``` ### Parameters | Parameter | Type | Description | | ------------- | -------- | ---------------------------------------------------- | | `numberValue` | `string` | The party identification number for the device user. | ### Returns - `void` ### Example ```javascript import { SFMCSdkModule } from "@sfmc/react-native-sfmc-core"; import type { SFMCSdkApi } from "@sfmc/react-native-sfmc-core"; const sfmc: SFMCSdkApi = await SFMCSdkModule.requestSdk(); sfmc.setPartyIdentificationNumber("PID-1001"); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity-editor/party-identification-number.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityModifier.html#/c:@M@SFMCSDK@objc(pl)SFIdentityModifier(py)partyIdentificationNumber>) ## setPartyIdentificationType Sets the party identification type in the device user's identity profile. ### Syntax ```javascript SFMCSdkModule.setPartyIdentificationType(type); ``` ### Parameters | Parameter | Type | Description | | --------- | -------- | -------------------------------------------------- | | `type` | `string` | The party identification type for the device user. | ### Returns - `void` ### Example ```javascript import { SFMCSdkModule } from "@sfmc/react-native-sfmc-core"; import type { SFMCSdkApi } from "@sfmc/react-native-sfmc-core"; const sfmc: SFMCSdkApi = await SFMCSdkModule.requestSdk(); sfmc.setPartyIdentificationType("customer"); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity-editor/party-identification-type.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityModifier.html#/c:@M@SFMCSDK@objc(pl)SFIdentityModifier(py)partyIdentificationType>) ## getPartyIdentificationName Returns the party identification name currently set on the device. ### Syntax ```javascript SFMCSdkModule.getPartyIdentificationName(); ``` ### Returns - `Promise` - A promise that resolves to the current party identification name. ### Example ```javascript import { SFMCSdkModule } from "@sfmc/react-native-sfmc-core"; import type { SFMCSdkApi } from "@sfmc/react-native-sfmc-core"; const sfmc: SFMCSdkApi = await SFMCSdkModule.requestSdk(); const partyName = await sfmc.getPartyIdentificationName(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity/party-identification-name.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityInfo.html#/c:@M@SFMCSDK@objc(pl)SFIdentityInfo(py)partyIdentificationName>) ## getPartyIdentificationNumber Returns the party identification number currently set on the device. ### Syntax ```javascript SFMCSdkModule.getPartyIdentificationNumber(); ``` ### Returns - `Promise` - A promise that resolves to the current party identification number. ### Example ```javascript import { SFMCSdkModule } from "@sfmc/react-native-sfmc-core"; import type { SFMCSdkApi } from "@sfmc/react-native-sfmc-core"; const sfmc: SFMCSdkApi = await SFMCSdkModule.requestSdk(); const partyNumber = await sfmc.getPartyIdentificationNumber(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity/party-identification-number.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityInfo.html#/c:@M@SFMCSDK@objc(pl)SFIdentityInfo(py)partyIdentificationNumber>) ## getPartyIdentificationType Returns the party identification type currently set on the device. ### Syntax ```javascript SFMCSdkModule.getPartyIdentificationType(); ``` ### Returns - `Promise` - A promise that resolves to the current party identification type. ### Example ```javascript import { SFMCSdkModule } from "@sfmc/react-native-sfmc-core"; import type { SFMCSdkApi } from "@sfmc/react-native-sfmc-core"; const sfmc: SFMCSdkApi = await SFMCSdkModule.requestSdk(); const partyType = await sfmc.getPartyIdentificationType(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.identity/-identity/party-identification-type.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Protocols/IdentityInfo.html#/c:@M@SFMCSDK@objc(pl)SFIdentityInfo(py)partyIdentificationType>) ## track Tracks an event, which can trigger SDK actions such as in-app message display. ### Syntax ```javascript SFMCSdkModule.track(event); ``` ### Parameters | Parameter | Type | Description | | --------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `event` | `object` | The `SFMCEvent` payload to track. Valid event types are `CustomEvent`, `EngagementEvent`, `IdentityEvent`, `SystemEvent`, `CartEvent`, `OrderEvent`, and `CatalogObjectEvent`. | ### Returns - `void` ### Example ```javascript import { SFMCSdkModule } from "@sfmc/react-native-sfmc-core"; import type { SFMCSdkApi, SFMCEvent } from "@sfmc/react-native-sfmc-core"; const sfmc: SFMCSdkApi = await SFMCSdkModule.requestSdk(); const event: SFMCEvent = { objType: "CustomEvent", name: "app_open" }; sfmc.track(event); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk/-s-f-m-c-sdk/-companion/track.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Classes/SFMCSdk.html#/c:@CM@SFMCSDK@objc(cs)SFMCSdk(cm)trackWithEvent:>) ## sendImmediate Tracks an event and sends it immediately without waiting for the next batch cycle. ### Syntax ```javascript SFMCSdkModule.sendImmediate(event); ``` ### Parameters | Parameter | Type | Description | | --------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `event` | `object` | The `SFMCEvent` payload to track and send immediately. Valid event types are `CustomEvent`, `EngagementEvent`, `IdentityEvent`, `SystemEvent`, `CartEvent`, `OrderEvent`, and `CatalogObjectEvent`. | ### Returns - `void` ### Example ```javascript import { SFMCSdkModule } from "@sfmc/react-native-sfmc-core"; import type { SFMCSdkApi, SFMCEvent } from "@sfmc/react-native-sfmc-core"; const sfmc: SFMCSdkApi = await SFMCSdkModule.requestSdk(); const event: SFMCEvent = { objType: "CartEvent", subtype: "add", lineItems: [ { catalogObjectType: "Product", catalogObjectId: "sku-1", quantity: 2, price: 9.99, currency: "USD", }, ], }; sfmc.sendImmediate(event); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk/-s-f-m-c-sdk/-companion/send-immediate.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Classes/SFMCSdk.html#/c:@CM@SFMCSDK@objc(cs)SFMCSdk(cm)sendImmediateWithEvent:>) ## flush Flushes all queued events to Marketing Cloud servers immediately. ### Syntax ```javascript SFMCSdkModule.flush(); ``` ### Returns - `void` ### Example ```javascript import { SFMCSdkModule } from "@sfmc/react-native-sfmc-core"; import type { SFMCSdkApi } from "@sfmc/react-native-sfmc-core"; const sfmc: SFMCSdkApi = await SFMCSdkModule.requestSdk(); sfmc.flush(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk/-s-f-m-c-sdk/-companion/flush.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Classes/SFMCSdk.html#/c:@CM@SFMCSDK@objc(cs)SFMCSdk(cm)flush>) ## setLogging Sets the log level for the native Marketing Cloud SDK and Unified SFMC SDK. ### Syntax ```javascript SFMCSdkModule.setLogging(level); ``` ### Parameters | Parameter | Type | Description | | --------- | -------- | ------------------------------------------------------------------------- | | `level` | `string` | The SDK log level. Valid values are `DEBUG`, `WARN`, `ERROR`, and `NONE`. | ### Returns - `void` ### Example ```javascript import { SFMCSdkModule } from "@sfmc/react-native-sfmc-core"; import type { SFMCSdkApi } from "@sfmc/react-native-sfmc-core"; const sfmc: SFMCSdkApi = await SFMCSdkModule.requestSdk(); sfmc.setLogging("DEBUG"); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk.components.logging/-log-level/index.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Classes/SFMCSdk.html#/c:@M@SFMCSDK@objc(cs)SFMCSdk(cm)setLoggerWithLogLevel:logOutputter:>) ## getSdkState Returns the current SDK state object for diagnostics and support troubleshooting. ### Syntax ```javascript SFMCSdkModule.getSdkState(); ``` ### Returns - `Promise` - A promise that resolves to the SDK state object. ### Example ```javascript import { SFMCSdkModule } from "@sfmc/react-native-sfmc-core"; import type { SFMCSdkApi } from "@sfmc/react-native-sfmc-core"; const sfmc: SFMCSdkApi = await SFMCSdkModule.requestSdk(); const sdkState = await sfmc.getSdkState(); ``` ### See Also - [Android SDK Reference](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk/-s-f-m-c-sdk/get-sdk-state.html) - [iOS SDK Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/%3Chttps://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/appledocs/SFMCSdk/11.0/Classes/SFMCSdk.html#/c:@M@SFMCSDK@objc(cs)SFMCSdk(cm)state>) # SFMC SDK ## Packages - [com.salesforce.marketingcloud.sfmcsdk](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-sfmcsdk/sfmcsdk_index.md) - [com.salesforce.marketingcloud.sfmcsdk.components.events](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-sfmcsdk-components-events/sfmcsdk-components-events_index.md) - [com.salesforce.marketingcloud.sfmcsdk.components.identity](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-sfmcsdk-components-identity/sfmcsdk-components-identity_index.md) - [com.salesforce.marketingcloud.sfmcsdk.components.logging](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/com-salesforce-marketingcloud-sfmcsdk-components-logging/sfmcsdk-components-logging_index.md) # SFMC SDK (Foundation) Foundation SDK providing core infrastructure for all Marketing Cloud iOS SDKs ## API Reference ### [Classes](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/classes/sfmc-sdk_classes_index.md) 9 classes ### [Protocols](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/protocols/sfmc-sdk_protocols_index.md) 16 protocols ### [Enumerations](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/enums/sfmc-sdk_enums_index.md) 14 enumerations # SFMCSdk `Class` ## Declaration ```swift @objc(SFMCSdk) public final class SFMCSdk : NSObject @objc public static var cdp: CDP @objc public static var personalization: PERSONALIZATION @objc public static let identity: Identity @objc public static func initializeSdk(_ configuration: Config, completion: ((_ status: [ModuleInitStatus]) -> Void)? = nil) @objc public static func state() -> String @objc public static func setLogger(logLevel: LogLevel, logOutputter: LogOutputter? = LogOutputter()) public static func setLogger(logLevel: LogLevel, logOutputter: LogOutputter? = LogOutputter(), filters: [LoggerCategory] = [LoggerCategory]()) @objc public static func getLogLevel() -> LogLevel @objc public static func clearLoggerFilters() @objc public static func setFileProtectionType(fileProtectionType: FileProtectionType?) @objc public static func fileProtectionType() -> FileProtectionType? @objc public static func requestPersonalizationSdk(_ callback: @escaping () -> Void) @objc public static func requestCdpSdk(_ callback: @escaping (_ cdp: CdpInterface) -> Void) @objc public static func getStatus(module: ModuleName) -> ModuleStatus @objc public static func track(event: Event) @objc public static func sendImmediate(event: Event) @objc public static func flush() ``` ## SFMCSDK Modules ### `cdp` ```swift @objc public static var cdp: CDP ``` --- ### `personalization` ```swift @objc public static var personalization: PERSONALIZATION ``` --- ### `identity` ```swift @objc public static let identity: Identity ``` --- ## SFMCSDK Methods ### `initializeSdk(_:completion:)` ```swift @objc public static func initializeSdk(_ configuration: Config, completion: ((_ status: [ModuleInitStatus]) -> Void)? = nil) ``` --- ### `state()` ```swift @objc public static func state() -> String ``` --- ## Logger Methods ### `setLogger(logLevel:logOutputter:)` ```swift @objc public static func setLogger(logLevel: LogLevel, logOutputter: LogOutputter? = LogOutputter()) ``` --- ### `setLogger(logLevel:logOutputter:filters:)` ```swift public static func setLogger(logLevel: LogLevel, logOutputter: LogOutputter? = LogOutputter(), filters: [LoggerCategory] = [LoggerCategory]()) ``` --- ### `getLogLevel()` ```swift @objc public static func getLogLevel() -> LogLevel ``` --- ### `clearLoggerFilters()` ```swift @objc public static func clearLoggerFilters() ``` --- ## File Protection Helpers ### `setFileProtectionType(fileProtectionType:)` Provides a way to set/override the Protection level for File system ```swift @objc public static func setFileProtectionType(fileProtectionType: FileProtectionType?) ``` --- ### `fileProtectionType()` Returns File protection type set by the SDK or overridden value by the consuming application ```swift @objc public static func fileProtectionType() -> FileProtectionType? ``` --- ## SDK Getters ### `requestPersonalizationSdk(_:)` Requests the Personalization Module/SDK when it’s operational and safe to use. The provided callback will be invoked when Personalization is ready. The host app shouldn’t normally need to use this, as the Personalization module itself already does this for async operations, like fetching decisions/personalization. As Personalization intentionally doesn’t expose much functionality to the base SFMCSdk, one could use `PersonalizationModule.shared` within the callback code to use module-specific functionality. ```swift @objc public static func requestPersonalizationSdk(_ callback: @escaping () -> Void) ``` --- ### `requestCdpSdk(_:)` Requests the CDP Module/SDK when it’s operational and safe to use. The provided callback will be invoked when CDP Is ready. ```swift @objc public static func requestCdpSdk(_ callback: @escaping (_ cdp: CdpInterface) -> Void) ``` --- ### `getStatus(module:)` Returns the current operational status of the specified module. This method can be called at any time, even before the module is operational. ```swift @objc public static func getStatus(module: ModuleName) -> ModuleStatus ``` --- ## User Triggered Events ### `track(event:)` Tracks a custom event which are dispatched to all registered SDK modules. Events are processed asynchronously and may be batched before being sent to the network. Use [sendImmediate] for time-sensitive events that should bypass normal queuing. ```swift @objc public static func track(event: Event) ``` --- ### `sendImmediate(event:)` Tracks a custom event at high priority and schedules it to be sent to the server along with any other pending events in the queue. Unlike [track], this attempts to deliver queued events promptly rather than waiting for the next scheduled interval. This API is subject to SDK guardrails — there is a 60-second throttling period between consecutive calls. Use it only when timely delivery is important. ```swift @objc public static func sendImmediate(event: Event) ``` --- ### `flush()` Schedules a flush of any queued events. The flush is subject to SDK guardrails — notably, a 60-second throttling period between consecutive flush calls. If a flush was recently performed, the request will be deferred until the throttle window has elapsed. Use this only when prompt delivery is critical. Calling it frequently will not accelerate delivery and may be throttled by the SDK. ```swift @objc public static func flush() ``` --- # SFMCSdkInitializationStatus ## Package `com.salesforce.marketingcloud.sfmcsdk` ## Class Declaration ```kotlin class SFMCSdkInitializationStatus : InitializationStatus ``` ## Description Implementation of the SDK initialization interface. ## Properties ### status ```kotlin open override val status: Int ``` The SDK's initialization status. ## Parent Class - `InitializationStatus` ## Platform - androidJvm # SFMCSdkModuleConfig **Package:** `com.salesforce.marketingcloud.sfmcsdk` **Platform:** androidJvm --- ## Description ```kotlin class SFMCSdkModuleConfig ``` A configuration builder class for the Salesforce Marketing Cloud Unified SDK. This class facilitates building all supported configurations for `SFMCSdk`. The SDK is initialized using the configuration provided by this class through `SFMCSdk.configure`. **Note:** Only module configurations that need to be initialized should be provided. --- ## Properties ### cdpModuleConfig ```kotlin val cdpModuleConfig: CdpModuleConfig? ``` Configuration for the CDP (Customer Data Platform) module. ### engagementModuleConfig ```kotlin val engagementModuleConfig: EngagementModuleConfig? ``` Configuration for the Engagement module. ### inAppMessagingFeatureModuleConfig ```kotlin val inAppMessagingFeatureModuleConfig: InAppMessagingFeatureModuleConfig? ``` Configuration for the In-App Messaging feature module. ### mamModuleConfig ```kotlin val mamModuleConfig: MamModuleConfig? ``` Configuration for the MAM (Mobile Application Messaging) module. ### personalizationModuleConfig ```kotlin val personalizationModuleConfig: PersonalizationModuleConfig? ``` Configuration for the Personalization module. ### pushFeatureModuleConfig ```kotlin val pushFeatureModuleConfig: PushFeatureModuleConfig? ``` Configuration for the Push feature module. --- ## Nested Types ### Builder ```kotlin class Builder ``` Builder class for creating various configurations supported by `SFMCSdk`. Configurations implementing the Config interface (EngagementModuleConfig, PersonalizationModuleConfig, and CdpModuleConfig) can be set. #### Constructors ##### Builder() ```kotlin constructor() ``` Creates a new instance of the Builder. #### Properties ##### cdpModuleConfig ```kotlin var cdpModuleConfig: CdpModuleConfig? ``` Configuration for the CDP (Customer Data Platform) module. ##### engagementModuleConfig ```kotlin var engagementModuleConfig: EngagementModuleConfig? ``` Configuration for the Engagement module. ##### inAppMessagingFeatureModuleConfig ```kotlin var inAppMessagingFeatureModuleConfig: InAppMessagingFeatureModuleConfig? ``` Configuration for the In-App Messaging feature module. ##### mamModuleConfig ```kotlin var mamModuleConfig: MamModuleConfig? ``` Configuration for the MAM (Mobile App Messaging) module. ##### personalizationModuleConfig ```kotlin var personalizationModuleConfig: PersonalizationModuleConfig? ``` Configuration for the Personalization module. ##### pushFeatureModuleConfig ```kotlin var pushFeatureModuleConfig: PushFeatureModuleConfig? ``` Configuration for the Push feature module. #### Methods ##### build() ```kotlin fun build(): SFMCSdkModuleConfig ``` Constructs and returns a `SFMCSdkModuleConfig` instance using the configurations set in this builder. All module configurations provided through the builder are initialized. **Returns:** A configured `SFMCSdkModuleConfig` object. ### Companion ```kotlin object Companion ``` # SFMCSdkReadyListener **Package:** `com.salesforce.marketingcloud.sfmcsdk` **Platform:** androidJvm **SDK Version:** 11.0.0 --- ## Overview ```kotlin fun interface SFMCSdkReadyListener ``` A functional interface that provides a valid `SFMCSdk` instance when the SDK initialization is complete. ### Behavior - If SDK initialization has already completed, the listener is notified immediately - If `SFMCSdk.configure` has not been called or is currently executing, the listener is called upon completion - **Important:** If `SFMCSdk.configure` completes with `InitializationStatus.FAILURE`, the listener will **not** be invoked and all registered listeners are cleared --- ## Functions ### ready ```kotlin abstract fun ready(sdk: SFMCSdk) ``` Called when the SDK is ready to use. **Parameters:** - `sdk` - A valid instance of `SFMCSdk` # SFNotificationServiceConfig `Class` The configuration class for the notification service which provides configuration options for notification service extension, including option for setting logging levels. ## Declaration ```swift @objc(SFMCNotificationServiceConfig) public final class SFNotificationServiceConfig : NSObject @objc public let logLevel: LogLevel @objc public let shouldShowCarouselThumbnail: Bool @objc public let mediaProviders: Int @objc public init(logLevel: LogLevel = .none, shouldShowCarouselThumbnail: Bool = true, mediaProviders: Int = MediaProviders.sfmc.rawValue) @objc public convenience init(logLevel: LogLevel = .none, shouldShowCarouselThumbnail: Bool = true) ``` ## Cases ### `logLevel` The log level used for notification service extension. The default is `.none` . ```swift @objc public let logLevel: LogLevel ``` --- ### `shouldShowCarouselThumbnail` Indicates whether a thumbnail should be displayed for carousel notifications. The default is `true` . ```swift @objc public let shouldShowCarouselThumbnail: Bool ``` --- ### `mediaProviders` Bitmask of enabled media providers. Combine `SFMCMediaProviders` raw values with a bitwise OR (e.g. `SFMCMediaProvidersSfmc` ). Defaults to `SFMCMediaProviders.sfmc` . Use `SFMCMediaProviders.none` (i.e. `0` ) to opt out of SDK-managed media handling. ```swift @objc public let mediaProviders: Int ``` --- ### `init(logLevel:shouldShowCarouselThumbnail:mediaProviders:)` Initializes the notification service configuration with specified options. ```swift @objc public init(logLevel: LogLevel = .none, shouldShowCarouselThumbnail: Bool = true, mediaProviders: Int = MediaProviders.sfmc.rawValue) ``` --- ### `init(logLevel:shouldShowCarouselThumbnail:)` Convenience for callers who only need to set log level / thumbnail flag. Preserves the ObjC selector `initWithLogLevel:shouldShowCarouselThumbnail:` and inherits the primary init’s default of `SFMCMediaProviders.sfmc` . ```swift @objc public convenience init(logLevel: LogLevel = .none, shouldShowCarouselThumbnail: Bool = true) ``` --- # ShareCatalogEvent **Package:** `com.salesforce.marketingcloud.sfmcsdk.components.events` **SDK Version:** 11.0.0 **Platform:** androidJvm (Android) --- ## Overview An event to capture when a user shares a catalog object. `ShareCatalogEvent` is part of the Salesforce Marketing Cloud Unified SDK for Android and is used to track sharing interactions with catalog items within your application. --- ## Class Declaration ```kotlin class ShareCatalogEvent : CatalogEvent ``` --- ## Inheritance Hierarchy ``` Event (abstract) └── EngagementEvent (sealed) └── CatalogEvent (sealed) └── ShareCatalogEvent ``` --- ## Properties ### Inherited from CatalogEvent #### catalogObject - **Type:** `CatalogObject` - **Description:** Represents the catalog item associated with this event ### Inherited from EngagementEvent #### category ```kotlin open override var category: Event.Category ``` - **Description:** The Event category Name. Category contains list of allowed values #### priority ```kotlin open override val priority: Priority ``` - **Description:** Defines the priority level for the event --- ## Methods ### Inherited from EngagementEvent #### attributes() ```kotlin open override fun attributes(): Map ``` - **Returns:** `Map` - The Event attributes for this event - **Description:** Returns a map containing string keys and any type values representing event attributes #### name() ```kotlin open override fun name(): String ``` - **Returns:** `String` - The name for the event - **Description:** The name for the event. This value must match the Event Name used when creating the event in the Marketing Cloud UI for proper tracking functionality --- ## Related Types ### CatalogObject Represents various items that can be tracked such as products or blog posts. **Constructor:** ```kotlin @JvmOverloads constructor( type: String, id: String, attributes: Map = mapOf(), relatedCatalogObjects: Map> = mapOf() ) ``` **Parameters:** - `type: String` - A type name representing the catalog object - `id: String` - A unique id representing the catalog object - `attributes: Map` - (Optional) A map of user-supplied values. Defaults to empty map - `relatedCatalogObjects: Map>` - (Optional) A map of related catalog objects. Defaults to empty map --- ## Usage `ShareCatalogEvent` is used to track when users share catalog objects in your application. As a subclass of `CatalogEvent`, it requires a `CatalogObject` that identifies what item was shared. This event integrates with the Salesforce Marketing Cloud's engagement tracking system and should be tracked using the `EventManager` component of the SDK. --- ## Related Classes Other catalog event types in the same package: - `ViewCatalogEvent` - Captures when a user views a catalog object - `ViewCatalogDetailEvent` - Captures when a user views catalog object details - `QuickViewCatalogEvent` - Captures quick view interactions - `ReviewCatalogEvent` - Captures when a user reviews a catalog object - `CommentCatalogEvent` - Captures when a user comments on a catalog object - `FavoriteCatalogEvent` - Captures when a user favorites a catalog object --- ## Notes - This is a concrete implementation of `CatalogEvent` specifically for tracking sharing actions - As part of a sealed class hierarchy, type safety is ensured at compile time - The `@JvmOverloads` annotation on `CatalogObject` provides Java interoperability with overloaded constructors - Events must be configured in the Marketing Cloud UI with matching event names for proper tracking # ShipOrderEvent ## Package `com.salesforce.marketingcloud.sfmcsdk.components.events` ## Overview An E-commerce event to manage details of an order shipment. ## Platform - **Target**: androidJvm - **SDK Version**: SFMC SDK v3.1.0 (Salesforce Marketing Cloud Unified SDK 11.0.0) - **Available Versions**: 11.0.0, 10.0.0 ## Class Declaration ```kotlin class ShipOrderEvent : OrderEvent ``` ## Inheritance Hierarchy ``` Event (interface) └── EngagementEvent (sealed class) └── OrderEvent (sealed class) └── ShipOrderEvent (class) ``` ## Description `ShipOrderEvent` is a concrete implementation of `OrderEvent` used to track when an order has been shipped in an e-commerce flow. It extends the sealed `OrderEvent` class, which is part of the engagement event system in the Salesforce Marketing Cloud SDK. ## Properties ### Inherited from OrderEvent #### order ```kotlin val order: Order ``` A property that holds an Order object containing details about the shipment. ### Inherited from EngagementEvent #### category ```kotlin open override var category: Event.Category ``` The Event category Name. Category contains list of allowed values. #### priority ```kotlin open override val priority: Priority ``` Defines the priority level for the event. ## Methods ### Inherited from EngagementEvent #### attributes() ```kotlin open override fun attributes(): Map ``` The Event attributes for this event. **Returns:** `Map` - A map of event attributes. #### name() ```kotlin open override fun name(): String ``` The name for the event. This value must match the Event Name used when creating the event in the Marketing Cloud UI for any action to result from tracking this event. **Returns:** `String` - The event name. ## Related Types ### Order The `Order` data class contains the following properties: ```kotlin data class Order @JvmOverloads constructor( val id: String, val lineItems: List = listOf(), val totalValue: Double? = null, val currency: String? = null, val attributes: Map = mapOf() ) ``` **Constructor Parameters:** - **id** (`String`, required) - A unique identifier representing the order - **lineItems** (`List`, optional, default: `listOf()`) - A list of Line Item Data values - **totalValue** (`Double?`, optional, default: `null`) - The total value of the order - **currency** (`String?`, optional, default: `null`) - The currency of the total value for the order - **attributes** (`Map`, optional, default: `mapOf()`) - A map of user-supplied values ## Companion Object The `OrderEvent` class (parent of `ShipOrderEvent`) includes a companion object for factory methods or constants. ## Related Events Other `OrderEvent` subclasses available in the SDK: - `PurchaseOrderEvent` - For when a user makes a purchase - `PreorderEvent` - For preorder transactions - `CancelOrderEvent` - For order cancellations - `DeliverOrderEvent` - For order deliveries - `ReturnOrderEvent` - For order returns - `ExchangeOrderEvent` - For order exchanges ## Usage Notes 1. The event name set via `name()` must match the Event Name configured in the Marketing Cloud UI for tracking to trigger any associated actions. 2. Use this event to track the shipment stage of an order in your e-commerce flow. 3. The `Order` object should contain the complete order details including line items and total value. # Silent Push Notification Silent push notifications are delivered without an alert message or sound, typically to trigger updates to the app UI or background operations. A silent push notification wakes your app from a "Suspended" or "Not Running" state to update content or run certain background tasks without notifying users. To use silent push notifications to trigger background tasks, configure your app to receive notifications even when it’s in the background. To do so, navigate to the **Signing & Capabilities** pane on Xcode, and add the **Background Modes** capability to the main app target. Also ensure that you select the **Remote notifications** checkbox. ![](https://developer.salesforce.com/media/troubleshooting/silent_push_notification_setup.png) To handle silent push notifications, implement the `application:didReceiveRemoteNotification:fetchCompletionHandler:` application delegate method. For more information, see Apple’s documentation on [Pushing background updates to your app](https://developer.apple.com/documentation/usernotifications/pushing-background-updates-to-your-app). # Specify a Custom Notification Sound Play a custom sound when push notifications arrive by including an audio file in your app bundle. The SDK looks for a file named `custom.caf` in your app's resources and plays it when a push message arrives. This feature lets you create a distinctive audio signal that helps users recognize notifications from your app. 1. Add a file named `custom.caf` to your project. The cloud push payload looks for a file named `custom.caf`. ![The project file explorer in Xcode, showing a file named custom.caf.](https://developer.salesforce.com/media/push-messaging/custom-sound-file-add-to-project.png) 2. Add the `custom.caf` audio file to the **Copy Bundle Resources** folder in Xcode for your app. ![The Build Phases tab in Xcode, showing the Copy Bundle Resources phase with the custom.caf file selected.](https://developer.salesforce.com/media/push-messaging/custom-sound-file_xcode-copy-build-phases.png) 3. To prevent Xcode from using cached files, perform a clean build folder in Xcode. In the **Product** menu, hold the Option key and select **Clean Build Folder**. 4. Enable the custom sound option on the MobilePush Administration page. You might need to work with a Marketing Cloud Engagement admin to enable this option. ![The MobilePush Administration page in the Marketing Cloud Engagement UI, showing the Custom Sound option enabled.](https://developer.salesforce.com/media/push-messaging/custom-sound-marketer-enable.png) # Specify a Custom Notification Sound for iOS Push Notifications This feature uses a sound included in your mobile app as a custom audio signal when a push message arrives on the mobile device. 1. Add a file named `custom.caf` to your project. The cloud push payload looks for a file named `custom.caf`. ![The project file explorer in Xcode, showing a file named custom.caf.](https://developer.salesforce.com/media/push-messaging/custom-sound-file-add-to-project.png) 2. Add the `custom.caf` audio file to the **Copy Bundle Resources** folder in Xcode for your app. ![The Build Phases tab in Xcode, showing the Copy Bundle Resources phase with the custom.caf file selected.](https://developer.salesforce.com/media/push-messaging/custom-sound-file_xcode-copy-build-phases.png) 3. To prevent Xcode from using cached files, perform a clean build of the folder in Xcode. In the **Product** menu, hold the Option key and select **Clean Build Folder**. # Style **Package:** `com.salesforce.marketingcloud.pushmodels.data` **Module:** Push Models Module v1.0.2 **Platform:** androidJvm ## Overview ```kotlin interface Style : Parcelable ``` An interface for defining text styling in push notifications. Implements Android's `Parcelable` for data transfer. ## Inheritors - [StyleImpl](#styleimpl) ## Nested Types ### Alignment ```kotlin enum class Alignment : Enum ``` Enumeration for text alignment options. ### Companion ```kotlin object Companion ``` Companion object for the Style interface. ### FontStyle ```kotlin enum class FontStyle : Enum ``` Enumeration for font style variations. ### Size ```kotlin enum class Size : Enum ``` Enumeration for font size options. ### StyleImpl ```kotlin data class StyleImpl( val fontColor: String? = null, val backgroundColor: String? = null, val fontSize: Style.Size? = null, val alignment: Style.Alignment? = null, val fontStyle: Style.FontStyle? = null, var span: Spanned? = null ) : Style ``` Data class implementation of Style interface. Defines text appearance for push notifications with a `span` property containing rendered HTML. ## Properties ### alignment ```kotlin abstract val alignment: Style.Alignment? ``` Text alignment configuration. ### backgroundColor ```kotlin abstract val backgroundColor: String? ``` Background color for the styled text. ### fontColor ```kotlin abstract val fontColor: String? ``` Font color for the text. ### fontSize ```kotlin abstract val fontSize: Style.Size? ``` Font size specification. ### fontStyle ```kotlin abstract val fontStyle: Style.FontStyle? ``` Font style configuration. ## Functions ### describeContents ```kotlin open override fun describeContents(): Int ``` Parcelable implementation method describing contents. ### writeToParcel ```kotlin open override fun writeToParcel(parcel: Parcel, flags: Int) ``` Parcelable implementation for writing object data to a Parcel. **Parameters:** - `parcel` - The Parcel to write to - `flags` - Additional flags for writing --- _Part of Salesforce Marketing Cloud Unified SDK 11.0.0_ # Template **Package:** `com.salesforce.marketingcloud.pushmodels.data` **Module:** Push Models Module v1.0.2 **Version:** 11.0.0 **Platform:** androidJvm ## Overview Interface that defines templates used to specify the layout of push notifications. It extends `Parcelable` for Android serialization. ## Inheritance ```kotlin interface Template : Parcelable ``` ## Known Inheritors - `RichButtonTemplate` (com.salesforce.marketingcloud.pushmodels.rich.buttons) - `CarouselFullTemplate` (com.salesforce.marketingcloud.pushmodels.rich.carousel) ## Properties ### identifier ```kotlin abstract val identifier: String? ``` Optional string identifier for the template. --- ### style ```kotlin abstract val style: Style? ``` Optional Style object defining visual presentation. --- ### type ```kotlin abstract val type: Template.Type ``` Required enum value specifying the template type. ## Nested Types ### Template.Type ```kotlin enum Type : Parcelable, Enum ``` Enumeration defining available template types, implements both Parcelable and Enum. #### Enum Constants ##### RichButtons Represents a rich buttons template type. ##### CarouselFull Represents a carousel full template type. #### Properties **entries** ```kotlin val entries: EnumEntries ``` Provides an immutable list of all enum entries in declaration order. **value** ```kotlin val value: String ``` String value associated with the enum constant. #### Methods **valueOf(value: String)** ```kotlin fun valueOf(value: String): Template.Type ``` Returns the enum constant matching the specified name (exact match required, no whitespace). **Returns:** `Template.Type` --- **values()** ```kotlin fun values(): Array ``` Returns an array of all constants in declaration order. **Returns:** `Array` ## Additional Notes This interface is part of the Salesforce Marketing Cloud Unified SDK for Android and provides the foundation for rich notification layouts. The template system allows developers to create visually rich push notifications with different layouts such as buttons and carousels. # Test and Validate Basic Push Implementation After you finish implementation, contact registration, and push notification provisioning, test and validate your setup by sending your first push notification through Marketing Cloud Engagement. ## Validate Device Registration and Opt-In Status To confirm that your device is registered and opted in, complete these steps. 1. Review [Test and Validate Registrations](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_validate_implementation_test_registrations.md). 2. Copy the device ID for later use. ## Send a Push Notification Use the Marketing Cloud Engagement user interface to send a test push notification. Alternatively, you can [create](https://developer.salesforce.com/docs/marketing/marketing-cloud/references/mc_rest_push?meta=Create%2Ba%2BPush%2BMessage) and [send](https://developer.salesforce.com/docs/marketing/marketing-cloud/references/mc_rest_push?meta=Send%2Ba%2BMessage%2Bto%2Ba%2BList) push notifications by using the REST API for Marketing Cloud Engagement. To send a test push notification, complete these steps. 1. In Marketing Cloud Engagement, go to **Mobile Studio** > **MobilePush**. 2. Click **Create Message**. 3. On the Create Message page, select the **Outbound** template. 4. Define the properties of the message: - For **Message Name**, enter a message name. - For **App**, select the app you created during setup. - For **Send Method**, select **Schedule**. - For **Push Method**, select **Alert**. 5. Click **Next**. 6. For **Audience Type**, select **Contact List**. 7. Click **Create List**. 8. Click **MobilePush Data** and then select **MobilePush Demographics**. 9. Drag the **Device ID** attribute to the canvas. ![MobilePush demographics page, with the Device ID attribute dragged onto the canvas. A device ID value is listed in the criteria field.](https://developer.salesforce.com/media/additional-sdk-configuration/add-device-id-attribute-to-canvas.png) 10. In the Device ID attribute field, paste the device ID for your test device. 11. Click **Done**. 12. Click **Save as Filter** and name the contact list. 13. Select the contact list, and then select **Auto-refresh before send**. 14. Click **Next**. 15. Create your test push notification by specifying the **Title** and **Message**. 16. Click **Next**. 17. For **Delivery**, select **Immediately**. 18. Send the message. To review the progress of your test push notification, go to the **Sends** tab in MobilePush. ![The Sends tab in MobilePush, a test push notification with a status of Completed.](https://developer.salesforce.com/media/additional-sdk-configuration/review-send-status-mobilepush.png) If the status shows `Completed` but you didn’t receive a push notification, there’s likely an issue with the implementation. For troubleshooting guidance, see [Troubleshoot Push Implementation](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_troubleshooting/mc_engagement_troubleshooting_push.md). ## Review Test Notification and Analytics After you successfully send a push notification to your test device, test that your implementation is configured to send back analytics. 1. Open and interact with the test push notification on your device. 2. Send the app to the background. 3. On the Engagement Dashboard, go to **Mobile Studio** > **MobilePush**. Wait for about 5 minutes for the data to populate. 4. Select or search the name of the message that you sent. 5. Review analytics and message details. If you don’t see analytics data, there’s likely an issue with your push implementation. For guidance on identifying and troubleshooting issues with your push implementation, see [Troubleshoot Push Implementation](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_troubleshooting/mc_engagement_troubleshooting_push.md). # Test and Validate Registrations After you implement the SDK in your app, test and validate contact registrations. For testing purposes, set a contact key, such as your email address, in your app. By setting a contact key, you can quickly locate and target a test push notification to a test device. Next, build and run your app on your connected device. Finally, review the results of the test registration. Complete these steps to confirm that data is being processed. **note:** It can take up to five minutes for Marketing Cloud Engagement to process and display the registration. 1. In Marketing Cloud Engagement, go to **Audience Builder** > **Contact Builder**. 2. On the **All Contacts** tab, in the navigation panel, select **MobilePush**. 3. Search for the contact key or device ID of your test user. 4. Select the contact. 5. On the **Membership** tab, review the opt-in status for the contact’s device. 6. On the **Attributes** tab, in the **MobilePush Data** section, confirm that the **Device ID** is correct. Also, make sure that the expected device token in the **System Token** field is registered and that the **Status** is `Active`. A registered device token is required for delivering push notifications. If you can’t find the registration data or the registration data isn’t what you expected, see [Troubleshoot Your Push Implementation](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_troubleshooting/mc_engagement_troubleshooting_push.md). # Test and Validate Your Implementation After you integrate the Engagement SDK with your app, test and validate your implementation to make sure that everything works correctly. Testing helps you identify and resolve issues before you deploy your app to production. ## Validation Workflow Follow this workflow to validate your implementation: 1. **Test contact registrations** - Verify that devices register correctly with Marketing Cloud Engagement and that contact data is being captured and processed. 2. **Test push notifications** - Send test push notifications to confirm that your app can receive and display notifications correctly. 3. **Test analytics** - Verify that your app sends analytics data back to Marketing Cloud Engagement when users interact with notifications. ## Test Contact Registrations Validate that your implementation correctly registers devices and contacts with Marketing Cloud Engagement. This includes: - Device ID registration - Contact key association - Opt-in status - Device token registration - Contact attributes For more information, see [Test and Validate Registrations](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_validate_implementation_test_registrations.md). ## Test Push Notifications and Analytics Test that your app can receive push notifications and send analytics data back to Marketing Cloud Engagement. This includes: - Sending test push notifications - Receiving notifications on your device - Opening and interacting with notifications - Verifying analytics data in Marketing Cloud Engagement For more information, see [Test and Validate Basic Push Implementation](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_validate_implementation_test_push.md). # Text **Package:** `com.salesforce.marketingcloud.pushmodels.data` **Module:** Push Models Module v1.0.2 **Platform:** androidJvm --- ## Overview A data class representing text content in push notifications. Implements `Parcelable` and `PushView` interfaces. ```kotlin data class Text( val text: String, val style: Style.StyleImpl? = null, val actions: List? = listOf() ) : Parcelable, PushView ``` --- ## Constructors ### Text ```kotlin constructor( text: String, style: Style.StyleImpl? = null, actions: List? = listOf() ) ``` Creates a Text instance with the specified content, optional styling, and optional actions. **Parameters:** - `text` - The string content to display - `style` - Optional styling configuration (defaults to null) - `actions` - Optional list of actions associated with the text (defaults to empty list) --- ## Properties ### text ```kotlin val text: String ``` The text content to be displayed. ### style ```kotlin open override val style: Style.StyleImpl? ``` Optional styling configuration for the text appearance. ### actions ```kotlin open override val actions: List? ``` Optional list of actions that can be triggered from this text element. --- ## Functions ### toString ```kotlin open override fun toString(): String ``` Returns a string representation of the Text object. **Returns:** String representation of this instance --- ## Companion Object ```kotlin object Companion ``` Companion object for the Text class. --- ## Inheritance - `Parcelable` - Android parcelable interface for serialization - `PushView` - Interface for push notification view elements # track Method to track events, which could result in actions such as an InApp Message being displayed. ## Syntax `MCCordovaPlugin.track(event)` ## Kind Static method of `MCCordovaPlugin`. ## Parameters | Parameter | Type | Description | | --------- | --------------------------------------------------------------------------------------------------------------------------- | ------------------------ | | `event` | `CustomEvent`\| `EngagementEvent`\| `IdentityEvent` \| `SystemEvent` \| `CartEvent` \| `OrderEvent` \| `CatalogObjectEvent` | The event to be tracked. | ## See Also - [Event Tracking](/docs/marketing/mobilepush/guide/event-tracking.html) # track This method helps to track events, which could result in actions such as an in-app message being displayed. ## Syntax ```javascript MCReactModule.track(event); ``` ## Parameters | Parameter | Type | Description | | --------- | -------------------------------------------------------------------------------------------------------------------- | ------------------- | | `event` | `CustomEvent`, `EngagementEvent`, `IdentityEvent`, `SystemEvent`, `CartEvent`, `OrderEvent`, or `CatalogObjectEvent` | The event to track. | ## Returns - `void` - No return value. ## Example ```javascript import { MCReactModule } from "react-native-marketingcloudsdk"; const trackPurchaseEvent = () => { try { const purchaseEvent = { name: "Purchase", attributes: { amount: 29.99, currency: "USD", productId: "prod123", }, }; MCReactModule.track(purchaseEvent); console.log("Purchase event tracked"); } catch (error) { console.error("Error tracking event:", error); } }; ``` ## See Also - [Event Tracking](/docs/marketing/mobilepush/guide/event-tracking.html) # Track Cart To track the contents of an in-app shopping cart, use [`trackCartContents()`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.analytics/-analytics-manager/track-cart-contents.html). For more information about this method's general use with Einstein Recommendations, see _Salesforce Help_: [Track Items in Shopping Cart](https://help.salesforce.com/articleView?id=mktg.mc_ctc_track_cart.htm). Use the analytics manager to track cart contents with items, quantities, and prices. ::::::tabset{tabs='["SDK v10", "SDK v8", "SDK v7"]'} :::::tab For SDK version 10, use this example. ```java MarketingCloudSdk.requestSdk { engagementSdk -> val analyticsManager = engagementSdk.analyticsManager val cartItem = PiCartItem("Burger", 2, 2.99, "burger_123") val cart = PiCart(listOf(cartItem)) analyticsManager.trackCartContents(cart) } ``` ::::: :::::tab For SDK version 8, use this example. ```java SFMCSdk.requestSdk { sdk -> sdk.mp { val analyticsManager = it.analyticsManager val cartItem = PiCartItem("Burger", 2, 2.99, "burger_123") val cart = PiCart(listOf(cartItem)) analyticsManager.trackCartContents(cart) } } ``` ::::: :::::tab For SDK version 7, use this example. ```java MarketingCloudSdk.requestSdk { val analyticsManager = it.analyticsManager val cartItem = PiCartItem("Burger", 2, 2.99, "burger_123") val cart = PiCart(listOf(cartItem)) analyticsManager.trackCartContents(cart) } ``` ::::: :::::: # Track Cart To track the contents of an in-app shopping cart, use the `trackCartContents` method. For more information about using this method with Einstein Recommendations, see _Salesforce Help_: [Track Items in Cart](https://help.salesforce.com/articleView?id=mktg.mc_ctc_track_cart.htm). ::::::tabset{tabs='["SDK v10+", "SDK v8", "SDK v7"]'} :::::tab For SDK version 10 and later, use this example. ```swift MarketingCloudSdk.requestSdk { mc in let cartItem = mc?.cartItemDictionary( price: 1.10, quantity: 1, item: "123456", uniqueId: "uniqueId_123456" ) let cart = mc?.cartDictionary(cartItem: [cartItem]) mc?.trackCartContents(cart!) } ``` ::::: :::::tab For SDK version 8, use this example. ```swift SFMCSdk.requestPushSdk { mp in let cartItem = mp.cartItemDictionary( price: 1.10, quantity: 1, item: "123456", uniqueId: "uniqueId_123456" ) let cart = mp.cartDictionary(cartItem: [cartItem]) mp.trackCartContents(cart!) } ``` ::::: :::::tab For SDK version 7, use this example. ```swift let cartItem = MarketingCloudSDK.sharedInstance().sfmc_cartItemDictionary( withPrice: 1.10, quantity: 1, item: "123456", uniqueId: "uniqueId_123456" ) let cart = MarketingCloudSDK.sharedInstance().sfmc_cartDictionary( withCartItemDictionaryArray: [cartItem!] ) MarketingCloudSDK.sharedInstance().sfmc_trackCartContents(cart!) ``` ::::: :::::: # Track Conversion To track a purchase made through your mobile app, use [`trackCartConversion()`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.analytics/-analytics-manager/track-cart-conversion.html). For more information about this method's general use with Einstein Recommendations, see _Salesforce Help_: [Track Purchase Details](https://help.salesforce.com/articleView?id=mktg.mc_ctc_track_conversion.htm). Use the analytics manager to track order details including cart items, order number, shipping, and discount. ::::::tabset{tabs='["SDK v10", "SDK v8", "SDK v7"]'} :::::tab For SDK version 10, use this example. ```java MarketingCloudSdk.requestSdk { engagementSdk -> val analyticsManager = engagementSdk.analyticsManager val cartItem = PiCartItem("Burger", 2, 2.99, "burger_123") val cart = PiCart(listOf(cartItem)) val order = PiOrder(cart, "ABC1234", 4.99, .2) analyticsManager.trackCartConversion(order) } ``` ::::: :::::tab For SDK version 8, use this example. ```java SFMCSdk.requestSdk { sdk -> sdk.mp { val analyticsManager = it.analyticsManager val cartItem = PiCartItem("Burger", 2, 2.99, "burger_123") val cart = PiCart(listOf(cartItem)) val order = PiOrder(cart, "ABC1234", 4.99, .2) analyticsManager.trackCartConversion(order) } } ``` ::::: :::::tab For SDK version 7, use this example. ```java MarketingCloudSdk.requestSdk { val analyticsManager = it.analyticsManager val cartItem = PiCartItem("Burger", 2, 2.99, "burger_123") val cart = PiCart(listOf(cartItem)) val order = PiOrder(cart, "ABC1234", 4.99, .2) analyticsManager.trackCartConversion(order) } ``` ::::: :::::: # Track Conversion To track a purchase made through your mobile app, use the `trackCartConversion` method. For more information about using this method with Einstein Recommendations, see _Salesforce Help_: [Track Purchase Details](https://help.salesforce.com/articleView?id=mktg.mc_ctc_track_conversion.htm). ::::::tabset{tabs='["SDK v10+", "SDK v8", "SDK v7"]'} :::::tab For SDK version 10 and later, use this example. ```swift MarketingCloudSdk.requestSdk { mc in let cartItem = mc?.cartItemDictionary( price: 1.10, quantity: 1, item: "123456", uniqueId: "uniqueId_123456" ) let cart = mc?.cartDictionary(cartItem: [cartItem]) let order = mc?.orderDictionary( orderNumber: "123456", shipping: 2.11, discount: 4.99, cart: cart! ) mc?.trackCartConversion(order!) } ``` ::::: :::::tab For SDK version 8, use this example. ```swift SFMCSdk.requestPushSdk { mp in let cartItem = mp.cartItemDictionary( price: 1.10, quantity: 1, item: "123456", uniqueId: "uniqueId_123456" ) let cart = mp.cartDictionary(cartItem: [cartItem]) let order = mp.orderDictionary( orderNumber: "123456", shipping: 2.11, discount: 4.99, cart: cart! ) mp.trackCartConversion(order!) } ``` ::::: :::::tab For SDK version 7, use this example. ```swift let cartItem = MarketingCloudSDK.sharedInstance().sfmc_cartItemDictionary( withPrice: 1.10, quantity: 1, item: "123456", uniqueId: "uniqueId_123456" ) let cart = MarketingCloudSDK.sharedInstance().sfmc_cartDictionary( withCartItemDictionaryArray: [cartItem!] ) let order = MarketingCloudSDK.sharedInstance().sfmc_orderDictionary( withOrderNumber: "123456", shipping: 2.11, discount: 4.99, cart: cart! ) MarketingCloudSDK.sharedInstance().sfmc_trackCartConversion(order!) ``` ::::: :::::: # Track Inbox Message Opens To track analytics for inbox messages, use [`trackInboxOpenEvent()`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.analytics/-analytics-manager/track-inbox-open-event.html). This method sends the open analytic value to Marketing Cloud Engagement. The SDK automatically provides analytics for message downloads. Use the analytics manager to track when users open inbox messages. ::::::tabset{tabs='["SDK v10", "SDK v8", "SDK v7"]'} :::::tab For SDK version 10, use this example. ```java MarketingCloudSdk.requestSdk { engagementSdk -> val analyticsManager = engagementSdk.analyticsManager analyticsManager.trackInboxOpenEvent(message as InboxMessage) } ``` ::::: :::::tab For SDK version 8, use this example. ```java SFMCSdk.requestSdk { sdk -> sdk.mp { val analyticsManager = it.analyticsManager analyticsManager.trackInboxOpenEvent(message as InboxMessage) } } ``` ::::: :::::tab For SDK version 7, use this example. ```java MarketingCloudSdk.requestSdk { val analyticsManager = it.analyticsManager analyticsManager.trackInboxOpenEvent(message as InboxMessage) } ``` ::::: :::::: # Track Inbox Message Opens Call the `trackInboxOpenEvent()` to track analytics for Inbox messages and send them to Marketing Cloud. We automatically provide analytical information for message downloads. To record analytics, call `trackMessageOpened` with an inbox message dictionary. These examples show how to track inbox opens in a table view. ::::::tabset{tabs='["SDK v10+", "SDK v8", "SDK v7"]'} :::::tab For SDK version 10 and later, use this example. ```swift func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let inboxMessage = dataSourceArray[indexPath.row] MarketingCloudSdk.requestSdk { mc in mc?.trackMessageOpened(inboxMessage) } // Your selection handling } ``` ::::: :::::tab For SDK version 8, use this example. ```swift func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let inboxMessage = dataSourceArray[indexPath.row] SFMCSdk.requestPushSdk { mp in mp.trackMessageOpened(inboxMessage) } // ... your selection handling } ``` ::::: :::::tab For SDK version 7, use this example. ```swift func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let inboxMessage = dataSourceArray[indexPath.row] MarketingCloudSDK.sharedInstance().sfmc_trackMessageOpened(inboxMessage) // ... your selection handling } ``` ::::: :::::: # Track Message View States Use the `didShowMessage` and `didCloseMessage` callback methods to help manage the view state of your app. In-app messages are shown in an activity controlled by the SDK within the activity stack for your app. Your app is required to respond to a view appearing or disappearing. - [didShowMessage](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/inappmessagingfeaturemodule/com.salesforce.marketingcloud.inappmessagingfeature/-in-app-message-manager/-event-listener/did-show-message.html) is invoked when the in-app message is initially presented. - [didCloseMessage](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/inappmessagingfeaturemodule/com.salesforce.marketingcloud.inappmessagingfeature/-in-app-message-manager/-event-listener/did-close-message.html) is invoked after the user closes the message and includes the close reason. Implement these methods as part of your event listener. See [Listen for Events](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_in-app_messages_android_events_listen.md). # Track Message View States Track when in-app messages are opened and closed by implementing delegate methods. These methods notify your app when an in-app message appears or closes. Use this information to manage the view hierarchy for your app and to respond to lifecycle events. In-app messages are shown as the top view controller in the hierarchy of your app. Use these delegate methods to: - Pause or resume animations when messages appear or disappear - Update UI state when the view hierarchy changes - Track analytics about message display - Manage app behavior based on message visibility ::::::tabset{tabs='["SDK v11", "SDK v10 or Lower"]'} :::::tab Use this code to track message view states in version 11 of the SDK for iOS. The SDK supports the [didShow and didClose](/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/inappmessageeventdelegate.html) methods. ```swift func didShow(inAppMessage message: InAppMessageDetails) { // message shown } func didClose(inAppMessage message: InAppMessageDetails, action: InAppMessageCloseAction) { // message closed } ``` ::::: :::::tab Use this code to track message view states in version 10 or lower of the SDK for iOS. ```swift func sfmc_didShow(inAppMessage message: [AnyHashable : Any]) { // message shown } func sfmc_didClose(inAppMessage message: [AnyHashable : Any]) { // message closed } ``` ::::: :::::: # Track Page Views To implement page-view analytics in your app, use [`trackPageView()`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.analytics/-analytics-manager/track-page-view.html). For more information about this method's general use with Einstein Recommendations, see _Salesforce Help_: [Track Page View](https://help.salesforce.com/s/articleView?id=mktg.mc_ctc_track_page_view.htm). Use the analytics manager to track page views with URLs, titles, items, and search terms. The `trackPageView()` method requires, at a minimum, a String representing the in-app URL to be tracked. Additional overloaded methods are available. Refer to the Javadoc for details. ::::::tabset{tabs='["SDK v10", "SDK v8", "SDK v7"]'} :::::tab For SDK version 10, use this example. ```java MarketingCloudSdk.requestSdk { engagementSdk -> val analyticsManager = engagementSdk.analyticsManager analyticsManager.trackPageView("url") analyticsManager.trackPageView("url", "title") analyticsManager.trackPageView("url", "title", "item") analyticsManager.trackPageView("url", "title", "item", "searchTerms") } ``` ::::: :::::tab For SDK version 8, use this example. ```java SFMCSdk.requestSdk { sdk -> sdk.mp { val analyticsManager = it.analyticsManager analyticsManager.trackPageView("url") analyticsManager.trackPageView("url", "title") analyticsManager.trackPageView("url", "title", "item") analyticsManager.trackPageView("url", "title", "item", "searchTerms") } } ``` ::::: :::::tab For SDK version 7, use this example. ```java MarketingCloudSdk.requestSdk { val analyticsManager = it.analyticsManager analyticsManager.trackPageView("url") analyticsManager.trackPageView("url", "title") analyticsManager.trackPageView("url", "title", "item") analyticsManager.trackPageView("url", "title", "item", "searchTerms") } ``` ::::: :::::: # Track Page Views To implement page-view analytics in your app, use the `trackPageView` method. For more information about using this method with Einstein Recommendations, see _Salesforce Help_: [Track Items Viewed](https://help.salesforce.com/articleView?id=mktg.mc_ctc_track_page_view.htm). ::::::tabset{tabs='["SDK v10+", "SDK v8", "SDK v7"]'} :::::tab For SDK version 10 and later, use this example. ```swift MarketingCloudSdk.requestSdk { mc in mc?.trackPageView( url: "http://my.example.com", title: "page title", item: "item name", search: "search term" ) } ``` ::::: :::::tab For SDK version 8, use this example. ```swift SFMCSdk.requestPushSdk { mp in mp.trackPageView( url: "http://my.example.com", title: "page title", item: "item name", search: "search term" ) } ``` ::::: :::::tab For SDK version 7, use this example. ```swift MarketingCloudSDK.sharedInstance().sfmc_trackPageView( withURL: "http://my.example.com", title: "page title", item: "item name", search: "search term" ) ``` ::::: :::::: # Track Push Notifications To ensure proper tracking of push notifications in Marketing Cloud Engagement, call the SDK in your push notification handler method. If you don't call the SDK in the handler method, open counts for your push messaging campaigns aren’t tracked. Implement the notification response handler as shown in these examples. ::::::tabset{tabs='["SDK v10+", "SDK v8 and 9", "SDK v7"]'} :::::tab For SDK version 10 and later, use this example. ```swift // The method is called on the delegate when the user responds to the // notification by opening the app, dismissing the notification, or choosing a // UNNotificationAction. Set the delegate before the app returns from // applicationDidFinishLaunching:. func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void ) { // tell the SDK about the notification PushFeature.requestSdk { pushFeature in pushFeature?.setNotificationResponse(response) } completionHandler() } ``` ::::: :::::tab For SDK versions 8 and 9, use this example. ```swift // The method is called on the delegate when the user responds to the // notification by opening the app, dismissing the notification, or choosing a // UNNotificationAction. Set the delegate before the app returns from // applicationDidFinishLaunching:. func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void ) { // tell the SDK about the notification SFMCSdk.requestPushSdk { mp in mp.setNotificationRequest(response.notification.request) } completionHandler() } ``` ::::: :::::tab For SDK version 7, use this example. ```swift // The method is called on the delegate when the user responds to the // notification by opening the app, dismissing the notification, or choosing a // UNNotificationAction. Set the delegate before the app returns from // applicationDidFinishLaunching:. func userNotificationCenter( _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void ) { // tell the MarketingCloudSDK about the notification MarketingCloudSDK.sharedInstance().sfmc_setNotificationRequest( response.notification.request ) completionHandler() } ``` ::::: :::::: # trackEvent Tracks a custom event for analytics purposes. ## Syntax ```dart Future trackEvent(Map event) ``` ## Parameters - `event` (Map) - The event data to track ## Returns - `Future` - Completes when the event has been tracked. ## Example ```dart try { await SfmcSdk.trackEvent({ 'eventName': 'purchase', 'amount': 29.99, 'currency': 'USD', 'productId': 'prod123' }); print('Event tracked successfully'); } catch (e) { print('Failed to track event: $e'); } ``` ## Notes - Events are used for analytics and can trigger journey builder activities. - Event data should be structured as key-value pairs. # Troubleshoot Data Merge For iOS applications upgraded from SDK versions 7.x to versions up to 8.0.6, the previous v7.x tags and attributes are retained on the device but not sent to the server. If an application doesn’t reset or regenerate tags and attributes, the device sends empty tags and attributes to the system. The following sections walk through the requirements for merging datasets successfully. - [Upgrade the SDK](#upgrade-the-sdk) - [Merge data](#merge-data-optional) (Optional) - [Merge data automatically](#automatic-merging) - [Merge data manually](#manual-merging) - [Retry data merge](#retry-data-merge) ## Upgrade the SDK Using SPM, upgrade to the latest version of the SDK for iOS and SFMCSDK for iOS. ### Swift Compilation Error You may encounter a build failure if the Swift compiler version used to build the SDK doesn't match the version used by your current Xcode toolchain. The build fails with this error: ``` X86_64-apple-ios-simulator.private.swiftinterface failed to build module 'PushFeatureSDK'; this SDK is not supported by the compiler (the SDK is built with 'Apple Swift version 6.1.2...', while this compiler is 'Apple Swift version 6.2.3...'). Please select a toolchain which matches the SDK. 'PushFeatureProtocol' is unavailable: cannot find Swift declaration for this protocol. ``` To resolve this issue, follow these steps to reset your environment: 1. Clear Derived Data. 2. Remove the SDK dependencies from your project and then add them back again. 3. Clean and Run. ## Merge Data (Optional) The merging tool offers two options to merge attributes and tags: automatic merging and manual merging. In some scenarios, you can choose to defer or avoid merging the datasets. The merging tool defaults to an "opted out" state if you don’t implement either of the merging methods. In the opted out state, tags and attributes aren’t merged from the version 7.x dataset to your current application’s dataset. ### Automatic Merging The automatic merging option attempts to merge old data into the current dataset, with the current data taking precedence over data within the version 7.x dataset. The following tables illustrate how automatic merging behaves and how data is merged. **note:** in this tables, key\:value pairs are denoted using `:` as the separator. **Attributes** | Prior Dataset | Current Dataset | Merge Result | | ------------- | --------------- | ------------ | | A\:B | empty | A\:B | | empty | A\:B | A\:B | | A\:B, C\:D | A\:E | A\:E, C\:D | | A\:B | A\: cleared | A\: cleared | **Tags** | Prior Dataset | Current Dataset | Merge Result | | ------------- | --------------- | ------------- | | SHIRTS | empty | SHIRTS | | empty | PANTS | PANTS | | SHIRTS | PANTS | SHIRTS, PANTS | | SHIRTS | SHIRTS, PANTS | SHIRTS, PANTS | The following code snippets show you how to configure the SDK to attempt an automatic merge. **note:** To ensure the completion callback passed into `setAutoMergePolicy` is set before SDK initialization, place the following code snippets before SDK initialization. ``` SFMCSdk.setAutoMergePolicy { isMergeSucces in if(!isMergeSuccess) { // ... } } ``` ``` [SFMCSdk setAutoMergePolicyOnCompletion:^(BOOL isMergeSuccess) { if(!isMergeSuccess) { // ... } }]; ``` ### Manual Merging The manual merge option enables you to receive both the prior data and the current data in a callback, providing the opportunity to choose what data ultimately ends up in the final dataset. You can decide what attributes and tags are set in the current dataset. However, to set attributes and tags accordingly, you must retain the data until the SDK is initialized. **important:** Access to the tags and attributes for versions 7.x and 8.x is provided before SDK initialization. #### Swift ``` class ExampleDelegate: UIResponder, UIApplicationDelegate { var setTagsAndAttributes: (() -> ())? = nil // ... } // ... SFMCSdk.setManualMergePolicy(withHandler: {(v8, v9) in self.setTags = { let tags: [String] = // e.g. v9["tags"] MarketingCloudSdk.requestSdk { mc in mc?.addTags(tags) } } } private func handleSDKInitializationCompletion(status: [ModuleInitStatus]) { // ... if moduleStatus.initStatus == .success { // Handle successful initialization for each module switch moduleStatus.moduleName { case .engagement: self.setTags?() // Handle successful initialization for Marketing cloud module } } // ... } // ... SFMCSdk.initializeSdk(configBuilder.build(), completion: completionHandler) ``` ``` class ExampleDelegate: UIResponder, UIApplicationDelegate { var setTagsAndAttributes: (() -> ())? = nil // ... } // ... SFMCSdk.setManualMergePolicy(withHandler: {(v7, v8) in self.setTagsAndAttributes = { let attributes: [String:String] = // e.g. v8["attributes"] as! [String : String] SFMCSdk.identity.setProfileAttributes([ModuleName.push : attributes]) let tags: [String] = // e.g. v8["tags"] SFMCSdk.requestPushSdk { mp in mp.addTags(tags) } } } // ... let completionHandler: (OperationResult) -> () = { result in // ... if result == .success { // ... if (SFMCSdk.mp.getStatus() == .operational) { self.setTagsAndAttributes?() } // ... } } // ... SFMCSdk.initializeSdk(ConfigBuilder().setPush(config: configuration, onCompletion: completionHandler).build()) ``` #### Objective C ``` @interface ExampleDelegate : UIResponder @property (nonatomic, copy) void (^setTags)(void); // ... [SFMCSdk setManualMergePolicyWithHandler:^(NSDictionary * _Nonnull v8, NSDictionary * _Nonnull v9) { self.setTags = ^{ NSArray *tags = // e.g. v9[@"tags"]; [SFMarketingCloudSdk requestSdk:^(id _Nonnull mp) { [mp addTags: tags]; }]; } }]; // MARK: - SDK Initialization Completion Handler - (void)handleSDKInitializationCompletion:(NSArray *)status { // ... if (moduleStatus.initStatus == SFMCSdkOperationResultSuccess) { switch (moduleStatus.moduleName) { case SFMCSdkModuleNameEngagement: if (self.setTags != nil) { [self setTags]; } break; } } // ... SFMCSdkConfigBuilder *configBuilder = [[SFMCSdkConfigBuilder alloc] init]; configBuilder = [configBuilder setEngagementWithConfig:pushConfig]; [SFMCSdk initializeSdk:[configBuilder build] completion:^(NSArray * _Nonnull status) { // Handle completion [self handleSDKInitializationCompletion:status]; }]; ``` ``` @interface ExampleDelegate : UIResponder @property (nonatomic, copy) void (^setTagsAndAttributes)(void); // ... [SFMCSdk setManualMergePolicyWithHandler:^(NSDictionary * _Nonnull v7, NSDictionary * _Nonnull v8) { self.setTagsAndAttributes = ^{ NSDictionary *attributes = // e.g. v8[@"attributes"]; [[SFMCSdk identity] setProfileAttributes:attributes]; NSArray *tags = // e.g. v8[@"tags"]; [SFMCSdk requestPushSdk:^(id _Nonnull mp) { [mp addTags: tags]; }]; } }]; // ... void (^completionHandler)(OperationResult) = ^(OperationResult result) { switch(result) { case OperationResultSuccess: // ... if ([[SFMCSdk mp] getStatus] == ModuleStatusOperational) { if (self.setTagsAndAttributes != nil) { [self setTagsAndAttributes]; } } // ... break; // ... } } SFMCSdkConfigBuilder *configBuilder = [[SFMCSdkConfigBuilder alloc] init]; configBuilder = [configBuilder setPushWithConfig:pushConfig onCompletion:completionHandler]; [SFMCSdk initializeSdk:[configBuilder build]]; ``` ## Retry Data Merge If you must run the merge tool again, you can attempt the merge multiple times. Reattempting merges doesn’t roll back the current dataset but enables you to regain access to the data within the old version 7.x dataset. ``` let appId = // your app ID let resetSuccess: Bool = SFMCSdk.resetDataPolicy(appId: appId) if (resetSuccess) { print("reset succeeded") } ``` ``` NSString *appId = // your app ID BOOL resetSuccess = [SFMCSdk resetDataPolicyWithAppId:appId]; if(resetSuccess) { NSLog(@"reset succeeded"); } ``` # Troubleshoot Initialization and Registration Diagnose issues with Salesforce Engagement SDK initialization and contact or device registration in Marketing Cloud Engagement, including missing devices, duplicate device IDs, and attributes that don't appear. Before you troubleshoot these scenarios, review the basic troubleshooting information for [Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_android.md) and [iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios.md) apps to rule out any fundamental implementation issues. ## Contacts and Their Devices Don’t Appear in Marketing Cloud Engagement Contacts and devices appear in Marketing Cloud Engagement only if your app successfully initializes the SDK. First, ensure the SDK is initialized correctly. It can take up to five minutes to process and display new device registrations. If your devices or contacts don’t show up after successful SDK initialization, wait at least five minutes and check for the contact key again by doing the following. 1. In Marketing Cloud Engagement, go to **Audience Builder** > **Contact Builder** > **All Contacts**. 2. Select the **MobilePush** channel. 3. Search for and select the contact key or device ID for the user that you’re troubleshooting. ![The All Contacts tab in Contact Builder, showing a filled in search box and a contact that matches the search.](https://developer.salesforce.com/media/troubleshooting/select-contact-key-from-all-contacts.png) You can’t look up a contact if you didn’t set a contact key. When you don’t set a contact key, Marketing Cloud Engagement generates and assigns a corresponding contact key to the contact as a random GUID. To identify the GUID and determine if the device was registered, follow these steps. 1. Go to **Audience Builder** > **Contact Builder** > **All Contacts**. 2. Select the **MobilePush** channel in the left navigation. 3. Search for and select the contact key or device ID for the user that you’re troubleshooting. Talk to your marketer about revising your [contact key strategy](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_register_contacts_devices/mc_engagement_register_contacts_devices_determine_key_strategy.md). ## Contacts Have Multiple Device IDs A device ID is analogous to an instance of an app installation. When a contact installs your app, the SDK creates a corresponding device ID for a contact in these scenarios: - If the contact purchases a new mobile device and installs your app. - If the contact deletes the app and then later reinstalls your app. - If the contact does a factory-reset of the device and then reinstalls the app. You can’t delete additional device IDs. There’s also no age-decay criteria to automatically delete less-active devices. However, you can review the device IDs associated with a contact by doing the following. 1. In Engagement, navigate to **Audience Builder** > **Contact Builder** and click the **All Contacts** tab. 2. Select the **MobilePush** channel in the left navigation. 3. Search for and select the contact key or device ID for the user that you’re troubleshooting. 4. On the contact’s **Attributes** tab, locate the MobilePush section. 5. Review the MobilePush channel details for the contact, including device IDs. ![The MobilePush Data section of the Attributes tab for a contact, showing the contact details, which include the system token.](https://developer.salesforce.com/media/troubleshooting/review-mobilepush-channel-details.png) ## Old Device IDs are Still Opted In Engagement determines whether a device is eligible to receive push notifications in these ways. - User Engagement: When a user launches the app, the app can send registration data to your Marketing Cloud Engagement account, even if the device is opted out of receiving push notifications. This scenario is represented in step 3 of this diagram. Older devices can remain inactive for months or even years, and therefore unable to communicate with Marketing Cloud Engagement. In this scenario, older device IDs can remain opted in and persist in your account. - Push Notification Service (PNS): The PNS notifies Marketing Cloud Engagement that the device can’t receive notifications. After it receives this notification, Marketing Cloud Engagement waits to receive confirmation of a device’s eligibility to receive push notifications. After receiving this confirmation, Marketing Cloud Engagement waits until it’s explicitly instructed by the PNS that a device has opted out, or until there are three consecutive delivery failures from the PNS, and then opts the device out from future push notifications. This scenario is illustrated in step 6b of the operational diagram for the SDK. ![How the Engagement SDK works](https://developer.salesforce.com/media/overview/Mkting_MobilePush_SequenceDiag_PushNotification_041124_zh.png) ## Contacts Without Device IDs For information about resolving common causes of contact dissociation, see [Contact Dissociation](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_register_contacts_devices/mc_engagement_register_contacts_devices_contact_dissociation.md). You can also [delete dissociated contacts](https://help.salesforce.com/articleView?id=000313920&type=1) from your account. ## Contact Keys Use Random GUIDs If your app doesn’t set the contact key in the device registration, Marketing Cloud Engagement automatically generates and assigns a random GUID to represent that contact. See [Set the Contact Key](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_register_contacts_devices/mc_engagement_register_contacts_devices_set_contact_key.md). ## Attributes Aren’t Registered or Don’t Appear in Marketing Cloud There are several reasons why attributes don’t appear in Marketing Cloud. To troubleshoot this issue, first make sure that the SDK is fully initialized before it makes registration calls or method updates. If a device attempts to make one of these updates, the requests fail. Add logging to your [Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_android_push_messages_not_displayed.md) or [iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios_push_display_log_check.md), and then review the logs for errors. Attributes can also be cleared using the SDK’s `clear` method. If you use the `clear` method, the registration call updates to reflect the cleared state. This update means that the SDK doesn’t send any attributes to Marketing Cloud. Make sure that your code doesn’t clear any attributes that were previously set. You can also use the `getSdkState()` convenience method to view the output from the SDK’s current state. Finally, make sure that the attributes that you send to Marketing Cloud exist in Contact Builder. In Contact Builder, go to **Data Designer** > **MobilePush Data**. Select and review the attributes that are associated with the Demographics table. Make sure that the attributes you send to the SDK exactly match the attributes in Contact Builder. # Troubleshoot Initialization Errors on Android The troubleshooting steps for initialization errors vary depending on the version of the Salesforce Engagement SDK you use. ## Version 8 and higher The [`InitializationStatus`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk/-initialization-status/index.html) is provided via the [`InitializationListener`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk/-initialization-listener/index.html) passed into the call to the SFMCSdk's `configure` method. ## Version 7 The [`InitializationStatus`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/MarketingCloudSdk/7.4/com.salesforce.marketingcloud/-initialization-status/index.html) is provided via the [`InitializationListener`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/MarketingCloudSdk/7.4/com.salesforce.marketingcloud/-marketing-cloud-sdk/-initialization-listener/index.html) passed into the call to the SDK's [init](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/MarketingCloudSdk/7.4/com.salesforce.marketingcloud/-marketing-cloud-sdk/init.html) method. While this class contains extensive information that can help troubleshoot SDK initialization issues, there are only a limited number of things that you can address at runtime. This section describes the methods from `InitializationStatus` that are useful to check at runtime and how you can recover from them. The `InitializationStatus` is provided via the `InitializationListener` passed into the call to the SFMC SDK's `configure` method. - `status()` - : The [`status()`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk/-initialization-status/status.html) method returns the status of the initialization call. - `locationsError()` - : If you've configured the SDK to enable either geofence or proximity messaging, [`locationsError()`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud/-initialization-status/locations-error.html) indicates whether the SDK encountered an issue with the Google Play Service location library. Additionally, you can also use [`playServicesMessage()`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud/-initialization-status/play-services-message.html) and [`playServicesStatus()`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud/-initialization-status/play-services-status.html) to determine the exact action that you must take to resolve this issue. However, the most likely issue is that the device doesn't have a compatible version of Google Play Services installed and you must prompt the user to perform an update. - `messagingPermissionError()` - : [`messagingPermissionError()`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud/-initialization-status/messaging-permission-error.html) indicates that region messaging was unable to be turned on after a restart due to the `android.Manifest.permission.ACCESS_FINE_LOCATION` or `android.Manifest.permission.ACCESS_BACKGROUND_LOCATION` no longer being granted. Enabling [`geofence`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud/-marketing-cloud-config/geofencing-enabled.html) or [`proximity`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud/-marketing-cloud-config/proximity-enabled.html) messaging requires you to request the runtime permission for location. Then, after you've called the corresponding messaging enablement method ([`enableGeofenceMessaging`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages/-region-message-manager/enable-geofence-messaging.html) or [`enableProximityMessaging`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud.messages/-region-message-manager/enable-proximity-messaging.html)), the SDK will track this setting and check whether the permission is still granted during each initialization. If the user has revoked the location permission from your application, the SDK disables the previously enabled messaging type and requires you to re-request the permission from the user, and re-enable messaging in the SDK. ## Example InitializationListener Implementation ``` SFMCSdk.configure(context.applicationContext as Application, SFMCSdkModuleConfig.build { this.pushModuleConfig = newConfig }) { when(it.status) { com.salesforce.marketingcloud.sfmcsdk.InitializationStatus.SUCCESS -> { Log.v("MyApp", "SDK init succeeded") } com.salesforce.marketingcloud.sfmcsdk.InitializationStatus.FAILURE -> { Log.e("MyApp", "SDK init failed") } } } ``` ``` MarketingCloudSdk.init(context, config) { status -> when (status.status()) { InitializationStatus.Status.COMPLETED_WITH_DEGRADED_FUNCTIONALITY -> { if (status.locationsError()) { //Handle Google Play Services issues. if (GoogleApiAvailability.getInstance().isUserResolvableError(status.playServicesStatus())) { // User will likely need to update GooglePlayServices through the Play Store. // Call GoogleApiAvailability.getInstance().showErrorDialogFragment(...) from Activity. } } else if (status.messagingPermissionError()) { // User disabled location permission. // Re-request permission and if granted enable desired messaging type } } InitializationStatus.Status.SUCCESS -> Log.v("MyApp", "SDK init succeeded") InitializationStatus.Status.FAILED -> Log.e( "MyApp", "The SDK failed to initialize. Status: $status", status.unrecoverableException() ) } } ``` ## See Also - [Troubleshoot Issues on Android Apps](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_android.md) # Troubleshoot iOS App Submission Errors App submission errors can occur when you’re publishing your apps to App Store Connect. These errors include an error message from Xcode or during Apple’s app review. > We identified one or more issues with a recent delivery for your app, “[app name]”. Your delivery was successful, but you may wish to correct the following issues in your next delivery: > > Missing Purpose String in Info.plist File - Your app’s code references one or more APIs that access sensitive user data. The app’s Info.plist file should contain a `NSLocationAlwaysUsageDescription` key with a user-facing purpose string explaining clearly and completely why your app needs the data. Starting Spring 2019, all apps submitted to the App Store that access user data will be required to include a purpose string. If you’re using external libraries or SDKs, they may reference APIs that require a purpose string. While your app might not use these APIs, a purpose string is still required. You can contact the developer of the library or SDK and request they release a version of their code that doesn’t contain the APIs. Learn more (https://developer.apple.com/documentation/uikit/core_app/protecting_the_user_s_privacy). This error can occur even if you aren’t using Location Messaging. If you aren’t using the SDK’s location messaging functionality, your users aren’t prompted to provide location permissions. This error occurs because the SDK includes references to `CoreLocation.framework`. During the app review process, the automated binary scanning detects these references and requires you to provide purpose strings. If you aren’t using Location Messaging, add a purpose string to your app’s `Info.plist` file as a placeholder, as shown in this example. ``` NSLocationAlwaysUsageDescription Placeholder Purpose String ``` # Troubleshoot Issues in iOS Service Extensions This guide provides a structured approach to troubleshooting common issues in iOS Service Extensions, ensuring seamless integration and functionality. ## Resolve Embedded Binary Signing Issues Embedded binary signing errors occur when you disable automatic signing and your Main Target and Notification Service Extension are signed with different certificates. If you encounter build failures or runtime issues related to code signing, follow these troubleshooting steps. - [Check your certificates](#check-your-certificates) - [Verify provisioning profiles](#verify-provisioning-profiles) - [Update the embedded binary’s signing settings](#update-the-embedded-binarys-signing-settings) - [Check app settings](#check-app-settings) ### Check Your Certificates 1. Make sure that the certificate you used for the parent app (main app) is the same as the one you used for the embedded extension. 2. Use the same distribution certificate for both targets. ### Verify Provisioning Profiles 1. On Xcode, navigate to **Preferences** > **Accounts** and make sure you selected the correct provisioning profile. 2. Make sure that both the parent app and the embedded binary share the same provisioning profile, and includes the right entitlements for both. 3. In case of manual profiles, download and install the latest provisioning profiles from the [Apple Developer](https://developer.apple.com/account) website. ### Update the Embedded Binary’s Signing Settings 1. In the Xcode project navigator, select the embedded binary. 2. Go to **General** > **Signing & Capabilities**. 3. Make sure **Automatically manage signing** is checked. If not, manually set the correct Team, Signing Certificate, and Provisioning Profile. 4. Make sure the embedded binary uses the same certificate and provisioning profile as the main app. ### Check App Settings 1. Make sure both the main app target and the embedded binary target are set to use the same provisioning profile and the same signing certificate. 2. Check each target’s **Signing & Capabilities** tab to verify this. ## Validate Entitlements and Permissions Make sure both your app and its extension are set up to use the same App Group. Check the entitlements file and the **App Groups** setting in both the app and extension targets. ``` com.apple.security.application-groups group.com.yourcompany.yourapp.shared ``` ## Check Info.plist Configuration A common source of errors in Service Extensions is incorrect `Info.plist` settings. To avoid potential issues, review these key configurations. ### Extension Key Make sure the `NSExtension` key in your extension’s `Info.plist` is set up correctly. For the Notification Service Extension, make sure that `NSExtensionPrincipalClass` is properly set. If you’re using Swift, prefix it with `$(PRODUCT_MODULE_NAME)` to link to the Swift class. ``` NSExtensionPrincipalClass $(PRODUCT_MODULE_NAME).NotificationService ``` ``` NSExtensionPrincipalClass NotificationService ``` ### AppGroup Key Make sure that the `SF_MARKETINGCLOUD_APP_GROUP_KEY` key in the `Info.plist` of your extension is set to the correct value. ## Check NotificationService Setup To make sure your Notification Service Extension functions correctly with the SDK, verify these configurations. ### Verify Correct Class Inheritance Make sure your `NotificationService` class inherits from `SFMCNotificationService`. Incorrect inheritance can cause the extension to not work properly. ### Enable Debug Logging Enable debug-level logging using the `sfmcProvideConfig()` method to help debug any issues when setting up the SDK. ``` override func sfmcProvideConfig() → SFNotificationServiceConfig { return SFNotificationServiceConfig(logLevel: .debug) } ``` ``` - (SFMCNotificationServiceConfig *)sfmcProvideConfig { return [[SFMCNotificationServiceConfig alloc] initWithLogLevel:SFMCExtensionSdkLogLevelDebug]; } ``` ## Check for Background Task Limitations Notification Service Extension has a limited time to handle notifications. Make sure your code doesn’t exceed these limits. For more information, see the official documentation on [Apple Developer](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/%3Chttps://developer.apple.com/documentation/usernotifications/unnotificationserviceextension/didreceive(_:withcontenthandler:)>). ## Handle App Crashes or Freezing Service extensions can have memory issues or use too many resources. Use Xcode’s Instruments (like Allocations and Leaks) to monitor memory usage and stay within limits. # Troubleshoot Issues on Android Apps Find solutions to common issues when implementing the MobilePush Android SDK in your app. - [Push Messages Not Displayed](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_android_push_messages_not_displayed.md) — Check SDK logs, send test pushes, and evaluate SDK state when messages don't appear in your app. - [Troubleshoot Initialization Errors](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_android_initialization_errors.md) — Resolve SDK initialization problems, including location permission errors and Google Play Services issues. - [Troubleshoot Multiple Push SDKs](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_android_multiple_push_sdks.md) — Configure the SDK when integrating multiple push providers in a single app. - [Troubleshoot Push Delivery Analytics](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_android_push_delivery_analytics.md) — Fix issues with push delivery analytics and ensure proper event tracking. # Troubleshoot Issues on iOS Apps Find solutions to common issues when you implement the Salesforce Engagement SDK in your iOS app. - [Troubleshoot the "No Such Module: 'SFMCSDK'" Error](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios_sfmcsdk_module.md) — Resolve a missing `SFMCSDK` module during a CocoaPods build. - [Troubleshoot App Submission Errors](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios_submission_errors.md) — Resolve errors from Xcode or Apple's app review during app submission. - [Troubleshoot APNs Server Configuration](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_apns_server_config.md) — Configure your Apple Push Notification service connection for development and production builds. - [Troubleshoot Push Message Display](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios_push_display.md) — Diagnose why push messages don't appear in your app. - [Troubleshoot Multiple Push SDKs](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios_multiple_sdks.md) — Configure the SDK to coexist with SDKs from other push providers. - [Troubleshoot Data Merges](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios_data_merge.md) — Merge tags and attributes when you upgrade from SDK version 7.x. - [Troubleshoot Data Protection](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios_data_protection.md) — Fix file access issues caused by iOS Data Protection settings. - [Handle Crashes](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios_keychain_crash.md) — Fix keychain-related crashes in SDK versions 8.0.13 and earlier. - [Troubleshoot MarketingCloudSDK.bundle Inclusion](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios_bundle_incl_crash.md) — Fix crashes caused by a missing SDK bundle in versions 8.0.13 and earlier. - [Troubleshoot Silent Push Notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios_silent_push.md) — Configure your app to receive and process silent push notifications. - [Troubleshoot Push Delivery Analytics](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios_push_analytics.md) — Resolve issues with missing or inaccurate push delivery analytics. ## Review Additional Troubleshooting Guidance Refer to these articles when you test your app, or to troubleshoot message delivery issues. - _Apple Developer_: [Technical Note TN2265: Troubleshooting Push Notifications](https://developer.apple.com/library/archive/technotes/tn2265/_index.html) - _Download_: [APNs Debugging Provisioning File](https://developer.apple.com/library/ios/technotes/tn2265/tn2265_PersistentConnectionLogging.zip) - _Apple Developer_: [APNs Port Functionality Information](https://support.apple.com/en-gb/102266) ## See Also - [Troubleshoot Issues in iOS Service Extensions](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios_extension.md) # Troubleshoot Multiple Push SDKs The Salesforce Engagement SDK can coexist and work in the same app as the SDKs of other push providers. However, we recommend checking with your other SDK vendors to ensure they also support a multi-push provider implementation. Consider these factors if you implement multiple push SDKs. ## Common Issues With Multiple Push Provider Some multiple push provider (MPP) implementations can prevent the transmission of device tokens and push messages. Without device tokens, the SDK doesn’t register the device properly. As a result, Marketing Cloud is unable to send push notifications to the device. The SDK expects you to pass push notifications to the `setNotificationRequest` method. Using this method makes the SDK aware of the notifications and lets it handle them accordingly. Apple has specific delegate methods that the consuming application must implement to register with APNs and receive push notifications. Implementing multiple push providers can affect the previously mentioned functionality since other vendors can provide wrapper methods for registration and receiving the notifications. Consuming applications often listen to the wrapper methods instead of actual Apple-provided delegate methods. An example of a common issue is when registration with Apple is done for one push provider without setting the `deviceToken` for other push providers. ## Handling MPP with the SDK Method Swizzling is the process of changing the implementation of a selector at runtime. If Method Swizzling is enabled, other push providers automatically intercept all the application delegate methods, which differ from the normal flow in setting up the `deviceToken` and notification `userinfo`. Method Swizzling can confuse SDK users about how and where to set the SDK’s required API methods because another provider is changing the implementation without their knowledge. To determine if other SDK providers use Swizzling, check to see if they use these methods. - `func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)` - `func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)` SDK users can handle MPP implementations regardless of whether Swizzling is enabled. For more information, see [Troubleshoot Multiple Push SDKs with Swizzling Enabled](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios_multiple_sdks_with_swizzling.md) and [Troubleshoot Multiple Push SDKs with Swizzling Disabled](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios_multiple_sdks_without_swizzling.md). ## Common Implementation Issues MPP implementation issues are often caused by issues related to device registration, badging, geolocation, custom payload keys, and feedback. - Registration: You must only make one call to a push SDK to register for push notifications. Otherwise, a single push notification can trigger multiple notification banners, alerts, or sounds. The SDK gives the app developer the power to register. - Notification Settings: An app can invoke `requestAuthorizationWithOptions` and `registerForRemoteNotifications` multiple times. However, only the settings from the last call are used, as each successive call overwrites the previous settings. - Badging: There’s no way to guarantee the value of a badge. - Custom Payload Keys: If your implementation must distinguish between two notification providers, use custom keys or other payload-specific data to ensure that your app calls the correct SDK handler that supports multiple notification handlers. Passing a third party’s notification to `setNotificationRequest` or `setNotificationUserInfo` is essentially a no-op call. The SDK only emits logs indicating the origin of the notification wasn’t from Engagement. - Geolocation: If you implement multiple SDKs that use location-enabled services, use only one SDK’s location enablement. Using more than one leads to unknown and unsupportable consequences. For example, the methods used by the other providers to interact with iOS `CoreLocation` services and enable location services are likely to affect each provider. An app can monitor a limited number of geofences at any given time. This number depends on iOS version, device type, and other considerations. With multiple implementations competing for a limited resource, the user experience can suffer. Additionally, permissions needed to use location-enabled SDKs can overlap or conflict. - Feedback: Not all providers are able to detect if a device has been unregistered. To see how notifications are handled using Firebase as a push provider, see the [iOS LearningApp](https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS/tree/spm/examples/LearningApp/LearningApp/AppDelegate.swift). # Troubleshoot Multiple Push SDKs on Android While you can integrate multiple push SDKs into a single app, this approach can lead to complications and we can't guarantee reliable results. The following sections highlight some considerations you must keep in mind as you develop your app with multiple push SDK integrations. Areas of concern can include registration, geolocation, and more. **important:** Any other push provider you choose must also allow a multiple push provider implementation. ## Remove SenderId from SDK Initialization **important:** Don't set the [`SenderId`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.config/-push-feature-config/-builder/set-sender-id.html) during the SDK's initialization. If the `SenderId` is set during initialization, the SDK attempts to fetch a push token from the Firebase SDK. Doing so can lead to inconsistencies in the token that is registered with Engagement. ## Handle Push Token Set the push token in the SDK whenever it has been retrieved or updated from the Firebase SDK. ``` try { FirebaseMessaging.getInstance().token.addOnCompleteListener { task -> if (task.isSuccessful) { SFMCSdk.requestSdk { sdk -> sdk.mp { it.pushMessageManager.setPushToken(task.result) } } } } } catch (e: java.lang.Exception) { Log.e(TAG, "Failed to retrieve InstanceId from Firebase.") } ``` ``` try { FirebaseMessaging.getInstance().token.addOnCompleteListener { task -> if (task.isSuccessful) { MarketingCloudSdk.requestSdk { sdk -> sdk.pushMessageManager.setPushToken(task.result) } } } } catch (e: Exception) { Log.e(TAG, "Failed to retrieve InstanceId from Firebase.") } ``` **important:** Not updating the SDK with a new push token when [`onNewToken`](https://firebase.google.com/docs/reference/android/com/google/firebase/messaging/FirebaseMessagingService) is triggered prevents Engagement from sending push messages to your application. ## Handle Push Message When a push message is received from Engagement, pass it into the SDK to be presented. ``` class MessagingService : FirebaseMessagingService() { override fun onMessageReceived(message: RemoteMessage) { if (PushMessageManager.isMarketingCloudPush(message)) { SFMCSdk.requestSdk { sdk -> sdk.mp { it.pushMessageManager.handleMessage(message) } } } else { //Not from Marketing Cloud Engagement. Must handle yourself. } } } ``` ``` class MessagingService : FirebaseMessagingService() { override fun onMessageReceived(message: RemoteMessage) { if (PushMessageManager.isMarketingCloudPush(message)) { MarketingCloudSdk.requestSdk { sdk -> sdk.pushMessageManager.handleMessage(message) } } else { //Not from Engagement. Must handle yourself. } } } ``` **important:** Messages passed into [`handleMessage`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/MarketingCloudSdk/9.0/-marketing%20-cloud%20-s-d-k/com.salesforce.marketingcloud.messages.push/-push-message-manager/handle-message.html) that aren't from Engagement are ignored. ## See Also - [Troubleshoot Issues on Android Apps](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_android.md) # Troubleshoot Multiple Push SDKs with Swizzling Disabled To disable Swizzling, refer to the other push provider’s documentation. When Swizzling is disabled in the other push provider, the default `AppDelegate` methods are called. ::::::tabset{tabs='["SDK v10", "SDK v8"]'} :::::tab For SDK version 10 and later, use this code: ```swift // Disable Swizzling in the other push provider used //registerForRemoteNotifications() method gets to this callback func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { PushFeature.requestSdk { pushFeature in pushFeature?.setDeviceToken(deviceToken) } } /** REQUIRED IMPLEMENTATION */ func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { PushFeature.requestSdk { pushFeature in pushFeature?.setNotificationUserInfo(userInfo) } completionHandler(.newData) } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { PushFeature.requestSdk { pushFeature in pushFeature?.setNotificationResponse(response) } completionHandler() } func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.banner, .list, .sound]) } ``` ::::: :::::tab For SDK version 8, use this code: ```swift // Disable Swizzling in the other push provider used //registerForRemoteNotifications() method gets to this callback func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { SFMCSdk.requestPushSdk { mp in mp.setDeviceToken(deviceToken) } } /** REQUIRED IMPLEMENTATION */ func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { SFMCSdk.requestPushSdk { mp in mp.setNotificationUserInfo(userInfo) } completionHandler(.newData) } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { SFMCSdk.requestPushSdk { mp in mp.setNotificationRequest(response.notification.request) } completionHandler() } func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.banner, .list, .sound]) } ``` ::::: :::::: ## See Also - [Troubleshoot Multiple Push SDKs](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios_multiple_sdks.md) - [Troubleshoot Multiple Push SDKs with Swizzling Enabled](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios_multiple_sdks_with_swizzling.md) # Troubleshoot Multiple Push SDKs with Swizzling Enabled If Swizzling is enabled, implement the other push provider’s delegate methods first. When that's complete, implement the Salesforce Engagement SDK methods. 1. Configure the SDK along with the other Push provider, as shown in these code examples.
Code example for iOS SDK v10 or later: ```swift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { if let options = launchOptions, let notification = options[UIApplication.LaunchOptionsKey.remoteNotification] as? [AnyHashable: Any] { self.notificationUserInfo = notification } FirebaseApp.configure() Messaging.messaging().delegate = self self.configureSdk() if #available(iOS 10.0, *) { UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: { _, _ in } ) } else { let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) } application.registerForRemoteNotifications() return true } @discardableResult func configureSdk() -> Bool { let appID = "" let accessToken = "" let appEndpointURL = "" let mid = "" #if DEBUG SFMCSdk.setLogger(logLevel: .debug) #endif let appEndpoint = URL(string: appEndpointURL)! var configBuilder = ConfigBuilder() let engagementConfiguration = MarketingCloudSdkConfigBuilder(appId: appID) .setAccessToken(accessToken) .setMarketingCloudServerUrl(URL(string: appEndpointURL)!) .setMid(mid) .setInboxEnabled(true) .setLocationEnabled(true) .setAnalyticsEnabled(true) .build() configBuilder = configBuilder .setEngagement(config: engagementConfiguration) let pushFeatureConfiguration = PushFeatureConfigBuilder() .setApplicationControlsBadging(true) .build() configBuilder = configBuilder .setPushFeature(config: pushFeatureConfiguration) // Set the completion handler to take action when all modules initialization is completed. // Seting the completion handler is optional. let completionHandler: ((_ status: [ModuleInitStatus]) -> Void) = { [weak self] status in DispatchQueue.main.async { self?.handleSDKInitializationCompletion(status: status) } } SFMCSdk.initializeSdk(configBuilder.build(), completion: completionHandler) return true } // MARK: - SDK Initialization Completion Handler private func handleSDKInitializationCompletion(status: [ModuleInitStatus]) { var allSuccessful = true for moduleStatus in status { print("Module: \(moduleStatus.moduleName.rawValue), Status: \(moduleStatus.initStatus.rawValue)") if moduleStatus.initStatus == .success { // Handle successful initialization for each module switch moduleStatus.moduleName { case .engagement: // Handle successful initialization for Marketing cloud module case .pushFeature: // Handle successful initialization for Push Feature module default: break } } else if moduleStatus.initStatus == .error { allSuccessful = false // module failed to initialize, check logs for more details } else if moduleStatus.initStatus == .cancelled { allSuccessful = false // module initialization was cancelled (for example due to re-confirguration triggered before init was completed) } else if moduleStatus.initStatus == .timeout { allSuccessful = false // module failed to initialize due to timeout, check logs for more details } } if allSuccessful { print("SDK initialization completed successfully") } else { print("SDK initialization completed with errors - check logs above") } } ```
Code example for iOS SDK v8: ```swift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { if let options = launchOptions, let notification = options[UIApplication.LaunchOptionsKey.remoteNotification] as? [AnyHashable: Any] { self.notificationUserInfo = notification } FirebaseApp.configure() Messaging.messaging().delegate = self self.configureSFMCSdk() if #available(iOS 10.0, *) { UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization( options: authOptions, completionHandler: { _, _ in } ) } else { let settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) } application.registerForRemoteNotifications() return true } @discardableResult func configureSFMCSdk() -> Bool { let appID = "" let accessToken = "" let appEndpointURL = "" let mid = "" #if DEBUG SFMCSdk.setLogger(logLevel: .debug) #endif let appEndpoint = URL(string: appEndpointURL)! let mobilePushConfiguration = PushConfigBuilder(appId: appID) .setAccessToken(accessToken) .setMarketingCloudServerUrl(appEndpoint) .setMid(mid) .setInboxEnabled(true) // enable if needed by your application .setLocationEnabled(true) // enable if needed by your application .setAnalyticsEnabled(true) // enable if needed by your application .build() let completionHandler: (OperationResult) -> () = { result in if result == .success { self.setupMobilePush() } else if result == .error { } else if result == .cancelled { } else if result == .timeout { } } SFMCSdk.initializeSdk(ConfigBuilder().setPush(config: mobilePushConfiguration, onCompletion: completionHandler).build()) return true ```
2. Configure the SDK to set the device token, as shown in these code examples.
Code example for iOS SDK v10 or later: ```swift // MARK: FireBaseMessaging Delegate /** Set deviceToken to MarketingCloudSDK in the FCM delegate method when Swizzling is enabled. DeviceToken must be set MANDATORILY to MarketingCloudSDK using`SFMCSdk.mp.setDeviceToken` API for Push notifications to be received through Mobile Push. */ extension AppDelegate : MessagingDelegate { func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) { print("FCM Token", fcmToken ?? "") PushFeature.requestSdk { pushFeature in print("SDK is operational") if let apnsToken = messaging.apnsToken { print("Setting APNs token in MarketingCloudSDK") pushFeature?.setDeviceToken(apnsToken) } else { print("fcm token is null") } print("SDK is not yet operational") } } } ```
Code example for iOS SDK v8: ```swift // MARK: FireBaseMessaging Delegate /** Set deviceToken to MarketingCloudSDK in the FCM delegate method when Swizzling is enabled. DeviceToken must be set MANDATORILY to MarketingCloudSDK using`SFMCSdk.mp.setDeviceToken` API for Push notifications to be received through Mobile Push. */ extension AppDelegate : MessagingDelegate { func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) { print("FCM Token", fcmToken ?? "") SFMCSdk.requestPushSdk { mp in print("SDK is operational") if let apnsToken = messaging.apnsToken { print("Setting APNs token in MarketingCloudSDK") mp.setDeviceToken(apnsToken) } else { print("fcm token is null") } print("SDK is not yet operational") } } } ```
``` When Swizzling is enabled in the other push provider, respective delegate methods are intercepted. For example, when a push notification is received from Firebase, the payload received in the `didReceive` notification method for the `UNUserNotificationCenterDelegate` is altered to receive a `MessagingMessageInfo` object. Because the payload doesn’t match the format that the SDK expects, the message isn’t reported. To handle this situation, implement the delegate methods described in these code examples.
Code example for iOS SDK v10 or later: ```swift /* REQUIRED IMPLEMENTATION */ func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { PushFeature.requestSdk { pushFeature in pushFeature?.setNotificationUserInfo(userInfo) } completionHandler(.newData) } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { PushFeature.requestSdk { pushFeature in pushFeature?.setNotificationResponse(response) } completionHandler() } func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.banner, .list, .sound]) } ```
Code example for iOS SDK v8: ```swift /* REQUIRED IMPLEMENTATION */ func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { SFMCSdk.requestPushSdk { mp in mp.setNotificationUserInfo(userInfo) } completionHandler(.newData) } func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { SFMCSdk.requestPushSdk { mp in mp.setNotificationRequest(response.notification.request) } completionHandler() } func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.banner, .list, .sound]) } ```
Notification messages from other providers appear in the device’s notification center. However, any action on the notification message from the SDK, such as URL handling or reporting, doesn’t work. ## See Also - [Troubleshoot Multiple Push SDKs](mc_engagement_troubleshooting_ios_multiple_sdks.md) - [Troubleshoot Multiple Push SDKs with Swizzling Disabled](mc_engagement_troubleshooting_ios_multiple_sdks_without_swizzling.md) # Troubleshoot Push Delivery Analytics If you encounter issues with push delivery analytics, consider these common problems and their resolutions: - Missing Push Delivery Analytics - : First, confirm that push delivery analytics is turned on in Marketing Cloud Engagement. If analytics is turned off, work with a Marketing Admin to turn it on. If push delivery events and analytics don’t appear in your reports, verify that you’re sending supported message types. Push delivery analytics are only available for Push and Alert + Inbox messages. In-app, location, and silent messages aren’t tracked. - Multiple Push Provider Implementation Problems - : If you use multiple push providers, make sure that no fields or keys are removed from the push payload before you pass it to `SFMCNotificationService`, which your `NotificationService` class in the service extension inherits from. The SDK requires the complete push payload to process push delivery events. If any keys or fields are missing, the SDK logs a warning and doesn’t process the push delivery event. # Troubleshoot Push Delivery Analytics on Android When encountering issues with push delivery analytics, consider these common problems and their resolutions: - Missing Push Delivery Analytics - : - First confirm that push delivery analytics is enabled in the Engagement UI. If disabled, your Engagement admin must enable it for the SDK to send delivery events. - If push delivery events and analytics aren't appearing in your Engagement reports, verify whether you're sending supported message types. Push delivery analytics are only available for Push and Alert + Inbox messages. In-App, Geofence, Proximity, and silent pushes aren't tracked. - Multiple Push Provider Implementation Problems - : If you're using multiple push providers, ensure that no fields or keys are removed from the push payload before passing it to [SFMC `PushMessageManager.handleMessage`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/MarketingCloudSdk/9.0/-marketing%20-cloud%20-s-d-k/com.salesforce.marketingcloud.messages.push/-push-message-manager/index.html#-1329426742%2FFunctions%2F165651098). The SDK requires the complete push payload to process push delivery events. If any keys or fields are missing, the SDK logs a warning and doesn't process the push delivery event. ## See Also - [Troubleshoot Issues on Android Apps](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_android.md) - [Troubleshoot Multiple Push SDKs on Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_android_multiple_push_sdks.md) # Troubleshoot Push Messages Not Displayed on Android If you encounter issues receiving messages in an app that uses the Salesforce Engagement SDK, consider these troubleshooting steps. - [Check the SDK log](#check-the-sdk-logs) - [Send a test push](#send-a-test-push) - [Evaluate the SDK state](#evaluate-the-sdk-state) ## Check the SDK Logs 1. Enable logging in the SDK. 2. Check the log for errors. The SDK provides verbose messages that are helpful in identifying and rectifying errors. 3. To capture the log output from the SDK, add the [MCLogListener](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sdk/com.salesforce.marketingcloud/-m-c-log-listener/index.html) interface. ```java // Enable SFMC logging SFMCSdk.setLogging(LogLevel.DEBUG, LogListener.AndroidLogger()) // Set Log Level MarketingCloudSdk.setLogLevel(MCLogListener.VERBOSE) // Set Android Logcat Log Listener MarketingCloudSdk.setLogListener(MCLogListener.AndroidLogListener()) ``` 4. Implement a custom log listener. ```java // Custom Logger implementation class MyLogger : MCLogListener, LogListener { override fun out(level: Int, tag: String, message: String, throwable: Throwable?) { // level: VERBOSE, DEBUG, INFO, WARN, ERROR // Do something with the log output } override fun out(level: LogLevel, tag: String, message: String, throwable: Throwable?) { // level: DEBUG, WARN, ERROR // Do something with the log output } } // Set Custom Log Listener MarketingCloudSdk.setLogListener(MyLogger()) ``` ## Send a Test Push To test whether your device can receive a push directly from FCM, follow these steps. 1. Get the push token from the SDK.
View code example for SDK version 8 ```java SFMCSdk.requestSdk { sdk -> sdk.mp { it.pushMessageManager.pushToken?.let { token -> Log.d("TOKEN", token) } } } ```
View code example for SDK version 7 ```java MarketingCloudSdk.requestSdk { sdk -> Log.d("TOKEN", sdk.pushMessageManager.pushToken) } ```
2. Use this script to send yourself a push message. ```bash #!/usr/bin/env bash export PUSH_TOKEN=#Use push token from SDK's PushMessageManager#getPushToken() method export FCM_SERVER_KEY=#Use value from Firebase console curl --header "Authorization: key=$FCM_SERVER_KEY" \ --header Content-Type:"application/json" \ https://fcm.googleapis.com/fcm/send \ -d "{\"to\":\"$PUSH_TOKEN\",\"data\":{\"_m\":\"test_message\",\"alert\":\"It Worked!\",\"title\":\"Test Push\", \"_sid\":\"SFMC\"}}" ``` If your device successfully receives a message using the sample script but still can't receive a message from Marketing Cloud Engagement, follow these steps. 1. Wait 15 minutes after the first registration call for the device you're testing with to ensure your device is properly registered in Engagement. 2. Check the **List** you created in the Engagement UI and ensure the `DeviceId` you printed in [Logcat](https://developer.android.com/tools/logcat) shows up in the list. **note:** For information about sending a test message in the Marketing Cloud Engagement, see [Send a Test Message to Validate Accuracy](https://help.salesforce.com/s/articleView?id=mktg.mc_mp_test_send.htm). ## Evaluate the SDK state Look through the output from the SDK's [`getSdkState()`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/sfmcsdk/com.salesforce.marketingcloud.sfmcsdk/-s-f-m-c-sdk/get-sdk-state.html) method. **note:** Sometimes the output from the SDK's Get State method can exceed Android's output length restrictions. Adding an `indentSpaces` to the output of JSONObjects can help bypass this restriction.
View code example for SDK version 8 and later ```java if (BuildConfig.DEBUG) { // Enable Logging _BEFORE_ calling the SDK's configure/init method SFMCSdk.setLogging(LogLevel.DEBUG, LogListener.AndroidLogger()) MarketingCloudSdk.setLogLevel(VERBOSE) MarketingCloudSdk.setLogListener(MCLogListener.AndroidLogListener()) // When the SDK is ready, output its state to the logs SFMCSdk.requestSdk { // Specifically get the push state information with(it.getSdkState()["PUSH"] as JSONObject) { // General Troubleshooting Log.i("~#SdkState", "initConfig: ${this["initConfig"]}") Log.i("~#SdkState", "initStatus: ${this["initStatus"]}") Log.i("~#SdkState", "PushMessageManager: ${(this["PushMessageManager"] as JSONObject).toString(2)}") Log.i("~#SdkState", "RegistrationManager: ${(this["RegistrationManager"] as JSONObject).toString(2)}") // Troubleshoot InApp Messages Log.i("~#SdkState", "InAppMessageManager: ${(this["InAppMessageManager"] as JSONObject).toString(2)}") Log.i( "~#SdkState", "InApp Messages: ${((this["InAppMessageManager"] as JSONObject)["messages"] as JSONArray).toString(2)}" ) // Get Everything Log.i("~#SdkState", "InApp Events: ${(this["Event"] as JSONObject).toString(2)}") } } } ```
View code example for SDK version 7 ```java if (BuildConfig.DEBUG) { // Enable Logging _BEFORE_ calling the SDK's configure/init method MarketingCloudSdk.setLogLevel(VERBOSE) MarketingCloudSdk.setLogListener(MCLogListener.AndroidLogListener()) // When the SDK is ready, output its state to the logs MarketingCloudSdk.requestSdk { // Specifically get the push state information with(it.sdkState) { // General Troubleshooting Log.i("~#SdkState", "initConfig: ${this["initConfig"]}") Log.i("~#SdkState", "initStatus: ${this["initStatus"]}") Log.i("~#SdkState", "PushMessageManager: ${(this["PushMessageManager"] as JSONObject).toString(2)}") Log.i("~#SdkState", "RegistrationManager: ${(this["RegistrationManager"] as JSONObject).toString(2)}") // Troubleshoot InApp Messages Log.i("~#SdkState", "InAppMessageManager: ${(this["InAppMessageManager"] as JSONObject).toString(2)}") Log.i( "~#SdkState", "InApp Messages: ${((this["InAppMessageManager"] as JSONObject)["messages"] as JSONArray).toString(2)}" ) // Get Everything Log.i("~#SdkState", "InApp Events: ${(this["Event"] as JSONObject).toString(2)}") } } } ```
When you debug push messaging, focus on the [NotificationManager](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.notifications/-notification-manager/index.html) and [PushMessageManager](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.push/-push-message-manager/index.html) sections for key insights.
View code example for SDK version 8 ```json { "sfmcSDKVersion": "1.0.2", "PUSH": { "initConfig": "MarketingCloudConfig(applicationId=, accessToken=, senderId=, marketingCloudServerUrl=http://localhost:43683/, mid=null, analyticsEnabled=true, geofencingEnabled=true, inboxEnabled=true, piAnalyticsEnabled=true, proximityEnabled=true, markMessageReadOnInboxNotificationOpen=true, delayRegistrationUntilContactKeyIsSet=false, useLegacyPiIdentifier=true, notificationCustomizationOptions={notificationBuilder=com.salesforce.marketingcloud.explorer.sdk.SdkInterfaces}, urlHandler=com.salesforce.marketingcloud.explorer.sdk.SdkInterfaces@6b985d4, appPackageName=com.salesforce.marketingcloud.explorer.debug, appVersionName=8.0.5-SNAPSHOT.DEBUG, predictiveIntelligenceServerUrl=https://app.igodigital.com/api/v1/collect/process_batch)", "initStatus": "InitializationStatus(status=SUCCESS, unrecoverableException=null, locationsError=false, playServicesStatus=0, playServicesMessage=SUCCESS, encryptionChanged=false, storageError=false, proximityError=false, messagingPermissionError=false, sslProviderEnablementError=false, initializedComponents=[BehaviorManager, LifecycleManager, RequestManager, AlarmScheduler, SyncRoute, ControlChannel, LocationManager, ProximityManager, AnalyticsManager, InboxMessageManager, NotificationManager, RegionMessageManager, PushMessageManager, RegistrationManager, InAppMessageManager, Event], isUsable=true)", "RequestManager": {}, "AlarmScheduler": { "pending_alarms": {} }, "ControlChannel": { "flag": "NONE" }, "LocationManager": { "geofencingEnabled": true, "proximityEnabled": true, "apiCode": 0, "apiMessage": "SUCCESS", "locationRequests": 0, "locationsReceived": 0, "geofenceEvents": 0 }, "ProximityManager": { "proximityEnabled": true, "enteredEvents": 0, "exitedEvents": 0 }, "AnalyticsManager": { "bet_analytics": true, "et_analytics": true, "pi_analytics": true, "device_stats": true }, "InboxMessageManager": { "inbox_messages": "[]" }, "NotificationManager": { "notificationsEnabled": true, "shouldShowNotificationListener": "com.salesforce.marketingcloud.explorer.sdk.SdkInterfaces" }, "RegionMessageManager": { "geofenceMessagingEnabled": false, "proximityMessagingEnabled": false, "geofence_regions": "[]", "geofence_region_messages": "[]", "proximity_regions": "[]", "proximity_region_messages": "[]", "boot_complete_permission": true }, "PushMessageManager": { "pushEnabled": true, "tokenRefreshListeners": [ "com.salesforce.marketingcloud.explorer.sdk.SdkModule$$ExternalSyntheticLambda1" ], "debugInfo": { "senderId": "", "deviceToken": "", "firebaseApps": [ "FirebaseApp{name=[DEFAULT], options=FirebaseOptions{applicationId=1::android:, apiKey=, databaseUrl=null, gcmSenderId=null, storageBucket=null, projectId=et-public-demo-app}}" ], "c2dmReceiver": [ { "name": "com.google.firebase.iid.FirebaseInstanceIdReceiver", "priority": 0 } ], "instanceIdService": [], "messagingService": [ { "name": "com.salesforce.marketingcloud.messages.push.MCFirebaseMessagingService", "priority": -1 }, { "name": "com.google.firebase.messaging.FirebaseMessagingService", "priority": -500 } ] } }, "RegistrationManager": { "current_registration": { "deviceID": "18324364E1C9D141F1ABC9E8B33FC5938C5DA61B0E52AB8E434CBD202ED9BD93", "device_Token": "", "sdk_Version": "8.0.5.0", "app_Version": "8.0.5-SNAPSHOT.DEBUG : 23600000", "dST": false, "location_Enabled": false, "proximity_Enabled": false, "platform_Version": "12", "push_Enabled": true, "timeZone": "-18000", "platform": "Android", "hwid": "Google Pixel 4", "etAppId": "", "locale": "en_US", "tags": ["ALL", "Android", "DEBUG"], "attributes": [] }, "last_sent_timestamp": "2022-03-09T18:10:41.107Z" }, "InAppMessageManager": { "messages": [], "eventListener": "com.salesforce.marketingcloud.explorer.sdk.SdkInterfaces", "subscriberToken": "null", "custom_font_set": false, "status_bar_color": -13615201 }, "Event": { "triggers": [] } } } ```
View code example for SDK version 7 ```json { "initConfig": "MarketingCloudConfig(applicationId=, accessToken=, senderId=, marketingCloudServerUrl=http://localhost:39241/, mid=null, analyticsEnabled=true, geofencingEnabled=true, inboxEnabled=true, piAnalyticsEnabled=true, proximityEnabled=true, markMessageReadOnInboxNotificationOpen=true, delayRegistrationUntilContactKeyIsSet=false, useLegacyPiIdentifier=true, notificationCustomizationOptions={smallIconResId=2131230860, launchIntentProvider=com.salesforce.marketingcloud.explorer.sdk.SdkInterfaces, channelIdProvider=com.salesforce.marketingcloud.explorer.sdk.SdkInterfaces}, urlHandler=com.salesforce.marketingcloud.explorer.sdk.SdkInterfaces@1133e7c, appPackageName=com.salesforce.marketingcloud.explorer.debug, appVersionName=7.4.4.DEBUG, predictiveIntelligenceServerUrl=https://app.igodigital.com/api/v1/collect/process_batch)", "initStatus": "InitializationStatus(status=SUCCESS, unrecoverableException=null, locationsError=false, playServicesStatus=0, playServicesMessage=SUCCESS, encryptionChanged=false, storageError=false, proximityError=false, messagingPermissionError=false, sslProviderEnablementError=false, initializedComponents=[BehaviorManager, LifecycleManager, RequestManager, AlarmScheduler, SyncRoute, ControlChannel, LocationManager, ProximityManager, AnalyticsManager, InboxMessageManager, NotificationManager, RegionMessageManager, PushMessageManager, RegistrationManager, InAppMessageManager, Event], isUsable=true)", "RequestManager": {}, "AlarmScheduler": { "pending_alarms": {} }, "ControlChannel": { "flag": "NONE" }, "LocationManager": { "geofencingEnabled": true, "proximityEnabled": true, "apiCode": 0, "apiMessage": "SUCCESS", "locationRequests": 0, "locationsReceived": 0, "geofenceEvents": 0 }, "ProximityManager": { "proximityEnabled": true, "enteredEvents": 0, "exitedEvents": 0 }, "AnalyticsManager": { "bet_analytics": true, "et_analytics": true, "pi_analytics": true, "device_stats": true }, "InboxMessageManager": { "inbox_messages": "[]" }, "NotificationManager": { "notificationsEnabled": true, "shouldShowNotificationListener": "com.salesforce.marketingcloud.explorer.sdk.SdkInterfaces" }, "RegionMessageManager": { "geofenceMessagingEnabled": false, "proximityMessagingEnabled": false, "geofence_regions": "[]", "geofence_region_messages": "[]", "proximity_regions": "[]", "proximity_region_messages": "[]", "boot_complete_permission": true }, "PushMessageManager": { "pushEnabled": true, "tokenRefreshListeners": [ "com.salesforce.marketingcloud.explorer.sdk.SdkModule$$ExternalSyntheticLambda1", "com.salesforce.marketingcloud.explorer.sdk.SdkModule$$ExternalSyntheticLambda1" ], "debugInfo": { "senderId": "", "deviceToken": "", "firebaseApps": [ "FirebaseApp{name=[DEFAULT], options=FirebaseOptions{applicationId=, apiKey=, databaseUrl=null, gcmSenderId=null, storageBucket=null, projectId=et-public-demo-app}}" ], "c2dmReceiver": [ { "name": "com.google.firebase.iid.FirebaseInstanceIdReceiver", "priority": 0 } ], "instanceIdService": [], "messagingService": [ { "name": "com.salesforce.marketingcloud.messages.push.MCFirebaseMessagingService", "priority": -1 }, { "name": "com.google.firebase.messaging.FirebaseMessagingService", "priority": -500 } ] } }, "RegistrationManager": { "current_registration": { "deviceID": "CECBFF7A84675A152774E60FDE7C461263DFF3957013B0771B39D89F2EA6D41B", "device_Token": "", "sdk_Version": "7.4.4", "app_Version": "7.4.4.DEBUG : 23240000", "dST": false, "location_Enabled": false, "proximity_Enabled": false, "platform_Version": "14", "push_Enabled": true, "timeZone": 19800, "platform": "Android", "hwid": "Google Pixel 7", "etAppId": "", "locale": "en_US", "tags": ["ALL", "Android", "DEBUG"], "attributes": [] }, "last_sent_timestamp": "2024-04-22T07:45:35.509Z" }, "InAppMessageManager": { "messages": [], "eventListener": "com.salesforce.marketingcloud.explorer.sdk.SdkInterfaces", "subscriberToken": "", "custom_font_set": false, "status_bar_color": -13615201 }, "Event": { "triggers": [] } } ```
If you’ve implemented multiple push providers, review [Troubleshoot Multiple Push SDKs](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_android_multiple_push_sdks.md) for more information. ## See Also - [Troubleshoot Issues on Android Apps](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_android.md) # Troubleshoot the "No Such Module 'SFMCSDK'" Error If Xcode can't find required modules for the Salesforce Engagement SDK, it reports this build error: "No such module 'SFMCSDK'". The required dependencies for the SDK include the `SFMCSDK` module automatically. Don't install this module manually. ## Resolve This Issue Complete these steps to resolve this error. 1. Confirm that your Podfile contains the pods listed in [Implement the SDK with CocoaPods](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_integrate_ios/engagement_sdk_guide_integrate_ios_cocoapods.md) for your SDK version. 2. Run `pod install`. ## See Also - [Implement the SDK with CocoaPods](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_integrate_ios/engagement_sdk_guide_integrate_ios_cocoapods.md) # Troubleshoot Your Push Implementation Diagnose issues with push notification delivery, display, and analytics reporting in the Salesforce Engagement SDK. Before you troubleshoot these scenarios, review the basic troubleshooting information for [Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_android.md) and [iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios.md) apps to rule out any fundamental implementation issues. ## Troubleshooting Checklist While troubleshooting, consider these questions when testing and validating push notifications: - Is the device registered in Marketing Cloud Next or Marketing Cloud Engagement with a valid device token? - Is the device opted-in to receive push notifications? - If you use the SDK with Marketing Cloud Engagement, is the contact or device in the refreshed audience list or data extension that you sent the message to? - If you use the SDK with Marketing Cloud Next, is the contact and their corresponding device in the segment that you sent the message to? - Does Marketing Cloud show that the send job is complete? If you answered Yes to all of these questions, but the device didn't receive the notification, there's likely an issue with the implementation. If you answered No to all of these questions, your implementation probably has an issue with registration or setting up your audience. In either case, review these troubleshooting steps to identify and resolve the issue. ## Contacts Aren’t Receiving Push Notifications Contacts fail to receive push notifications for several reasons: - The contact is associated with an invalid device token - The contact is opted out for one of these reasons: - Invalid or malformed registrations - Feedback from the push notification service (Apple or Google) - Mismatched credentials (Sender ID, p12 Certificate, or p8 Auth Key) - Contact opted out on the device - The contact wasn’t in the audience list, data extension, or segment for the push notification ### Review Invalid Device Tokens The process of retrieving device tokens varies across platforms. For iOS, the app retrieves the device token and then forwards it to the SDK. For Android, the SDK typically manages the retrieval and registration of the device token automatically on behalf of the app. For more information, refer to steps 1–3 in this diagram. ![Push Notification Sequence of Events](https://developer.salesforce.com/media/overview/Mkting_MobilePush_SequenceDiag_PushNotification_041124_zh.png '{"class": "image-lg"}') Some Android implementations interfere with the process of retrieving the device token, which requires the app to forward the device token to the SDK, similar to iOS. In this situation, make sure that the app forwards an unmodified token to the SDK. Altering the device token risks creating a malformed, invalid, or delayed device token. In some cases, the app can fail to forward the device token to the SDK and Marketing Cloud entirely. First, review the registration and the device token by the SDK by following the [steps to troubleshoot registrations](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_initialization_registration.md). Next, review the logs and the SDK state output. To review the device token and other details stored in Marketing Cloud Engagement, follow these steps. 1. In Audience Builder, go to **Contact Builder** > **All Contacts** > **MobilePush**. 2. Search for and select the contact key or device ID for the user that you’re troubleshooting. ![The All Contacts page in Audience Builder showing a filled in search box and a contact that matches the search.](https://developer.salesforce.com/media/troubleshooting/select-contact-key-from-all-contacts.png) 3. On the **Attributes** tab for the contact, in the **MobilePush Data** section, review the details for the contact. Confirm that the device token, which is labeled **System Token** in the UI, is well-formed and that the **Status** is active. ![The MobilePush Data section of the Attributes tab for a contact, showing the contact details.](https://developer.salesforce.com/media/troubleshooting/review-mobilepush-channel-details.png) ### Review Contact Opt-Out Status Make sure that the contact isn’t opted out because of an invalid registration. Confirm that the SDK is initialized and is configured to register a valid device token. Verify that the value of the `push_Enabled` field is `true`. If either of these values is missing from the registration payload, Marketing Cloud sets the contact as opted out. Review the registration and the device token by following the [steps to troubleshoot registrations](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_initialization_registration.md). Next, review the logs and the SDK state output. To review opted out information in Marketing Cloud Engagement, follow these steps. 1. In Audience Builder, go to **Contact Builder** > **All Contacts**. 2. Select the **Mobile** channel. 3. Search for and select the contact key or device ID for the user that you’re troubleshooting. 4. On the **Membership** tab, review the contact’s opt-out information. If the status is Not Opted In, the contact has opted not to receive push notifications. ![The Membership tab for a contact, showing the contact's opt status.](https://developer.salesforce.com/media/troubleshooting/review-contact-opt-out-information.png) ### Review Contact Opt-Out Reason Every time Marketing Cloud sends a push notification to the push notification service, it receives feedback on whether the send succeeded or failed. Some failure states are due to invalid or malformed tokens. The causes of this issue are noted under [Review Invalid Device Tokens](#review-invalid-device-tokens). Other failure states occur when the contact opts out of receiving push notifications. In this case, Marketing Cloud reacts to the feedback from the push notification service by updating the contact record to opt that contact out. To review the time and reason that a user was opted out in Marketing Cloud Engagement, follow these steps. 1. In Audience Builder, go to **Contact Builder** > **All Contacts**. 2. Select the **Mobile** channel. 3. On the **MobilePush** tab, search for and select the contact key or device ID for the user that you’re troubleshooting. 4. On the **Membership** tab, review the opt-out information. The push notification services give feedback on a best effort basis. The services don’t always inform Marketing Cloud immediately after a contact opts out. For example, aggressive testing scenarios can cause delays with the push notification service. As a result, the service might not give accurate opt-out feedback for several send attempts. ### Review Mismatched Credentials Check whether your Android and iOS credentials, server key, and `.p8` authentication key that you uploaded in Marketing Cloud are correct. Mismatched credentials cause your sends to fail. To ensure that your credentials are uploaded correctly, see _Salesforce Help_: [Add Provisioning Info to Your App](https://help.salesforce.com/s/articleView?id=mktg.mc_mp_provisioning_info.htm). ## Contact Not in the Push Notification Audience or Data Extension To send a message, Engagement requires a contact key. For MobilePush, Engagement uses the contact key to look up the corresponding device information for that audience, and then sends the message to their device or devices. Before sending a test push notification, verify that the filtered list, filtered data extension, or standard data extension contains the correct contact keys for the recipients. To ensure that the contact keys are correct, refresh your audience before you send. 1. In Engagement, navigate to **Mobile Studio** > **MobilePush** > **Overview** tab. 2. Create a message. 3. On the **Select Audience** step, select the list. 4. Select **Auto-refresh before send** before clicking **Next**. 5. Finish creating your test message and send. Depending on the automations set up within your account, added or modified audience records may not automatically be reflected in the filtered lists or filtered data extensions that you’re trying to send with. To ensure the contact key record is populated in the list or data extension you’re testing with, refresh the filtered list or filtered data extension. Standard data extensions don’t require a refresh. ## Push Messages Received But Not Displayed Ensure that you correctly configure any overrides or customizations to push notification handling, such as supporting rich image notifications or saving notifications locally in the app or inbox. Review information about customized notifications in the platform-specific push notification guides for [Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_push_notifications/mc_engagement_push_notifications_android.md) and [iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_push_notifications/mc_engagement_push_notifications_ios.md). Silent push notifications are notifications that your app receives in the background. They’re designed for processing without displaying on the device. To enable your app to handle silent push notifications, use the [`SilentPushListener`](https://salesforce-marketingcloud.github.io/MarketingCloudSDK-Android/javadocs/SFMCSdk/11.0/pushfeaturemodule/com.salesforce.marketingcloud.pushfeature.push/-push-message-manager/-silent-push-listener/index.html) method in Android. For iOS, see [Silent Push Notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_troubleshooting/mc_engagement_troubleshooting_ios_silent_push.md). ## Open or Engagement Analytics Don’t Appear in Engagement After a contact opens a notification on the device, the SDK records the analytic event. The SDK submits analytics to Engagement after the application goes into the background or comes into the foreground. If a user forces the app to close, the analytic event is stored and submitted to Engagement after the next app open. It can take up to five minutes for Engagement servers to process and make the analytics available. The three most common reasons for why engagement analytics don’t show up in Engagement are tied to initialization of the SDK. - Failed or delayed initialization can lead to delayed, duplicate, or missing analytics data. Make sure that the SDK initializes successfully in your app. - The SDK records and submits analytic events only if `etanalytics` is configured. As part of initialization, ensure that the builder is configured with `etanalytics` enabled. - Android requires a callback for analytics. If you use push SDKs from multiple providers in your app, see the [Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_troubleshooting/mc_engagement_troubleshooting_android_multiple_push_sdks.md) and [iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_troubleshooting/mc_engagement_troubleshooting_ios_multiple_sdks.md) troubleshooting guides. # Troubleshooting Diagnose and resolve common issues with the Engagement SDK, including contact registration, push notification delivery, and platform-specific implementation problems. - [Troubleshoot Initialization and Registration](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_initialization_registration.md) — Resolve issues with contacts and devices that don't appear in Marketing Cloud Engagement. - [Troubleshoot Push Implementation](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_push.md) — Diagnose why contacts don't receive push notifications or why engagement analytics don't appear. - [Troubleshoot Issues on Android Apps](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_android.md) — Find fixes for Android-specific initialization, multiple-SDK, and push delivery analytics issues. - [Troubleshoot Issues on iOS Apps](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios.md) — Find fixes for iOS-specific push notification, credential, and app submission issues. - [Troubleshoot Issues in iOS Service Extensions](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting_ios_extension.md) — Fix signing, entitlement, and configuration issues in Notification Service Extensions. # Unblock Network Ports Testing your app while connected to a corporate network can prevent your test device from receiving messages, especially if your firewall blocks certain ports. Unblock these TCP ports to ensure that your test device can reach the APNs servers. | TCP Port | Description | | -------- | -------------------------------------------------------------------------------------------------------------------- | | 5223 | Used by devices to communicate to the APNs servers | | 2195 | Used to send notifications to the APNs servers | | 2196 | Used by the APNs feedback service | | 443 | Used as a fallback service for Wi-Fi devices when those devices can’t communicate with the APNs service on port 5223 | # Unified Flutter Setup The unified Flutter setup works with Marketing Cloud Engagement and Marketing Cloud Next. Its plugins wrap the native Android and iOS libraries behind a single, consistent, modular Dart surface using Flutter's platform channels. **note:** If you use the Marketing Cloud Engagement-specific version of the Flutter plugin, you can [migrate to the Flutter unified plugin](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/migrate-to-flutter-unified-plugin.md). ## Who Should Use This Setup Use this setup if: - You're integrating Flutter for the first time. - You're implementing Marketing Cloud Engagement with Flutter. - You're implementing Marketing Cloud Next with Flutter. ## Prerequisites Make sure these components meet the baseline requirements: | Components | Minimum Requirement | | ---------- | ------------------------ | | Flutter | 3.3.0 or later | | Dart SDK | >=3.0.6 <4.0.0 | | iOS | 12.0 or later | | Android | minSdk 26, compileSdk 36 | ## Select your Package The non-unified version of the Flutter plugin integrated Marketing Cloud features by using a single monolithic plugin that covered the entire SDK surface. The unified plugin splits the functionality into focused packages that use a consistent `requestSdk()` API. Its modular design ensures that your app includes only the required functionality. The unified Flutter plugin offers these packages: - **Product packages:** Represent a Marketing Cloud product. Install the `sfmc_marketingcloudsdk` package for Marketing Cloud Engagement, the `sfmc_mobileappmessaging` package for Marketing Cloud Next, or both. - **Core package:** `sfmc_core` provides the foundation that both product packages require. When you install a product package, the system resolves it automatically. - **Feature packages:** Packages for handling push notifications (`sfmc_push`) and in-app messages (`sfmc_iam`) are optional add-ons. Install only the features that your app needs. ## Architecture - **Melos workspace** — The plugins are organized as a Melos workspace monorepo. Each package is independently versioned and publishable. - **requestSdk() pattern** — Every package exposes a static `requestSdk()` method that initializes the native SDK. - **Event streams** — Modules use `EventChannel` to expose Dart streams for streaming events such as push token refresh, registration changes, and inbox updates. - **Platform channels** — Each package registers its own `MethodChannel` (`sfmc/sfmc_core`, `sfmc/push`, `sfmc/iam`, `sfmc/marketingcloudsdk`, `sfmc/mobileappmessaging`). ## Next Steps - [Install and configure](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/flutter-install-and-configure.md) - [Configure Flutter for Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/configure-flutter-android.md) - [Configure Flutter for iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/configure-flutter-ios.md) # Unified Mobile SDK Reference Marketing Cloud Unified Mobile SDK and its frameworks provide developers with a sophisticated toolkit used in apps that run on billions of devices globally across multiple industries. This section provides reference information for Marketing Cloud Engagement, Mobile App Messaging, and their associated plugins. - [Cordova Plugin API Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/cordova/cordova-plugin-api-reference.md) - [Flutter Plugin API Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter/flutter-plugin-api-reference.md) - [React Native Plugin for Engagement API Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react/react-plugin-api-reference.md) - [React Native Unified Plugin API Reference](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/react-hybrid/hybrid-react-plugin-api-reference.md) # Unified React Native Plugin The unified React Native plugin works with Marketing Cloud Engagement and Marketing Cloud Next, giving you a single, consistent way to integrate either product with React Native. **note:** If you use the Marketing Cloud Engagement-specific version of the React Native plugin, you can migrate to the unified React Native plugin. See [Migrate to React Native Unified Plugin](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/migrate-to-hybrid-react-native-plugin.md). ## Who Should Use This Plugin Use this setup if: - You’re integrating React Native for the first time. - You use Marketing Cloud Engagement, but you don’t already use the Engagement-specific React Native module. - You’re implementing Mobile App Messaging with React Native. ## Prerequisites Make sure these components meet the baseline requirements. | Components | Minimum Requirement | | ---------------- | ----------------------------------------------- | | React Native | 0.85.1 or later (with New Architecture enabled) | | React | 19.0 or later (tested against 19.2.3) | | Node.js | 20 or later | | iOS | 15.1 or later (Xcode 16 or later) | | Android | minSdk 26, compileSdk 36 or later | | Ruby (CocoaPods) | 3.1.0 or later | **important:** The React Native unified plugins run only on React Native New Architecture (TurboModules) and don’t support the bridge architecture. Make sure you enable the new architecture app-wide before adopting these plugins. For more information, see _React Native Architecture_: [About the New Architecture](https://reactnative.dev/architecture/landing-page). ## Select your Package Integrating Marketing Cloud features into a React Native app required stitching together separate SDKs and bridge modules per feature. This React Native unified plugin consolidates Push, In-App Messaging, Marketing Cloud Engagement, and Mobile App Messaging in one consistent `requestSdk()` API. This way, you pick the product you need and additionally add the features that you actually use. The React Native unified plugin offers these packages: - **Product packages:** Represent a Marketing Cloud product. Depending on app usage, install either or both `@sfmc/react-native-marketingcloudsdk` (Marketing Cloud Engagement) and `@sfmc/react-native-mobileappmessaging` (Mobile App Messaging). - **Core package:** (`@sfmc/react-native-sfmc-core`) is the core foundational dependency that both product packages depend on. When you install a product package, the system installs this core package automatically. - **Feature packages:** (`@sfmc/react-native-push` and `@sfmc/react-native-iam`) are optional add-ons. Install only the feature that your app needs. | Package | Type | Description | | --------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------ | | `@sfmc/react-native-sfmc-core` | Core | Core module for identity management, custom attributes, structured event tracking, and SDK logging. | | `@sfmc/react-native-marketingcloudsdk` | Product | Product module for Marketing Cloud Engagement including inbox, tags, attributes, analytics, and registration management. | | `@sfmc/react-native-mobileappmessaging` | Product | Product module for Marketing Cloud Mobile App Messaging including analytics and registration management. | | `@sfmc/react-native-push` | Feature | Module for push registration and push notification. | | `@sfmc/react-native-iam` | Feature | Module for in-app messaging SDK readiness and programmatic in-app message display. | **important:** `@sfmc/react-native-iam` (In-App Messaging) and `@sfmc/react-native-mobileappmessaging` (Mobile App Messaging) packages are not the same and are not interchangeable. In-App Messaging delivers messages inside your running app. Whereas, Mobile App Messaging is a Marketing Cloud product for device registration and analytics. ## Architecture - The unified plugins require React Native 0.85.1 with the New Architecture (TurboModules). The plugins don’t support the bridge architecture. - TurboModule specs are codegen-driven. Each package defines a `NativeModule.ts` specification, and React Native codegen generates the Java and Objective-C++ bindings. - Native Package Identifiers: The plugin’s native code is located under `com.salesforce.mc.{sfmccore, push, iam, marketingcloudsdk, mobileappmessaging}` on Android, with equivalent module prefixes on iOS. Use these identifiers when you set up ProGuard/R8 keep rules or diagnose native stack traces. ## Next Steps - [Install and Configure the Unified React Native Plugin](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/install-and-configure.md) - [Configure React Native for Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/configure-react-native-android.md) - [Configure React Native for iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/configure-react-native-ios.md) - [Migrate to React Native Unified Plugin](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/migrate-to-hybrid-react-native-plugin.md) (Required only if you’re migrating from the Marketing Cloud Engagement-specific version of the React Native `react-native-marketingcloudsdk` plugin.) # UnknownErrorException ## Package `com.salesforce.marketingcloud.pushmodels.exceptions` ## Module Push Models Module v1.0.2 ## Platform androidJvm ## Description Class thrown when unexpected errors occur during push notification processing. ## Class Declaration ```kotlin class UnknownErrorException(cause: Throwable) : PushException ``` ## Inheritance - Extends: `PushException` - Inherits from: `Throwable` (via PushException) ## Constructors ### UnknownErrorException ```kotlin constructor(cause: Throwable) ``` **Parameters:** - `cause`: `Throwable` - The underlying exception that caused this error # unregisterInboxResponseListener Unregisters a previously registered inbox response listener. ## Syntax ```dart void unregisterInboxResponseListener(Function callback) ``` ## Parameters - `callback` (Function) - The callback function to unregister ## Returns - `void` - No return value ## Example ```dart void onInboxResponse(dynamic response) { print('Inbox response received: $response'); } // Register the listener SfmcSdk.registerInboxResponseListener(onInboxResponse); // Later, unregister the listener SfmcSdk.unregisterInboxResponseListener(onInboxResponse); ``` ## Notes - It's important to unregister listeners to prevent memory leaks. - The callback function must be the same instance that was registered. ## Related Methods - [registerInboxResponseListener()](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/references/engagement-mobile-sdk-reference/flutter_registerInboxResponseListener.md) # UnsupportedWidgetException ## Package `com.salesforce.marketingcloud.pushmodels.exceptions` ## Overview Thrown when an unsupported widget type is encountered in push notification JSON. ## Class Declaration ```kotlin class UnsupportedWidgetException(type: String?) : PushException ``` ## Inheritance - Extends: `PushException` ## Constructors ### UnsupportedWidgetException ```kotlin constructor(type: String?) ``` Creates an exception for an unsupported widget type. **Parameters:** - `type` - The unsupported widget type string (nullable) ## Module Information - **Module**: Push Models Module v1.0.2 - **SDK**: Salesforce Marketing Cloud Unified SDK 11.0.0 - **Platform**: androidJvm # Update Imports in Android Apps that use SDK Version 11 In Version 11, the In-App Messaging classes have been relocated to new packages to support a more modular architecture. Update your import statements and access patterns. ## Updated Import Path Replace the import with the simplified version: | Class | Old Import Path | New Import Path (SDK 11) | | ---------- | ----------------------------------------------------------- | ------------------------------------------ | | UrlHandler | `com.salesforce.marketingcloud.pushfeature.push.UrlHandler` | `com.salesforce.marketingcloud.UrlHandler` | ```kotlin import com.salesforce.marketingcloud.UrlHandler ``` ## In-App Messaging Package Changes Update your existing imports to point to the new package locations: | Feature / Class | Old Import Path | New Import Path (SDK 11) | | ------------------- | ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | InAppMessage | `com.salesforce.marketingcloud.messages.iam.InAppMessage` | `com.salesforce.marketingcloud.inappmessaging.models.InAppMessage` | | InAppMessageManager | `com.salesforce.marketingcloud.messages.iam.InAppMessageManager` | `com.salesforce.marketingcloud.inappmessagingfeature.InAppMessageManager` | | Config (New) | — | Access the `InAppMessageManager` through `InAppMessagingFeatureConfig.requestSdk` and add `com.salesforce.marketingcloud.inappmessagingfeature.config.InAppMessagingFeatureConfig`. | | Close Action (New) | — | Add `com.salesforce.marketingcloud.inappmessagingfeature.InAppMessageCloseAction` if you are implementing `InAppMessageManager.EventListener` to import the `didClose` action parameter. | ```kotlin import com.salesforce.marketingcloud.inappmessaging.models.InAppMessage import com.salesforce.marketingcloud.inappmessagingfeature.InAppMessageCloseAction import com.salesforce.marketingcloud.inappmessagingfeature.InAppMessageManager import com.salesforce.marketingcloud.inappmessagingfeature.config.InAppMessagingFeatureConfig ``` # Update Imports in iOS Apps that use SDK Version 11 To migrate your iOS apps to version 11 of the SDK, remove the existing SDK imports and add these imports: ```swift import MarketingCloudSDK import PushFeatureSDK import InAppMessagingFeatureSDK ``` # Upgrade MobilePush SDK for Android From Version 8.x to 8.2.x The MobilePush SDK for Android version 8.2.x is compiled using JDK 17. This version of the JDK meets the requirements of [Gradle](https://developer.android.com/build/releases/gradle-plugin#compatibility) and [Google](https://developer.android.com/build/jdks#compileSdk). For more information, see the [Change Log](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_changelog.md#android). When you upgrade from 8.x to 8.2.x, you must make some changes to your app’s code. ## Add the New MobilePush SDK for Android To upgrade to Android SDK version 8.2.x, add the SDK as a dependency to your `build.gradle` file, as shown in this example. ```js implementation("com.salesforce.marketingcloud:marketingcloudsdk:8.2.x"); ``` To use the latest SDK version, replace `8.2.x` with the latest version number available on the [Change Log](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_changelog.md). ## Update the PushModuleReadyListener Implementation After you add the latest version of the SDK as a dependency and fetch that version in your project, modify your implementation of `PushModuleReadyListener`. **note:** This step applies to Java-based implementations only. If your implementation uses Kotlin, skip this step. Your existing `PushModuleReadyListener` implementation contains code similar to this example. ```java SFMCSdk.requestSdk(new SFMCSdkReadyListener() { @Override public void ready(@NonNull SFMCSdk sfmcSdk) { sfmcSdk.mp(new PushModuleReadyListener() { @Override public void ready(@NonNull PushModuleInterface pushModuleInterface) { pushModuleInterface.get... } }); } }); ``` Update the code to add a second `ready()` method that accepts a `ModuleInterface` parameter and casts it to `PushModuleInterface`, as shown in this example. ```java SFMCSdk.requestSdk(new SFMCSdkReadyListener() { @Override public void ready(@NonNull SFMCSdk sfmcSdk) { sfmcSdk.mp(new PushModuleReadyListener() { @Override public void ready(@NonNull PushModuleInterface pushModuleInterface) { pushModuleInterface.get... } @Override public void ready(@NonNull ModuleInterface moduleInterface) { this.ready((PushModuleInterface) moduleInterface); } }); } }); ``` # Upgrade the SDK Upgrade the Engagement SDK to get the latest features, performance improvements, and security updates for your apps. New major versions of the SDK include changes to initialization, contact management, and feature availability, so review the upgrade instructions for your target version before you begin. **important:** Upgrade the SDK one major version at a time. For example, to go from version 9 to version 11, first upgrade to version 10, and then to version 11. Skipping a version can cause compatibility issues and unexpected behavior in your app. Find the upgrade instructions for the version of the SDK that you want to upgrade to, and then follow the linked Android or iOS guide for that version. - [Upgrade to SDK Version 8](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_v8.md) - [Upgrade to SDK Version 9](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_v9.md) - [Upgrade to SDK Version 10](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_v10.md) - [Upgrade to SDK Version 11](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_v11.md) # Upgrade the SDK from Version 8 to Version 9 Version 9 of the SDK expands your iOS push messaging capabilities with the introduction of carousel push notifications, push delivery events, and Inbox 2.0 support. Upgrading to this version enables you to create more engaging interactive push notifications, gain valuable delivery insights, and enhance your in-app messaging with richer content and flexible call-to-action options. The upgrade steps include integrating the new iOS Extension SDK, updating `PushInterface` method signatures, and migrating iOS Service Extension code. ## Integrate the iOS Extension SDK Push delivery events and carousel templates require Service and Content Extensions, which are included with the iOS Extension SDK. For installation information, see [Integrate the iOS Extension SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_integrate_ios_extension/mc_engagement_integrate_ios_extension.md). ## Update PushInterface Method Signatures Version 9 of the SDK for iOS introduces changes to the `PushInterface` method signatures to support Carousel push notifications and Inbox 2.0 features. These updates involve modifications to the `UNUserNotificationCenterDelegate` implementation and the removal of custom inbox message handling methods. ### Update UNUserNotificationCenterDelegate Implementation Update your existing `UNUserNotificationCenterDelegate` implementation as shown in this example. ``` // REQUIRED IMPLEMENTATION // The method will be called on the delegate when the user responded to the notification by opening the application, // dismissing the notification or choosing a UNNotificationAction. // The delegate must be set before the application returns from applicationDidFinishLaunching:. @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // Required: tell the MarketingCloudSDK about the notification. This will collect mobile app analytics // and process the notification on behalf of your application. SFMCSdk.requestPushSdk { mp in mp.setNotificationResponse(response) } completionHandler() } ``` ### Inbox Message Handling Changes In version 9.0.0 and later, the SDK for iOS doesn’t support custom data sources and delegates for the inbox table view. These methods have been removed: ``` public func inboxMessagesTableViewDataSourceFor(tableView: UITableView) -> InboxMessagesDataSource? public func inboxMessagesTableViewDelegateFor(tableView: UITableView, dataSource: InboxMessagesDataSource) -> InboxMessagesDelegate? ``` **note:** To manage inbox messages, use the [built-in SDK methods](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_inbox_messages/mc_engagement_inbox_messages_ios_public_properties.md) instead of custom data sources and delegates. ## Migrate Service Extension Code The iOS Extension SDK now provides built-in methods for handling common Service Extension tasks, such as customizing notification content and managing push notification delivery. If your app uses custom code in its Service Extension, use the [provided customization methods](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_integrate_ios_extension/mc_engagement_integrate_ios_extension_configure_service.md) of the iOS Extension SDK. For a complete implementation example, see the [iOS LearningApp](https://github.com/salesforce-marketingcloud/MarketingCloudSDK-iOS/blob/spm/examples/LearningApp/MarketingCloudServiceExtension/NotificationService.swift). # Upgrade to Version 8 of the SDK Version 8 of the SDK provides improved architecture and new features for mobile app development. For information about upgrading Android apps to version 8 of the SDK, see: - [Upgrade Android to Version 8](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v8.md) - [Upgrade Android to Version 8.2](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v8_2.md) For information about upgrading iOS apps to version 8 of the SDK, see [Upgrade iOS to Version 8](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v8.md). # Upgrade to Version 9 of the SDK Version 9 of the SDK includes enhanced features and improvements over previous versions. For information about upgrading Android apps to version 9 of the SDK, see [Upgrade Android to Version 9](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_android_v9.md). For information about upgrading iOS apps to version 9 of the SDK, see [Upgrade iOS to Version 9](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade_ios_v9.md). # Upgrade to Version 9 of the SDK for Android Version 9 of the Android SDK brings improvements over previous versions, including new interactive notification features, better delivery tracking, and enhanced inbox messaging options. If your app uses version 7 or 8 of the SDK, we recommend that you upgrade sequentially in this order: 7.x → 8.x → 8.2.x → 9.x. Skipping a major version can result in compatibility issues. ## Add the New MobilePush Android SDK To upgrade to version 9, add the SDK as a dependency to your build.gradle file, as shown in this example. ```java implementation("com.salesforce.marketingcloud:marketingcloudsdk:9.x") ``` To use the latest SDK version, replace 9.x with the latest version number available on the [Change Log](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_changelog.md). ## Use RemoteViews for Carousel Notifications Version 9 and later of the SDK use `RemoteViews` to render carousel notifications and standard notifications. These notifications include buttons that you define in Content Builder. For best results, don’t override the SDK’s `RemoteViews` implementation. Don’t use `NotificationCompat.Builder.setContentView`, which can interfere with the way that the SDK renders content. For information about configuring the action that occurs when a user taps a button or a carousel image, see [Configure Button and Carousel Actions](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_push_notifications/mc_engagement_push_notifications_android_button_carousel.md). ## Handle Nullable URL Property in Inbox In version 9 and later, the `url` field in the `InboxMessage` object can be null. As a result, it doesn’t always contain a link to a CloudPages page for Inbox 2.0. Configure your app to handle this case by checking for null values before using the `url` field. For more information, see [Implement Inbox Messaging on Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/mc_engagement_inbox_messages/mc_engagement_inbox_messages_android.md). # UrlHandler **Package:** `com.salesforce.marketingcloud` **Type:** `fun interface` **SDK Version:** 11.0.0 **Target:** androidJvm **Module:** Common v1.0.0 ## Description This interface handles URL events from push notifications or in-app messages that require processing. It allows you to define custom behavior when users interact with URLs in Marketing Cloud messages. ## Declaration ```kotlin fun interface UrlHandler ``` ## Methods ### handleUrl ```kotlin abstract fun handleUrl( context: Context, url: String, urlSource: String ): PendingIntent? ``` Returns the `PendingIntent` to execute when a push notification action containing a URL needs display. **Parameters:** - **context** (`Context`) - Android context - **url** (`String`) - The URL to handle - **urlSource** (`String`) - Source of the URL event **Returns:** `PendingIntent?` - Nullable PendingIntent for the notification action. Return `null` if you want the SDK to handle the URL using default behavior. ## Nested Types ### Companion ```kotlin object Companion ``` A companion object for the UrlHandler interface. ## Usage As a functional interface (fun interface), `UrlHandler` can be implemented using a lambda expression: ```kotlin val urlHandler = UrlHandler { context, url, urlSource -> // Custom URL handling logic // Return a PendingIntent or null null } ``` # URLHandlingDelegate `Protocol` Receives Marketing Cloud URLs for your app to open or handle. ## Declaration ```swift @objc(SFMCSdkURLHandlingDelegate) public protocol URLHandlingDelegate @objc func sfmc_handleURL(_ url: URL, type: String) ``` ## Cases ### `sfmc_handleURL(_:type:)` Called when the SDK has a URL to handle. ```swift @objc func sfmc_handleURL(_ url: URL, type: String) ``` --- # URLType `Enumeration` Categories for URLs delivered to `sfmc_handleURL(_:type:)` . `URLHandlingDelegate` passes `type` as a string, not this enum. Compare the `type` argument to the string documented on each case (for example `"cloudPage"` ). ## Declaration ```swift @objc(SFMCSdkURLType) public enum URLType : Int case cloudPage case openDirect case action ``` ## Cases ### `cloudPage` CloudPage URL from a push or inbox flow. String passed to the delegate: `"cloudPage"` . ```swift case cloudPage ``` --- ### `openDirect` Open Direct URL. String passed to the delegate: `"openDirect"` . ```swift case openDirect ``` --- ### `action` Custom or button action URL (for example in-app message actions). String passed to the delegate: `"action"` . ```swift case action ``` --- # Use the SDK with Marketing Cloud Engagement The Salesforce Engagement SDK, formerly called the MobilePush SDK, helps you integrate push notifications, in-app messages, and location-based messaging into your mobile apps. Use the SDK to engage users, track analytics, and deliver personalized experiences. ## Get Started Begin by integrating the SDK into your mobile apps: - [Integrate the SDK for Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_integrate_android/engagement_sdk_guide_integrate_android.md) - [Integrate the SDK for iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_integrate_ios/mc_engagement_integrate_ios.md) - [Integrate the iOS Extension SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_integrate_ios_extension/mc_engagement_integrate_ios_extension.md) to add support for rich notifications and delivery tracking on iOS. If you use Cordova, React Native, or Flutter to develop your app, you can also [integrate the SDK with those platforms](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_development_frameworks/mc_engagement_development_frameworks.md). ## Implement Core Features After you integrate the SDK, implement its core features based on the needs of your app: - [Register Contacts and Devices](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_register_contacts_devices/mc_engagement_register_contacts_devices.md) — Associate devices with contacts and manage contact attributes and tags. - [Push Notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_push_notifications/mc_engagement_push_notifications.md) — Send push notifications to users of your app. - [In-App Messages](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_in-app_messages/mc_engagement_in-app_messages.md) — Display messages within your app. - [Inbox Messages](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_inbox_messages/mc_engagement_inbox_messages.md) — Create a message inbox in your app. - [Location Messages](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_location_messages/mc_engagement_location_messages.md) — Send location-based messages using geofences and beacons. - [Analytics](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_analytics/mc_engagement_analytics.md) — Track user interactions and integrate with product recommendations. - [Event Tracking](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_event_tracking/mc_engagement_event_tracking.md) — Track custom events in your app. ## Configure, Manage, and Maintain Your Apps Manage the features of the SDK, test for and resolve implementation issues, and keep your app up-to-date: - [Validate Your Implementation](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_validate_implementation/mc_engagement_validate_implementation.md) — Test push notifications and registrations. - [Runtime Toggles](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_runtime_toggles.md) — Enable or disable SDK features at runtime. - [Data Protection and Privacy](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_data_protection_privacy.md) — Implement privacy compliance features. - [Troubleshooting](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_troubleshooting/mc_engagement_troubleshooting.md) — Fix common SDK implementation issues. - [Upgrade the SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_upgrade/mc_engagement_upgrade.md) — Use the latest features and receive security updates by implementing the latest version of the SDK for your platform. ## Additional Resources See the [Changelog](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_engagement_changelog.md) for a complete release history of the SDK and its development frameworks. # Use the SDK with Marketing Cloud Next Use the SDK with Marketing Cloud Next to integrate push notifications, in-app messages, and analytics into your mobile apps. Use the SDK to engage users, track behavior, and deliver personalized experiences. ## Get Started Begin by integrating the SDK into your mobile apps: - [Integrate the SDK for Android](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_integrate_android/mc_next_integrate_android.md) - [Integrate the SDK for iOS](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_integrate_ios/mc_next_integrate_ios.md) - [Integrate the iOS Extension SDK](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_integrate_ios_extension/mc_next_integrate_ios_extension.md) to add support for rich notifications and delivery tracking on iOS. ## Implement Core Features After you integrate the SDK, implement its core features based on the needs of your app: - [Register Contacts and Devices](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_register_contacts_devices/mc_next_register_contacts_devices.md) — Associate devices with contacts and manage contact attributes. - [Push Notifications](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_push_notifications/mc_next_push_notifications.md) — Send push notifications to users of your app. - [In-App Messages](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_in-app_messages/mc_next_in-app_messages.md) — Display messages within your app. - [Analytics](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_analytics/mc_next_analytics.md) — Track user interactions and custom events. ## Configure and Manage Your Apps Manage SDK features and handle navigation: - [Runtime Toggles](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_runtime_toggles.md) — Enable or disable SDK features at runtime. - [Handle URLs](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_handle_urls.md) — Process URLs from push notifications and in-app messages. ## Additional Resources See the [Changelog](https://developer.salesforce.com/docs/marketing/mobile-unified-sdk/guide/mc_next_changelog.md) for a complete release history of the SDK. # User and Device Registration Before you can send messages to your users, you must register devices and users with Marketing Cloud Next. Registration is the most important step in your entire implementation. User and device registration is a critical process managed by the SDK, which plays a pivotal role in establishing a reliable framework for communication with your users. By managing this registration, the SDK ensures your application integrates smoothly with all Mobile Messaging features, from targeted messaging to analytics, all designed to enhance user engagement and provide valuable insights into user interactions. The SDK simplifies the registration process, allowing developers to concentrate on creating engaging user experiences. With the SDK managing the registration, you can ensure effectiveness without getting bogged down in complexity. ## Registration Flow Registering users and devices with Marketing Cloud Next is shown in steps 3 and 4 of this diagram. Although this diagram is specific to push notifications, these two registration steps are the same for all message types. See [How Mobile App Messaging SDK Works](https://developer.salesforce.com/docs/marketing/before-you-begin/engagement_sdk_guides_before_you_begin_how_works.md). ![Registration Flow Diagram](https://developer.salesforce.com/media/overview/Mkting_MobilePush_SequenceDiag_PushNotification_041124_zh.png) First, the app initializes the SDK. For push notifications, the SDK negotiates with the Push Notification Service (PNS) for a device token. Then, regardless of the message type, the SDK asynchronously attempts to register and update information, such as the device token, device ID, individual ID, attributes, and push opt-in status, with Marketing Cloud Next. By default, when a user installs and launches an app for the first time, the SDK immediately submits a registration after a successful SDK initialization. When there’s a change to the Individual record that SDK stores locally, it triggers a registration update. The SDK sends these subsequent registrations to Marketing Cloud Next within one minute of the first change to the locally stored Individual record. **note:** Registrations are asynchronous. While the SDK can receive a successful `201` response from the server indicating that it received the registration, the response doesn't indicate whether it successfully processed the request. ## Triggers and Throttles The SDK limits registration requests to one per minute. When your app changes any user record in its dataset, the SDK triggers a registration update. These changes encompass changes to individual IDs, custom attributes or tags, and system-related attributes, including time zone, device locale, and app version. ## Source of Truth for Registration The SDK is a source of truth for an individual’s device registration. The SDK sends registration data asynchronously in one direction to Marketing Cloud Next. After Marketing Cloud Next receives the SDK’s REST request, it takes a few minutes to fully process the updated registration data. ## Failures If a registration fails because Marketing Cloud Next is unavailable, the SDK uses a back-off algorithm with increasing retry intervals up to a maximum delay of one day. At that point, the SDK retries daily until registration is successful. # ViewCatalogDetailEvent **Package:** `com.salesforce.marketingcloud.sfmcsdk.components.events` **Inheritance:** `ViewCatalogDetailEvent` extends `CatalogEvent` ## Overview ```kotlin class ViewCatalogDetailEvent : CatalogEvent ``` An event to capture when a user views the details of a catalog object. ## Description This class represents an event in the Salesforce Marketing Cloud Unified SDK that tracks when users view detailed information about items in a catalog. It inherits functionality from the `CatalogEvent` base class. ## Platform - **Target:** androidJvm # ViewCatalogEvent ## Package ``` com.salesforce.marketingcloud.sfmcsdk.components.events ``` ## Description An event to capture when a user views a catalog object. ## Class Declaration ```kotlin class ViewCatalogEvent : CatalogEvent ``` ## Platform - **Target**: androidJvm - **SDK Version**: SFMC SDK v3.1.0 (Salesforce Marketing Cloud Unified SDK 11.0.0) ## Inheritance Hierarchy ``` Event (interface) └── EngagementEvent (sealed class) └── CatalogEvent (sealed class) └── ViewCatalogEvent (class) ``` ## Overview `ViewCatalogEvent` is a concrete implementation of `CatalogEvent` used to track when a user views a catalog object in your application. This event is part of the engagement tracking system in the Salesforce Marketing Cloud SDK. ## Inherited Properties ### From CatalogEvent #### catalogObject ```kotlin val catalogObject: CatalogObject ``` References the catalog item associated with the event. ### From EngagementEvent #### category ```kotlin open override var category: Event.Category ``` The Event category Name. Category contains list of allowed values. #### priority ```kotlin open override val priority: Priority ``` Defines the priority level for this event. ## Inherited Methods ### From EngagementEvent #### attributes() ```kotlin open override fun attributes(): Map ``` The Event attributes for this event. **Returns**: A map containing string keys and any-type values representing event attributes. #### name() ```kotlin open override fun name(): String ``` The name for the event. This value must match the Event Name used when creating the event in the Marketing Cloud UI for any action to result from tracking this event. **Returns**: String representing the event name. ## Related Classes ### CatalogObject Represents various items that can be tracked (e.g., a product, a blog post, etc.). **Constructor**: ```kotlin class CatalogObject @JvmOverloads constructor( val type: String, val id: String, val attributes: Map = mapOf(), val relatedCatalogObjects: Map> = mapOf() ) ``` **Parameters**: - `type` (String): A type name representing the catalog object. Required. - `id` (String): A unique id representing the catalog object. Required. - `attributes` (Map): A map of user-supplied values. Default: empty map. - `relatedCatalogObjects` (Map>): A map of related catalog objects. Default: empty map. ## Sibling Classes Other catalog event types that extend `CatalogEvent`: 1. **ViewCatalogDetailEvent** - Tracks detailed catalog item views 2. **QuickViewCatalogEvent** - Tracks quick preview interactions 3. **ShareCatalogEvent** - Tracks catalog sharing actions 4. **ReviewCatalogEvent** - Tracks review submissions 5. **CommentCatalogEvent** - Tracks comment interactions 6. **FavoriteCatalogEvent** - Tracks favoriting/bookmarking actions ## Usage Context This event is part of the engagement tracking system, allowing applications to monitor and report user interactions with catalog items in Marketing Cloud campaigns. Events are tracked using the `EventManager` after SDK initialization via `SFMCSdk.configure`. ## Notes - The `@JvmOverloads` annotation on `CatalogObject` generates multiple constructor overloads for Java interoperability - All `CatalogObject` properties are immutable (`val`) - `ViewCatalogEvent` is a sealed class subtype, meaning it can only be extended within its own module - The event name used when tracking must match the Event Name configured in the Marketing Cloud UI for any action to trigger # WhenReadyHandler **Package:** `com.salesforce.marketingcloud.pushfeature` **Module:** Push Feature Module v2.0.0 ## Description An abstract handler class that manages asynchronous SDK requests by delivering PushFeature instances to registered listeners using Android's Handler mechanism on the appropriate thread. ## Class Signature ```kotlin abstract class WhenReadyHandler( looper: Looper?, val listener: WhenReadyListener ) ``` ## Constructors ### WhenReadyHandler ```kotlin constructor(looper: Looper?, listener: WhenReadyListener) ``` Creates a new instance with the specified Looper and listener. **Parameters:** - `looper` - The Looper for thread handling (nullable) - `listener` - The WhenReadyListener to receive callbacks ## Properties ### completed ```kotlin @Volatile var completed: Boolean ``` Indicates whether the operation has completed. ### listener ```kotlin val listener: WhenReadyListener ``` The listener that receives SDK callbacks. ## Methods ### deliverSdk ```kotlin fun deliverSdk() ``` Delivers the SDK instance to the registered listener. # WhenReadyListener **Package:** `com.salesforce.marketingcloud.inappmessagingfeature` **Module:** In App Messaging Feature Module v1.0.0 ## Description A functional interface that provides a callback mechanism to receive a valid `InAppMessagingFeature` instance when it becomes ready for use. ## Usage Example ```kotlin InAppMessagingFeature.requestSdk { inAppMessagingFeature -> val manager = inAppMessagingFeature.getInAppMessageManager() // Show a previously blocked message by its ID manager.showMessage("message-id") } ``` ## Functions ### ready ```kotlin abstract fun ready(inAppMessagingFeature: InAppMessagingFeature) ``` Invoked when the `InAppMessagingFeature` is initialized and ready to be used. **Parameters:** - `inAppMessagingFeature` - The ready-to-use `InAppMessagingFeature` instance ## See Also - `InAppMessagingFeature.Companion.requestSdk` - `InAppMessagingFeature` --- _Part of the Salesforce Marketing Cloud Unified SDK 11.0.0_ # WhenReadyListener ## Package `com.salesforce.marketingcloud.pushfeature` ## Overview A functional interface that serves as a callback mechanism for when the PushFeature component becomes ready for use in the Salesforce Marketing Cloud Unified SDK. ## Type `fun interface` (Functional Interface) ## Description This interface defines a callback for when PushFeature is ready. As a functional interface, it can be implemented using lambda expressions in Kotlin. ## Methods ### ready ```kotlin abstract fun ready(pushFeature: PushFeature) ``` Called when PushFeature is ready for use. **Parameters:** - `pushFeature`: `PushFeature` - The PushFeature instance that is now ready **Returns:** `Unit` ## Platform - androidJvm ## Module Information - **Module:** Push Feature Module - **Version:** 2.0.0 - **SDK Version:** 11.0.0 (Salesforce Marketing Cloud Unified SDK) ## Usage As a functional interface, `WhenReadyListener` can be implemented using lambda expressions: ```kotlin // Lambda implementation val listener = WhenReadyListener { pushFeature -> // Use the ready PushFeature instance } ```