> Synerise Documentation — Mobile SDK (Part 1 of 2) > > This is part 1 of 2 of the "Mobile SDK" section. To reconstruct the full section, fetch all 2 parts in order (part 1, part 2, …) and concatenate them. Each article begins with a top-level "# " heading. The manifest listing all sections is at https://hub.synerise.com/llms-full.txt # SDK Lifecycle ### Synerise Builder Synerise builder class. **Declared In:** `com.synerise.sdk.core.Synerise.Builder` **Declaration:**
```Java public static class Builder ```
```Kotlin static class Builder ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **app** | Application | no | - | Application context | | **apiKey** | String | no | - | Profile API Key (formerly Client). Can be retrieved from Synerise App | | **applicationId** | String | no | - | Application ID | | **baseUrl** | String | no | - | Base URL in the SDK. Can be null | | **syneriseDebugMode** | Boolean | no | - | Debug mode flag | | **notificationIcon** | int | no | R.drawable.synerise_ic_default_icon | Notification icon | | **notificationIconColor** | int | no | R.color.syneriseGrayTranslucent | Notification color | | **channelDefaultName** | String | no | - | Default notification channel name | | **channelDefaultId** | String | no | - | Default notification channel ID | | **channelHighPriorityName** | String | no | - | High priority notification channel name | | **channelHighPriorityId** | String | no | - | High priority notification channel ID | | **pushListener** | OnRegisterForPushListener | no | - | Push listener | | **locationListener** | OnLocationUpdateListener | no | - | Location listener | | **crashHandlingEnabled** | Boolean | no | - | Crash handling flag | | **hostApplicationType** | HostApplicationType | yes | - | Host application type | | **hostApplicationSDKPluginVersion** | String | yes | - | Synerise SDK plugin version in the host application | | **setRequestValidationSalt** | String | yes | - | Synerise Profile salt string for request validation | | **messagingServiceType** | String | yes | GMS | Use `GMS` for Google Mobile Services or `HMS` for Huawei Mobile Services | **Initializers:** Start initializing Synerise SDK with this method. To get the Workspace API Key (formerly Business) and Profile API Key (formerly Client), sign in to your Synerise account and go to [Settings > API Key](https://app.synerise.com/spa/modules/settings/apikeys/list). Then, copy or generate a new API Key for the workspace and API Key for profiles.
public static Builder with(Application app, String apiKey, String appId)
--- Use this method to finish the initialization process.
public void build()
--- **Methods:** This method sets the icon that will be used as the small icon in notifications. It must be a drawable resource (not a mipmap) due to Android Oreo adaptive icons restrictions.
public Builder notificationIcon(@DrawableRes int notificationIcon)
--- This method sets the notification icon and text color. `notificationIconColor` must be in ARGB format.
public Builder notificationIconColor(int notificationIconColor)
--- This method enables/disables logcat logs from Synerise SDK. It is not recommended to use debug mode in the release version of your application.
public Builder syneriseDebugMode(boolean syneriseDebugMode)
--- This method passes info about Users application crashes as dedicated events to the backend. It is recommended to use `SyneriseCrashHandling`.
public Builder crashHandlingEnabled(boolean exceptionHandlerEnabled)
--- It is important to register your profiles for push messages, so Synerise SDK may ask you to register a profile for push notifications. This callback is called after the profile signs in, signs up, or deletes the account.
public Builder pushRegistrationRequired(@NonNull OnRegisterForPushListener listener)
--- This callback is called on demand by push notification, so it may be called at any time. Check out the [sample application](https://github.com/Synerise/android-sdk/blob/master/sample/src/main/java/com/synerise/sdk/sample/App.java) for example usage and remember to send.
public Builder locationUpdateRequired(@NonNull OnLocationUpdateListener listener)
--- You can provide your custom base URL to use your own API. You can use one of the constants: **SyneriseApiUrls.SYNERISE_AZ_API_URL** - `https://api.snrapi.com` **SyneriseApiUrls.SYNERISE_AZU_API_URL** - `https://api.azu.snrapi.com` **SyneriseApiUrls.SYNERISE_GEB_API_URL** - `https://api.geb.snrapi.com`
public Builder baseUrl(String baseUrl)
--- You can provide your notification channel name. By default, the channel name is set to your application name.
public Builder notificationDefaultChannelName(@NonNull String name)
--- You can provide your notification channel ID.
public Builder notificationDefaultChannelId(@NonNull String channelId)
--- You can provide your High Priority notification channel name. From default, channel name is set to ` High Priority`
public Builder notificationHighPriorityChannelName(@NonNull String name)
--- You can provide your High Priority notification channel ID.
public Builder notificationHighPriorityChannelId(@NonNull String channelId)
--- You can set the Synerise SDK host application type.
public Builder hostApplicationType(HostApplicationType type)
--- You can set Synerise the SDK plugin version of the host application.
public Builder hostApplicationSDKPluginVersion(@NonNull String version)
--- --- --- ## InitializationConfig Configuration class for initialization of the SDK. **Declared In:** `com.synerise.sdk.core.types.model.InitializationConfig` **Declaration:**
```Java public class InitializationConfig ```
```Kotlin class InitializationConfig ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **salt** | String | no | - | [Simple Profile Authentication](/developers/mobile-sdk/user-identification-and-authorization/simple-authentication) salt |
All the properties above are accessible by using getters.
**Methods:** There are getters and setters for the above properties. --- --- ## Settings Class model for settings. **Declared In:** `com.synerise.sdk.core.settings.Settings` **Declaration:**
```Java public class Settings ```
```Kotlin class Settings ```
**Properties:** | Property | Type | Description | | --- | --- | --- | | **sdk** | GeneralSettings | [General settings](/developers/mobile-sdk/settings#general) - This group contains options related to the general functioning of mobile SDK | | **notifications** | NotificationsSettings | [Notifications settings](/developers/mobile-sdk/settings#notifications) - This group contains options related to push notifications | | **tracker** | TrackerSettings | [Tracker](/developers/mobile-sdk/settings#tracker) - This group contains options related to tracking the customer activities in a mobile application | | **inAppMessaging** | InAppMessagingSettings | [In-app messaging](/developers/mobile-sdk/settings#in-app-messaging) - This group contains options related to the [in-app messages](/docs/campaign/in-app-messages) feature | | **injector** | InjectorSettings | [Injector](/developers/mobile-sdk/settings#injector) - This group contains options related to displaying [campaigns](/docs/campaign/Mobile) | **Note:** Learn more about settings [here](/developers/mobile-sdk/settings) --- --- ## TrackMode This enum contains the values which set a mode for tracking component interactions from the `android.widget` package. **Declared In:** `com.synerise.sdk.core.types.enums.TrackMode` **Declaration:**
```Java public enum TrackMode ```
```Kotlin public enum TrackMode ```
**Values:** | Property | Description | | --- | --- | | **PLAIN** | Tracks screen-visits. Events are sent when onStart of activities/Fragments is called. | | **FINE** | Tracks screen-visits and onClick events from components such as Buttons, ImageButtons, RatingBars | **Methods:** There are no methods. --- --- # SDK Lifecycle ## InitializationConfig **Declared In:** Headers/SNRInitializationConfig.h **Inherits from:** [NSObject](https://developer.apple.com/documentation/objectivec/nsobject) **Declaration**:
```Swift class InitializationConfig: NSObject ```
```Objective-C @interface SNRInitializationConfig: NSObject ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **requestValidationSalt** | String | yes | [Simple Profile Authentication](/developers/mobile-sdk/user-identification-and-authorization/simple-authentication) salt | --- --- ## Settings **Declared In:** Headers/SNRSettings.h **Inherits From:** [NSObject](https://developer.apple.com/documentation/objectivec/nsobject) **Declaration:**
```Swift class Settings: NSObject ```
```Objective-C @interface SNRSettings : NSObject ```
**Properties:** | Property | Type | Description | | --- | --- | --- | | **sdk** | GeneralSettings | [General settings](/developers/mobile-sdk/settings#general) - This group contains options related to the general functioning of mobile SDK | | **notifications** | NotificationsSettings | [Notifications settings](/developers/mobile-sdk/settings#notifications) - This group contains options related to push notifications | | **tracker** | TrackerSettings | [Tracker](/developers/mobile-sdk/settings#tracker) - This group contains options related to tracking the customer activities in a mobile application | | **inAppMessaging** | InAppMessagingSettings | [In-app messaging](/developers/mobile-sdk/settings#in-app-messaging) - This group contains options related to the [in-app messages](/docs/campaign/in-app-messages) feature | | **injector** | InjectorSettings | [Injector](/developers/mobile-sdk/settings#injector) - This group contains options related to displaying [campaigns](/docs/campaign/Mobile) | **Note:** Learn more about settings [here](/developers/mobile-sdk/settings) --- --- ## TrackerAutoTrackMode **Declared In:** Headers/SNRTrackerAutoTrackingSettings.h
`eager` mode was removed in SDK version 5.0.0.
**Declaration:**
```Swift enum TrackerAutoTrackMode: Int { plain, fine, disabled } ```
```Objective-C typedef NS_ENUM(NSInteger, SNRTrackerAutoTrackMode) { SNRTrackerAutoTrackModePlain, SNRTrackerAutoTrackModeFine, SNRTrackerAutoTrackModeDisabled } ```
# Overview Integrating Synerise Mobile (Android, iOS, React Native, Flutter) SDKs in your mobile application has many benefits, such as: - **Time-saving and low effort** - The integration is quick, allowing you to get started right away without spending time configuring or managing session tokens. Synerise stores customer tokens (both anonymous and recognized), manages their validity, refreshes and handles the logic of log-ins and log-outs. The integration is quick and you'll be able to secure user's information in no time. - **Safety guaranteed** - We have a highly secure and encrypted infrastructure: all sensitive data is encrypted in storage and the communication between the servers and the application is encrypted and secured well, which is proven by successfully passed audits. - **Automatic event tracking** - All customers' activities (events) in a mobile application are tracked in real time and sent in batches to Synerise. This way, you can use the Synerise Decision Hub to analyze the customers' behavior in your mobile app.
There is no auto-tracking option for React Native. To send events to Synerise, you must configure triggers which record and send events to Synerise.
- **Send push notifications** - Integrating your mobile app with Synerise Mobile SDK facilitates push notifications, which you can use to communicate with your customers. All interactions related to push notifications are collected as events, such as: opening a push notification, clicking a link in the notification, rejecting the notification, and so on. Based on [these events](/developers/mobile-sdk/event-tracking#predefined-event-list), you can measure the results of your push notification campaigns in the Synerise Decision Hub. - **Send in-app messages** - In-app messages allow you to display any creation in a mobile application and implement use cases such as [abandoned cart](/use-cases/abandoned-basket-inapp), [price drop notifications](/use-cases/in-app-price-drop-last-seen-products), sending out discount codes, or implement any information campaign, such as application update. In contrast to push notifications which are sent (pushed) to the app user by Synerise, in-app messages are requested (pulled) by the user’s device through Synerise mobile SDK and they doesn't require a marketing agreement to be displayed. - **Display recommendations and promotions** - Your mobile app can be a distribution channel where you can display [AI-based recommendations](/docs/ai-hub/recommendations-v2) and [promotions](/docs/ai-hub/personalized-promotions) which you can create in Synerise. Because the SDK keeps the customer context, actions such as fetching a recommendation or a promotion require only one SDK call. - **Build your application with Synerise Documents** - This feature allows you to build your mobile application based on [documents](/docs/assets/documents) in which you can include [promotions](/docs/ai-hub/personalized-promotions), [recommendations](/docs/ai-hub/recommendations-v2), [dynamic content](/docs/campaign/dynamiccontent) without releasing a new version of your app. ## What's next --- Proceed to [Installation and configuration](/developers/mobile-sdk/installation-and-configuration). # Sample projects on Github - [Github sample projects - Android](https://github.com/Synerise/android-sdk) - [Github sample projects - iOS](https://github.com/Synerise/synerise-ios-sdk) - [Github sample projects - React Native](https://github.com/Synerise/react-native-synerise-sdk) - [Github sample projects - Flutter](https://github.com/Synerise/synerise-flutter-sdk) # Android ## Method reference - Android # Profile identification ## Anonymous customers --- When you initialize the SDK, on the first start a UUID is generated and a JWT token is retrieved for an *anonymous customer*. The customer in this scenario is fully anonymous within the system and does not contain any personal information. Such a token allows some basic operations such as tracking events of anonymous customers, sending in-app messages, push notifications, display documents and more. However, better profile identification and management with extra features is provided when a customer is logged in. ## Recognized customers --- When an anonymous profile provides the unique identifier, the anonymous profile in the database is updated with new data. It becomes a known customer profile, which means that any activity before the customer was recognized is still present in the profile’s history. You can operate on personal information without fully authenticating a customer. You may have already imported customer data into Synerise and you have personal information in the system. The data can be linked. In such cases, you need to authenticate through your own backend systems. Before you can do that, you must merge the UUIDs from the SDK with a specific customer: 1. Retrieve the customer UUID generated by Synerise SDK. 2. Process the UUID in your own backend. If you use 3rd party authorization, you may need to pass this UUID into other systems. 3. Authorize the customer and match their identifier (loyalty card number, email address, or another type of identifier used in your system) with the customer UUID from Synerise. 4. Provide the customer UUID back to Synerise with all the additional information collected through the authorization process.
Sending this data directly from the application itself is highly discouraged and may cause authorization issues.
We recommend this customer recognition process to advanced clients. If you are a new Synerise clients and would like to run this kind of integration, you can contact us through [this form](https://hgintelligence.atlassian.net/servicedesk/customer/portal/1). ## Authenticated customers --- Synerise offers a means to fully authenticate customers and create customer sessions with JWT tokens that have access to all the features provided by Synerise. Three authentication methods are supported: - [Simple Profile Authentication](/developers/mobile-sdk/user-identification-and-authorization/simple-authentication) - [Synerise Authentication](/developers/mobile-sdk/user-identification-and-authorization/synerise-authentication) - [OAuth](/developers/mobile-sdk/user-identification-and-authorization/oauth)
This is the recommended authentication method.
- [Facebook Login](/developers/mobile-sdk/user-identification-and-authorization/authenticate-external-providers#facebook-login) - [Sign in with Apple](/developers/mobile-sdk/user-identification-and-authorization/authenticate-external-providers#sign-in-with-apple)
Available only for iOS and React Native (iOS).
# Android ## Configuring push notifications (Android) ### Prerequisites --- Google Firebase Cloud Messaging is necessary to handle [Mobile Campaigns](/docs/campaign/Mobile) sent from Synerise. 1. Follow the instructions in [this article](https://firebase.google.com/docs/storage/android/start). 2. Integrate the Firebase project with Synerise. See [this article](/docs/settings/tool/firebase). Documentation on how to prepare your first push notification is available in our [user guide](/docs/campaign/Mobile). ### Set up Firebase Cloud Messaging for Synerise SDK --- 1. Register your service in the AndroidManifest:
<application
              android:name=".App"
              android:allowBackup="true"
              android:icon="@mipmap/ic_launcher"
              android:label="@string/app_name"
              android:roundIcon="@mipmap/ic_launcher_round"
              android:supportsRtl="true"
              android:theme="@style/AppTheme">
              ...
              <service android:name=".service.MyFirebaseMessagingService">
                  <intent-filter>
                      <action android:name="com.google.firebase.MESSAGING_EVENT" />
                  </intent-filter>
              </service>
          </application>
2. In your application, implement registration for Firebase notifications:
```java public class App extends MultiDexApplication implements OnRegisterForPushListener { private static final String TAG = App.class.getSimpleName(); @Override public void onCreate() { super.onCreate(); Synerise.Builder.with(this, syneriseClientApiKey, appId) .notificationIcon(R.drawable.ic_notification_icon) .pushRegistrationRequired(this) ... .build(); } @Override public void onRegisterForPushRequired() { FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(instanceIdResult -> { String refreshedToken = instanceIdResult.getToken(); Log.d(TAG, "Refreshed token: " + refreshedToken); IApiCall call = Client.registerForPush(refreshedToken, true); call.execute(() -> Log.d(TAG, "Register for Push succeed: " + refreshedToken), apiError -> Log.w(TAG, "Register for push failed: " + refreshedToken)); }); } } ```
```kotlin class App:MultiDexApplication(), OnRegisterForPushListener { fun onCreate() { super.onCreate() Synerise.Builder.with(this, syneriseClientApiKey, appId) .notificationIcon(R.drawable.ic_notification_icon) .pushRegistrationRequired(this) build() } fun onRegisterForPushRequired() { FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener({ instanceIdResult-> val refreshedToken = instanceIdResult.getToken() Log.d(TAG, "Refreshed token: " + refreshedToken) val call = Client.registerForPush(refreshedToken, true) call.execute({ Log.d(TAG, "Register for Push succeed: " + refreshedToken) }, { apiError-> Log.w(TAG, "Register for push failed: " + refreshedToken) }) }) } companion object { private val TAG = App::class.java!!.getSimpleName() } } ```
The second parameter of the registration method is the agreement for mobile push campaigns. In the Profile's card in Synerise, you can find it in the **Subscriptions** section (if you have the required access permission). Learn more about the [Client.registerForPush(token, mobilePushAgreement) method in the method reference](/developers/mobile-sdk/method-reference/android/campaigns#register-for-push-notifications).
3. Add registerForPush method inside onNewToken callback. This should be done in your class which extends FirebaseMessagingService
```java @Override public void onNewToken(String refreshedToken) { super.onNewToken(refreshedToken); Log.d(TAG, "Refreshed token: " + refreshedToken); if (refreshedToken != null) { IApiCall call = Client.registerForPush(refreshedToken, true); call.execute(() -> Log.d(TAG, "Register for Push succeed: " + refreshedToken), apiError -> Log.w(TAG, "Register for push failed: " + refreshedToken)); } } ```
```kotlin fun onNewToken(refreshedToken:String) { super.onNewToken(refreshedToken) Log.d(TAG, "Refreshed token: " + refreshedToken) if (refreshedToken != null) { val call = Client.registerForPush(refreshedToken, true) call.execute({ Log.d(TAG, "Register for Push succeed: " + refreshedToken) }, { apiError-> Log.w(TAG, "Register for push failed: " + refreshedToken) }) } } ```
4. Pass the incoming push notification payload to the `Injector` in your `FirebaseMessagingService` implementation:
```java public class MyFirebaseMessagingService extends FirebaseMessagingService { @Override public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); boolean isSynerisePush = Injector.handlePushPayload(remoteMessage.getData()); } } ```
```kotlin class MyFirebaseMessagingService:FirebaseMessagingService() { fun onMessageReceived(remoteMessage:RemoteMessage) { super.onMessageReceived(remoteMessage) val isSynerisePush = Injector.handlePushPayload(remoteMessage.getData()) } } ```
Overriding `onMessageReceived(RemoteMessage)` stops simple notifications from being displayed while the app is the active screen. 5. In order to configure a notification icon and notification icon color, you need to set the following two parameters in `AndroidManifest.xml`, in the `application` section:
<meta-data
               android:name="com.synerise.sdk.messaging.notification_icon"
               android:resource="@drawable/ic_notification_icon" />
      <meta-data
               android:name="com.synerise.sdk.messaging.notification_icon_color"
               android:resource="@color/amaranth" />
The default values are: `android icon` and `white color`.
Check [the repository of our sample app](https://github.com/Synerise/android-sdk) for an example usage of building your non-Synerise notification.
### Keep Firebase token always up-to-date --- You must always keep the Firebase token updated. - Whenever the user changes the notification consent in the system or the application, you should call the `registerForPush` method ([Android](/developers/mobile-sdk/method-reference/android/campaigns#register-for-push-notifications); [iOS](/developers/mobile-sdk/method-reference/ios/campaigns#register-for-push-notifications), [Flutter](/developers/mobile-sdk/method-reference/flutter/campaigns), [React Native](/developers/mobile-sdk/method-reference/react-native/campaigns)). - In many cases in the application lifecycle, such as authorization, destroyed sessions, user context change, periodic jobs ([Work Manager](/developers/mobile-sdk/installation-and-configuration/android#work-manager)), and so on, the SDK invokes the [snr_registerForPushNotificationsIsNeeded(origin)](/developers/mobile-sdk/listeners-and-delegates/android-listeners#on-register-for-push-listener-on-register-for-push-required-with-origin) method or [snr_registerForPushNotificationsIsNeeded()](/developers/mobile-sdk/listeners-and-delegates/android-listeners#on-register-for-push-listener-on-register-for-push-required) method.
[Work Manager](/developers/mobile-sdk/installation-and-configuration/android#work-manager) allows you to keep the Firebase token updated even if the host application is not launched for a long time. It launches your app in the background approximately every 20 days and refreshes the token so it stays up to date.
#### Assign notifications to channels Starting with Android 8.0 (API level 26), all notifications must be assigned to a channel. Otherwise, they are not displayed. You can implement notifications in one of the following ways: - If you already have a channel defined in your application, use the `notificationDefaultChannelId(String)` and `NotificationHighPriorityChannelId(String)` methods of Builder during SDK initialization. - You cannot configure more than two notification channels. - If you want the SDK to set the channel names to default (same as the application name), initialize the SDK without the methods mentioned above. ### Callback methods ---
[NotificationListener](/developers/mobile-sdk/listeners-and-delegates/android-listeners#on-notification-listener) is available from SDK 4.9.0 version.
If you want to receive callbacks to inform the application about notification's state, implement `OnNotificationListener` using the `Injector.setOnNotificationListener` method. For details, see [this article](/developers/mobile-sdk/listeners-and-delegates/android-listeners#on-notification-listener). See sample code from the application below:
```java Injector.setOnNotificationListener(new OnNotificationListener() { @Override public void onNotificationReceived(NotificationInfo notificationInfo) { } @Override public void onNotificationClicked(NotificationInfo notificationInfo) { } @Override public void onNotificationDismissed(NotificationInfo notificationInfo) { } @Override public void onActionButtonClicked(NotificationInfo notificationInfo, String actionButton) { } }); ```
```kotlin Injector.setOnNotificationListener( object callback: OnNotificationListener() { override fun onNotificationReceived(notificationInfo: NotificationInfo) { } override fun onNotificationClicked(notificationInfo: NotificationInfo) { } override fun onNotificationDismissed(notificationInfo: NotificationInfo) { } override fun onActionButtonClicked( notificationInfo: NotificationInfo, actionButton: String) { } }) ```
### Configure notification encryption --- To enable encrypted push notifications, you must change the configuration of your workspace in the Synerise Platform. For details, read [Google Firebase](/docs/settings/tool/firebase). In the mobile application, you must set `encryption` to `true` in the notification settings.
```java Synerise.settings.notifications.setEncryption(true); ```
```kotlin Synerise.settings.notifications.setEncryption(true) ```
The SDK performs the encryption as a part of the `Synerise.Notifications.handleNotification` method. If you use only the `"Synerise"` issuer in push notifications, no more actions are required. If you need custom integration of encrypted push notifications, implement the following solution:
```java Map data = remoteMessage.getData(); if (Injector.isPushEncrypted(data)) { data = Injector.decryptPushPayload(data); } // your operations on push notification ```
```kotlin val data = remoteMessage.getData() if (Injector.isPushEncrypted(data)) { data = Injector.decryptPushPayload(data) } // your operations on push notification ```
The `decryptPushPayload` method returns raw data when the payload is not encrypted. If the crypter fails, the method returns null.
For more information, read [the description of the decryption method](/developers/mobile-sdk/method-reference/android/campaigns#decrypt-push-notification).
### Handling actions from push notifications --- - [Read more about types of actions in campaigns](/developers/mobile-sdk/campaigns/action-handling#types-of-actions-in-campaigns) - [Read more about handling actions from push notifications](/developers/mobile-sdk/campaigns/action-handling) # Basics ## Prerequisites --- Only for campaigns served by push notifications: [Configure push notifications](/developers/mobile-sdk/configuring-push-notifications). ## Overview --- Synerise campaigns are served in two ways: - By Push Notifications, which means that the campaigns are delivered as a push notification: - Simple push - Silent push - By Synerise backend, which means that the campaign is retrieved by SDK through API: - In-app messages
You can create each campaign type in the Synerise app. [Full documentation is available at this link](/docs/campaign/Mobile).
## Synerise push notification structure --- Each notification follows this basic structure corresponding to the operating system:
{
  "data": {
    "issuer": "Synerise",
    "message-type": "static-content",
    "content-type": "simple-push",
    "content": {
      <<campaign content>>
    }
  }
}
{
  "aps": {
    <<Apple params for iOS notification>>
  },    
  "issuer": "Synerise",
  "message-type": "static-content",
  "content-type": "simple-push",
  "content": {
    <<campaign content>>
  }
}
- `issuer` - in Synerise notifications, the issuer is always `Synerise`. If you want to handle notifications with your own methods, remember to change the `issuer` field. If `issuer` is set to `Synerise`, the payload is always handled by the Synerise SDK. - `message-type` - specifies if the content is static or dynamic. - `content-type` - specifies the type of content in the payload. - `content` - the content of the message. You can also react to Synerise push notifications in your own way, using the payloads presented earlier in this article. ## Checking push campaign type --- You may need to know whether an incoming push notification comes from Synerise.
| Method | Description | | --- | --- | | [`Injector.isSynerisePush`](/developers/mobile-sdk/method-reference/android/campaigns#check-if-push-notification-is-from-synerise) | Returns 'true' if the notification comes from Synerise.
It is validated by checking if the `issuer` of the push is `Synerise`. | | [`Injector.isSyneriseSimplePush`](/developers/mobile-sdk/method-reference/android/campaigns#check-if-push-notification-is-a-simple-push-campaign) | Checks if the notification payload contains a Simple Push campaign. | | [`Injector.isSyneriseBanner`](/developers/mobile-sdk/method-reference/android/campaigns#check-if-push-notification-is-a-banner-campaign) | Checks if the notification payload contains a Banner campaign. | | [`Injector.isSyneriseSilentCommand`](/developers/mobile-sdk/method-reference/android/campaigns#check-if-push-notification-is-a-silent-command) | Checks if the notification payload contains a Silent Command campaign. | | [`Injector.isSilentSdkCommand`](/developers/mobile-sdk/method-reference/android/campaigns#check-if-push-notification-is-a-silent-sdk-command) | Checks if the notification payload contains a Silent SDK Command campaign. |
| Method | Description | | --- | --- | | [`Synerise.isSyneriseNotification`](/developers/mobile-sdk/method-reference/ios/campaigns#check-if-push-notification-is-from-synerise) | Returns 'true' if the notification comes from Synerise.
It is validated by checking if the `issuer` of the push is `Synerise`. | | [`Synerise.isSyneriseSimplePush`](/developers/mobile-sdk/method-reference/ios/campaigns#check-if-push-notification-is-a-simple-push-campaign) | Checks if the notification payload contains a Simple Push campaign. | | [`Injector.isSyneriseBanner`](/developers/mobile-sdk/method-reference/ios/campaigns#check-if-push-notification-is-a-banner-campaign) | | [`Synerise.isSyneriseBanner`](/developers/mobile-sdk/method-reference/ios/campaigns#check-if-push-notification-is-a-banner-campaign) | Checks if the notification payload contains a Banner campaign. | | [`Synerise.isSilentCommand`](/developers/mobile-sdk/method-reference/ios/campaigns#check-if-push-notification-is-a-silent-command) | Checks if the notification payload contains a Silent Command campaign. | | [`Synerise.isSyneriseSilentSDKCommand`](/developers/mobile-sdk/method-reference/ios/campaigns#check-if-push-notification-is-a-silent-sdk-command) | Checks if the notification payload contains a Silent SDK Command campaign. |
| Method | Description | | --- | --- | | [`Synerise.Notificationsl.isSyneriseNotification`](/developers/mobile-sdk/method-reference/react-native/campaigns#check-if-push-notification-is-from-synerise) | Returns 'true' if the notification comes from Synerise.
It is validated by checking if the `issuer` of the push is `Synerise`. | | [`Synerise.Notificationsl.isSyneriseSimplePush`](/developers/mobile-sdk/method-reference/react-native/campaigns#check-if-push-notification-is-a-simple-push-campaign) | Checks if the notification payload contains a Simple Push campaign. | | [`Injector.isSyneriseBanner`](/developers/mobile-sdk/method-reference/react-native/campaigns#check-if-push-notification-is-a-banner-campaign) | | [`Synerise.Notificationsl.isSyneriseBanner`](/developers/mobile-sdk/method-reference/react-native/campaigns#check-if-push-notification-is-a-banner-campaign) | Checks if the notification payload contains a Banner campaign. | | [`Synerise.Notificationsl.isSyneriseSilentCommand`](/developers/mobile-sdk/method-reference/react-native/campaigns#check-if-push-notification-is-a-silent-command) | Checks if the notification payload contains a Silent Command campaign. | | [`Synerise.Notificationsl.isSyneriseSilentSDKCommand`](/developers/mobile-sdk/method-reference/react-native/campaigns#check-if-push-notification-is-a-silent-sdk-command) | Checks if the notification payload contains a Silent SDK Command campaign.|
| Method | Description | | --- | --- | | [`Synerise.notifications.isSyneriseNotification`](/developers/mobile-sdk/method-reference/flutter/campaigns#check-if-push-notification-is-from-synerise) | Returns 'true' if the notification comes from Synerise.
It is validated by checking if the `issuer` of the push is `Synerise`. | | [`Synerise.notifications.isSyneriseSimplePush`](/developers/mobile-sdk/method-reference/flutter/campaigns#check-if-push-notification-is-a-simple-push-campaign) | Checks if the notification payload contains a Simple Push campaign. | | [`Synerise.notifications.isSyneriseBanner`](/developers/mobile-sdk/method-reference/flutter/campaigns#check-if-push-notification-is-a-banner-campaign) | Checks if the notification payload contains a Banner campaign. | | [`Synerise.notifications.isSilentCommand`](/developers/mobile-sdk/method-reference/flutter/campaigns#check-if-push-notification-is-a-silent-command) | Checks if the notification payload contains a Silent Command campaign. | | [`Synerise.notifications.isSyneriseSilentSDKCommand`](/developers/mobile-sdk/method-reference/flutter/campaigns#check-if-push-notification-is-a-silent-sdk-command) | Checks if the notification payload contains a Silent SDK Command campaign. |
## Localizations in campaigns ---
This feature is currently available only for iOS SDK, React Native (iOS), and Flutter SDK (iOS).
You may set your localization to support different languages in your application - see ["Localize some strings occurring in the SDK"](/developers/mobile-sdk/settings#localize-some-strings-occurring-in-the-sdk) in the SDK Settings. **Available keys:** - **CTA button** in the [in-app alert of the Simple Push campaign](/developers/mobile-sdk/campaigns/simple-push#additional-in-app-alert-when-simple-push-is-received). - **dismiss button** in the [in-app alert of the Simple Push campaign](/developers/mobile-sdk/campaigns/simple-push#additional-in-app-alert-when-simple-push-is-received).
```Swift Synerise.settings.sdk.localizable = [ SNR_LOCALIZABLE_STRING_KEY_OK: "Go in!", SNR_LOCALIZABLE_STRING_KEY_CANCEL: "Go out!" ]; ```
```Objective-C SNRSynerise.settings.sdk.localizable = @[ SNR_LOCALIZABLE_STRING_KEY_OK: @"Go in!", SNR_LOCALIZABLE_STRING_KEY_CANCEL: @"Go out!" ]; ```
```JavaScript Synerise.Settings.sdk.localizable = { LocalizableStringKeyOK: "Go in!", LocalizableStringKeyCancel: "Go out!" }; ```
```Dart Synerise.settings.sdk.localizable = { Localizable.localizableStringKeyOk: "Go in!", Localizable.localizableStringKeyCancel: "Go out!" }; ```
## Blocking campaigns ---
This feature is available only for iOS SDK.
If you don't want to show any of the Synerise campaigns somewhere in your application or if there are View Controllers that should never be covered by Synerise activity (for example, banners), you can block the Synerise elements. To do this, add the **SyneriseActivityNotAllowed** protocol in your View Controller declaration. For example:
```Swift class SampleViewController: UIViewController, SyneriseActivityNotAllowed { } ```
```Objective-C @interface SampleViewController: UIViewController @end ```
*When View Controller implements that protocol and Synerise tries to run an activity, the activity is skipped.* # SDK Lifecycle ## InitializationConfig Class for additional initialization parameters. **Declared In:** lib/main/initialization_config.dart **Declaration:**
class InitializationConfig
**Properties** | Property | Type | Description | | --- | --- | --- | | **requestValidationSalt** | String | [Simple Profile Authentication](/developers/mobile-sdk/user-identification-and-authorization/simple-authentication) salt | --- --- ## Synerise Main SDK class responsible for managing all Synerise modules and core features. **Declared In:** lib/synerise.dart **Related To:** [SyneriseInitializer](/developers/mobile-sdk/class-reference/flutter/lifecycle#syneriseinitializer) [SettingsImpl](/developers/mobile-sdk/class-reference/flutter/modules#settings) [NotificationsImpl](/developers/mobile-sdk/class-reference/flutter/modules#notifications) [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client) [TrackerImpl](/developers/mobile-sdk/class-reference/flutter/modules#tracker) [InjectorImpl](/developers/mobile-sdk/class-reference/flutter/modules#injector) [ContentImpl](/developers/mobile-sdk/class-reference/flutter/modules#content) **Declaration:**
class Synerise
**Properties:** | Property | Type | Description | | --- | --- | --- | | **settings** | [SettingsImpl](/developers/mobile-sdk/class-reference/flutter/modules#settings) | Returns the Settings module | | **notifications** | [NotificationsImpl](/developers/mobile-sdk/class-reference/flutter/modules#notifications) | Returns the Notifications module | | **client** | [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client) | Returns the Client module | | **tracker** | [TrackerImpl](/developers/mobile-sdk/class-reference/flutter/modules#tracker) | Returns the Tracker module | | **injector** | [InjectorImpl](/developers/mobile-sdk/class-reference/flutter/modules#injector) | Returns the Injector module | | **content** | [ContentImpl](/developers/mobile-sdk/class-reference/flutter/modules#content) | Returns the Content module | **Methods:** This method initializes Synerise.
```Dart static SyneriseInitializer initializer() ```
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/lifecycle#initialization) --- This method changes a Profile (formerly Client) API key dynamically.
```Dart SyneriseInitializer changeApiKey(String apiKey) ```
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/lifecycle#change-profile-api-key-dynamically) --- --- --- ## SyneriseInitializer Class responsible for initialization of the SDK. **Declared In:** lib/main/synerise_initializer.dart **Declaration:**
class SyneriseInitializer
**Methods:** This method sets Profile API Key (formerly Client API Key) for the SDK initialization.
SyneriseInitializer withApiKey(String apiKey)
Before version 2.0.0, this method was called `withClientApiKey`.
--- This method sets the Synerise API base URL for SDK initialization in a custom environment.
SyneriseInitializer withBaseUrl(String baseUrl)
--- This method sets the salt string for request validation.
SyneriseInitializer setRequestValidationSalt(String requestValidationSalt)
--- This method enables or disables console logs from Synerise SDK.
SyneriseInitializer withDebugModeEnabled(bool debugModeEnabled)
--- This method enables or disables crash handling by Synerise SDK.
SyneriseInitializer withCrashHandlingEnabled(bool crashHandlingEnabled)
--- This method chooses the type of mobile services to use: - `gms` for Google Mobile Services (default) - `hms` for Huawei Mobile Services (can only be used on Huawei devices)
SyneriseInitializer setMessagingServiceType(String messagingServiceType)
--- This method initializes Synerise.
Future<void> init() async
# Android ## Class reference - Android # SDK lifecycle --- ## Initialization --- This method initializes Synerise.
This method must be called before any other Synerise SDK method and only once during the application's lifecycle.
**Declared In:** lib/main/synerise_initializer.dart **Class:** [Synerise](/developers/mobile-sdk/class-reference/flutter/lifecycle#synerise) [SyneriseInitializer](/developers/mobile-sdk/class-reference/flutter/lifecycle#syneriseinitializer) **Builder Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **withBaseUrl** | String | no | - | Synerise API custom environment base URL | | **withApiKey** | String | yes | - | Synerise Profile (formerly Client) API Key | | **withDebugModeEnabled** | bool | no | - | Enables or disables console logs | | **withCrashHandlingEnabled** | bool | no | - | Enables or disables crash handling | | **setRequestValidationSalt** | String | no | - | Sets salt string for request validation |
Before version 2.0.0, the `withApiKey` method was called `withClientApiKey`.
**Return Value:** No value is returned. **Example:**
```Dart Synerise.initializer() .withBaseUrl("YOUR_API_BASE_URL") .withApiKey("YOUR_PROFILE_API_KEY") .withDebugModeEnabled(false) .init(); ```
## Change Profile API Key dynamically --- This method changes a Profile (formerly Client) API key dynamically. **Declared In:** lib/synerise.dart **Class:** [Synerise](/developers/mobile-sdk/class-reference/flutter/lifecycle#synerise) **Declaration:**
static Future<void> changeApiKey(String apiKey, [InitializationConfig? config]) async
Before version 2.0.0, this method was called `changeClientApiKey`.
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **clientApiKey** | String | yes | - | Synerise Profile API Key (formerly Client API key) | | **config** | [InitializationConfig](/developers/mobile-sdk/class-reference/flutter/lifecycle#initializationconfig) | no | - | Object for additional initialization settings after the API key change | **Return Value:** No value is returned. ## Change Profile API Key dynamically with config --- This method changes a Profile (formerly Client) API key dynamically, with additional parameters. It can include a salt for [Simple Profile Authentication](/developers/mobile-sdk/user-identification-and-authorization/simple-authentication) requests. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.19.0 | 5.20.0 | 0.23.0 | 1.3.0 | **Declared In:** lib/synerise.dart **Class:** [Synerise](/developers/mobile-sdk/class-reference/flutter/lifecycle#synerise) **Declaration:**
static Future<void> changeApiKey(String apiKey, [InitializationConfig? config]) async
Before version 2.0.0, this method was called `changeClientApiKey`.
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **clientApiKey** | String | yes | - | Synerise Profile API Key (formerly Client API key) | | **config** | [InitializationConfig](/developers/mobile-sdk/class-reference/flutter/lifecycle#initializationconfig) | no | - | Object for additional initialization settings after the API key change | **Return Value:** No value is returned. ## Set up Debug Mode --- This method enables or disables console logs from Synerise SDK.
It is not recommended to use debug mode in the release version of your application.
**Declared In:** lib/main/synerise_initializer.dart **Class:** [Synerise](/developers/mobile-sdk/class-reference/flutter/lifecycle#synerise) **Declaration:**
.withDebugModeEnabled(bool debugModeEnabled)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **enabled** | Bool | yes | - | Enables or disables console logs | **Return Value:** No value is returned. ## Enable Crash Handling --- This method enables or disables crash handling by Synerise SDK.
If set to true, Synerise SDK will send the `client.applicationCrashed` event with information about crash.
**Declared In:** lib/main/synerise_initializer.dart **Class:** [Synerise](/developers/mobile-sdk/class-reference/flutter/lifecycle#synerise) **Declaration:**
.withCrashHandlingEnabled(bool crashHandlingEnabled)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **enabled** | Bool | yes | - | Enables or disables crash handling | **Return Value:** No value is returned. ## Set Request Validation Salt --- This method sets the salt string for request validation. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.14.0 | 5.7.1 | 0.15.0 | 0.7.0 | **Declared In:** lib/main/synerise_initializer.dart **Class:** [Synerise](/developers/mobile-sdk/class-reference/flutter/lifecycle#synerise) **Declaration:**
.setRequestValidationSalt(String requestValidationSalt)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **string** | String | yes | - | Synerise Profile salt string for request validation | **Return Value:** No value is returned. # Android ## Android listeners ### OnRegisterForPushListener {id=on-register-for-push-listener} ##### onRegisterForPushRequired(PushRegistrationOrigin origin) {id=on-register-for-push-listener-on-register-for-push-required-with-origin} This method is called when Synerise needs registration for push notifications. See [Configuring push notifications](/developers/mobile-sdk/configuring-push-notifications/android) for more details.
```Java - void onRegisterForPushRequired(PushRegistrationOrigin origin); ```
```Kotlin fun onRegisterForPushRequired(origin: PushRegistrationOrigin) ```
| Parameter | Type | Description | | --- | --- | --- | | **origin** | [PushRegistrationOrigin](/developers/mobile-sdk/class-reference/android/campaigns#pushregistrationorigin) | Information about the cause of the registration | --- --- ##### onRegisterForPushRequired() {id=on-register-for-push-listener-on-register-for-push-required} This method is called when Synerise needs registration for push notifications. See [Configuring push notifications](/developers/mobile-sdk/configuring-push-notifications/android) for more details.
```Java - void onRegisterForPushRequired(); ```
```Kotlin fun onRegisterForPushRequired() ```
--- --- ### OnNotificationListener {id=on-notification-listener} A listener to handle events from Synerise notifications. See [Configuring push notifications](/developers/mobile-sdk/configuring-push-notifications/android#callback-methods) for more details.
**OnNotificationListener** is available from 4.9.0 SDK version.
##### onNotificationReceived(NotificationInfo notificationInfo) {id=on-notification-listener-on-notification-receive} This method is called when a Synerise notification is received.
```Java - public void onNotificationReceived(NotificationInfo notificationInfo) ```
```Kotlin fun onNotificationReceived(notificationInfo: NotificationInfo) ```
| Parameter | Type | Description | | --- | --- | --- | | **notificationInfo** | [NotificationInfo](/developers/mobile-sdk/class-reference/android/campaigns#notificationinfo) | Object providing info about the notification. | ##### onNotificationDismissed(NotificationInfo notificationInfo) {id=on-notification-listener-on-notification-dismissed} This method is called when a Synerise notification is dismissed.
```Java - public void onNotificationDismissed(NotificationInfo notificationInfo) ```
```Kotlin fun onNotificationDismissed(notificationInfo: NotificationInfo) ```
| Parameter | Type | Description | | --- | --- | --- | | **notificationInfo** | [NotificationInfo](/developers/mobile-sdk/class-reference/android/campaigns#notificationinfo) | Object providing info about the notification. | ##### onNotificationClicked(NotificationInfo notificationInfo) {id=on-notification-listener-on-notification-clicked} This method is called when a Synerise notification is clicked.
```Java - public void onNotificationClicked(NotificationInfo notificationInfo) ```
```Kotlin fun onNotificationClicked(notificationInfo: NotificationInfo) ```
| Parameter | Type | Description | | --- | --- | --- | | **notificationInfo** | [NotificationInfo](/developers/mobile-sdk/class-reference/android/campaigns#notificationinfo) | Object providing information about the notification. | ##### onActionButtonClicked(NotificationInfo notificationInfo, String actionButton) {id=on-notification-listener-on-action-button-clicked} This method is called when an action button is clicked in a Synerise notification.
```Java - public void onActionButtonClicked(NotificationInfo notificationInfo, String actionButton) ```
```Kotlin fun onActionButtonClicked(notificationInfo: NotificationInfo, actionButton: String) ```
| Parameter | Type | Description | | --- | --- | --- | | **notificationInfo** | [NotificationInfo](/developers/mobile-sdk/class-reference/android/campaigns#notificationinfo) | Object providing information about the notification. | | **actionButton** | String | Text on the clicked action button. | --- --- ### OnClientStateChangeListener {id=on-client-state-change-listener} A listener to handle customer's sign-in state changes. To set your object with listener methods, you must use [this method](/developers/mobile-sdk/method-reference/android/client-authentication#set-client-state-change-listener). ##### onClientSignedIn() {id=on-client-state-change-listener-on-client-signed-in} This method is called when the customer signs in.
```Java - public void onClientSignedIn() ```
```Kotlin fun onClientSignedIn() ```
##### onClientSignedOut(ClientSessionEndReason reason) {id=on-client-state-change-listener-on-client-signed-out} This method is called when the customer signs out.
```Java - public void onClientSignedOut(ClientSessionEndReason reason) ```
```Kotlin fun onClientSignedOut(reason:ClientSessionEndReason) ```
| Parameter | Type | Description | | --- | --- | --- | | **reason** | [ClientSessionEndReason](/developers/mobile-sdk/class-reference/android/client#clientsessionendreason) | Specifies the reason for signing out. | --- --- ### OnInjectorListener {id=on-injector-listener} ##### onOpenUrl(SyneriseSource source, String url) {id=on-injector-listener-on-open-url} A listener to handle events from [campaigns](/developers/mobile-sdk/campaigns). Fired when a customer interacts with the URL action. This method returns `true` if activity is closed after executing an action; in other case, it returns `false`.
```Java - boolean onOpenUrl(SyneriseSource source, String url) ```
```Kotlin fun onOpenUrl(source:SyneriseSource, url:String):Boolean ```
| Parameter | Type | Description | | --- | --- | --- | | **source** | SyneriseSource | Interaction source | | **url** | String | URL value from the action of the activity | ##### onOpenUrl(InjectorSource source, String url) {id=on-injector-listener-on-open-url-deprecated} A listener to handle events from [campaigns](/developers/mobile-sdk/campaigns). Fired when a customer interacts with the URL action. This method returns `true` if activity is closed after executing an action; in other case, it returns `false`.
This method was deprecated in SDK version 6.0.0.
```Java - boolean onOpenUrl(InjectorSource source, String url) ```
```Kotlin fun onOpenUrl(source:InjectorSource, url:String):Boolean ```
| Parameter | Type | Description | | --- | --- | --- | | **source** | InjectorSource | Interaction source | | **url** | String | URL value from the action of the activity | ##### onDeepLink(SyneriseSource source, String deepLink) {id=on-injector-listener-on-deeplink} Fired when a customer interacts with the DEEP_LINKING action. The method returns `true` if activity is closed after executing the action; in other case, it returns `false`.
```Java - boolean onDeepLink(SyneriseSource source, String deepLink) ```
```Kotlin fun onDeepLink(source:SyneriseSource, deepLink:String):Boolean ```
| Parameter | Type | Description | | --- | --- | --- | | **source** | SyneriseSource | Interaction source | | **deepLink** | String | Deep link value from the action of the activity | ##### onDeepLink(InjectorSource source, String deepLink) {id=on-injector-listener-on-deeplink} Fired when a customer interacts with the DEEP_LINKING action. The method returns `true` if activity is closed after executing the action; in other case, it returns `false`.
This method was deprecated in SDK version 6.0.0.
```Java - boolean onDeepLink(InjectorSource source, String deepLink) ```
```Kotlin fun onDeepLink(source:InjectorSource, deepLink:String):Boolean ```
| Parameter | Type | Description | | --- | --- | --- | | **source** | InjectorSource | Interaction source | | **deepLink** | String | Deep link value from the action of the activity | --- --- ### OnInAppListener {id=on-in-app-listener} A listener to handle the states of [in-app message](/developers/mobile-sdk/campaigns/in-app-message).
**OnInAppListener** is available from 4.7.0 SDK version.
To set your object with listener methods, you must use [this method](/developers/mobile-sdk/method-reference/android/campaigns#set-in-app-listener). ##### shouldShow(InAppMessageData inAppMessageData) {id=on-in-app-listener-should-show} This method is called after an in-app message is loaded and Synerise SDK asks for permission to show it.
```Java boolean shouldShow(InAppMessageData inAppMessageData) ```
```Kotlin shouldShow(inAppMessageData: InAppMessageData): boolean ```
| Parameter | Type | Description | | --- | --- | --- | | **inAppMessageData** | [InAppMessageData](/developers/mobile-sdk/class-reference/android/campaigns#inappmessagedata) | In-app message data. | ##### onShown(InAppMessageData inAppMessageData) {id=on-in-app-listener-on-shown} This method is called after an in-app message appears.
```Java void onShown(InAppMessageData inAppMessageData) ```
```Kotlin onShown(inAppMessageData: InAppMessageData) ```
| Parameter | Type | Description | | --- | --- | --- | | **inAppMessageData** | [InAppMessageData](/developers/mobile-sdk/class-reference/android/campaigns#inappmessagedata) | In-app message data. | ##### onDismissed(InAppMessageData inAppMessageData) {id=on-in-app-listener-on-dismissed} This method is called after an in-app message disappears.
```Java void onDismissed(InAppMessageData inAppMessageData) ```
```Kotlin onDismissed(inAppMessageData: InAppMessageData) ```
| Parameter | Type | Description | | --- | --- | --- | | **inAppMessageData** | [InAppMessageData](/developers/mobile-sdk/class-reference/android/campaigns#inappmessagedata) | In-app message data. | ##### onContextFromAppRequired(InAppMessageData inAppMessageData) {id=on-in-app-listener-on-context-from-app-required} This method is called when an individual context (for example a profile ID, an item SKU) for an in-app message is needed.
```Java HashMap onContextFromAppRequired(InAppMessageData inAppMessageData) ```
```Kotlin onContextFromAppRequired(inAppMessageData: InAppMessageData): HashMap ```
| Parameter | Type | Description | | --- | --- | --- | | **inAppMessageData** | [InAppMessageData](/developers/mobile-sdk/class-reference/android/campaigns#inappmessagedata) | In-app message data. | ##### onHandledOpenUrl(InAppMessageData inAppMessageData) {id=on-in-app-listener-on-handled-open-url} This method is called when the [`SRInApp.openUrl(url)` method](/docs/campaign/in-app-messages/creating-inapp-templates/creating-inapp-template#open-url) is used in an in-app message.
```Java void onHandledOpenUrl(InAppMessageData inAppMessageData) ```
```Kotlin onHandledOpenUrl(inAppMessageData: InAppMessageData) ```
| Parameter | Type | Description | | --- | --- | --- | | **inAppMessageData** | [InAppMessageData](/developers/mobile-sdk/class-reference/android/campaigns#inappmessagedata) | In-app message data. | ##### onHandledOpenDeepLink(InAppMessageData inAppMessageData) {id=on-in-app-listener-on-handled-open-deeplink} This method is called when the [`SRInApp.openDeeplink(url)` method](/docs/campaign/in-app-messages/creating-inapp-templates/creating-inapp-template#open-deeplink) is used in an in-app message.
```Java void onHandledOpenDeepLink(InAppMessageData inAppMessageData) ```
```Kotlin onHandledOpenDeepLink(inAppMessageData: InAppMessageData) ```
| Parameter | Type | Description | | --- | --- | --- | | **inAppMessageData** | [InAppMessageData](/developers/mobile-sdk/class-reference/android/campaigns#inappmessagedata) | In-app message data. | ##### onCustomAction(String identifier, HashMap params, InAppMessageData inAppMessageData) {id=on-in-app-listener-on-custom-action} This method is called when the [`SRInApp.handleCustomAction(name, params)` method](/docs/campaign/in-app-messages/creating-inapp-templates/creating-inapp-template#trigger-a-custom-action) is used in an in-app message.
```Java void onCustomAction(String identifier, HashMap params, InAppMessageData inAppMessageData) ```
```Kotlin onCustomAction(identifier: String, params: HashMap , inAppMessageData: InAppMessageData) ```
| Parameter | Type | Description | | --- | --- | --- | | **inAppMessageData** | [InAppMessageData](/developers/mobile-sdk/class-reference/android/campaigns#inappmessagedata) | In-app message data. | | **identifier** | String | Identifier of the custom action. | | **params** | HashMap | Custom action parameters. | --- --- ### OnLocationUpdateListener {id=on-location-update-listener} A listener to handle events about location. ##### onLocationUpdateRequired() {id=on-location-update-listener-on-location-update-required} This method is called when the Tracker module requests a location update.
```Java - void onLocationUpdateRequired() ```
```Kotlin fun onLocationUpdateRequired() ```
--- --- ### OnContentWidgetListener {id=on-content-widget-listener} A listener to handle [Content Widget](/developers/mobile-sdk/displaying-recommendations/content-widget) actions. ##### onLoad(ContentWidget contentWidget) {id=on-content-widget-listener-on-load} This method is called after a widget is loaded.
```Java - void onLoad(ContentWidget contentWidget) ```
```Kotlin fun onLoad(contentWidget:ContentWidget) ```
| Parameter | Type | Description | | --- | --- | --- | | **contentWidget` | [ContentWidget](/developers/mobile-sdk/class-reference/android/content-widget#contentwidget) | The widget instance that called the listener method | ##### onLoadingError(ContentWidget contentWidget, ApiError apiError) {id=on-content-widget-listener-on-loading-error} This method is called when an error occurs while loading a widget.
```Java - void onLoadingError(ContentWidget contentWidget, ApiError apiError) ```
```Kotlin fun onLoadingError(contentWidget:ContentWidget, apiError:ApiError) ```
| Parameter | Type | Description | | --- | --- | --- | | **contentWidget** | [ContentWidget](/developers/mobile-sdk/class-reference/android/content-widget#contentwidget) | The widget instance that called the listener method | | **apiError** | [ApiError](/developers/mobile-sdk/class-reference/android/miscellaneous#apierror) | The error that occurred | ##### onClickActionReceive(ContentWidget contentWidget, BaseModel model) {id=on-content-widget-listener-on-click-action-receive} This method is called when the customer clicks a widget’s item.
```Java - void onClickActionReceive(ContentWidget contentWidget, BaseModel model) ```
```Kotlin fun onClickActionReceive(contentWidget:ContentWidget, model:BaseModel) ```
| Parameter | Type | Description | | --- | --- | --- | | **contentWidget** | [ContentWidget](/developers/mobile-sdk/class-reference/android/content-widget#contentwidget) | The widget instance that called the listener method | | **model** | BaseModel | The model's object that was clicked | ##### onLoading(ContentWidget contentWidget, boolean isLoading) {id=on-content-widget-listener-on-loading} This method is called when the widget’s loading state changes.
```Java - void onLoading(ContentWidget contentWidget, boolean isLoading) ```
```Kotlin fun onLoading(contentWidget:ContentWidget, isLoading:Boolean) ```
| Parameter | Type | Description | | --- | --- | --- | | **contentWidget** | [ContentWidget](/developers/mobile-sdk/class-reference/android/content-widget#contentwidget) | The widget instance that called the listener method | | **isLoading** | Boolean | Widget's loading state | ##### onSizeChange(ContentWidget contentWidget, ViewGroup.LayoutParams size) {id=on-content-widget-listener-on-size-change} This method is called when the widget’s size changes.
```Java - void onSizeChange(ContentWidget contentWidget, ViewGroup.LayoutParams size) ```
```Kotlin fun onSizeChange(contentWidget:ContentWidget, size:ViewGroup.LayoutParams) ```
| Parameter | Type | Description | | --- | --- | --- | | **contentWidget** | [ContentWidget](/developers/mobile-sdk/class-reference/android/content-widget#contentwidget) | The widget instance that called the listener method | | **size** | ViewGroup.LayoutParams | Widget's new size | # Modules ### Synerise Main Synerise module responsible for whole SDK. This class is responsible for initialization of SDK. **Declared In:** `com.synerise.sdk.core.Synerise` **Declaration:**
```Java public class Synerise ```
```Kotlin class Synerise ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **settings** | [Settings](/developers/mobile-sdk/class-reference/android/lifecycle#settings) | no | - | Configuration of whole SDK | **Initializers:** There are no initializers. **Methods:** Method to get applicationContext.
public static Context getApplicationContext()
--- Method that generates the document assigned to a slug.
public static String getClientApiKey()
--- Get application ID.
public static String getAppId()
--- Get base URL.
public static String getBaseUrl()
--- Get flag indicating debugMode state.
public static boolean getSyneriseDebugMode()
--- --- --- ### Client Module responsible for all operations connected with a profile (formerly client). **Declared In:** `com.synerise.sdk.client.Client` **Declaration:**
```Java public abstract class Client ```
```Kotlin abstract class Client ```
**Properties:** There are no properties. **Initializers:** There are no initializers. **Methods:** This method sets ClientStateChangeListener to get optional callbacks.
public static void setOnClientStateChangeListener(OnClientStateChangeListener listener)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-authentication#set-client-state-change-listener) --- This method removes ClientStateChangeListener.
public static void removeClientStateChangeListener()
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-authentication#remove-client-state-change-listener) --- This method changes a Profile (formerly Client) API key dynamically.
public static void changeApiKey(@NonNull String apiKey)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/lifecycle#change-profile-api-key-dynamically) --- This method changes a Profile (formerly Client) API key dynamically, with additional parameters.
public static void changeApiKey(String apiKey, InitializationConfig initializationConfig)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/lifecycle#change-profile-api-key-dynamically-with-config) --- This method registers a new customer with an email, password, and optional data.
public static IApiCall registerAccount(@NonNull RegisterClient registerClient)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-authentication#register-customer-account) --- This method activates a customer with email.
public static IApiCall requestAccountActivation(String email)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-authentication#request-customer-account-activation) --- This method confirms a customer account with the confirmation token.
public static IApiCall confirmAccountActivation(String token)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-authentication#confirm-customer-account-activation) --- This method requests a customer's account registration process with the PIN code.
public static IApiCall requestAccountActivationByPin(String email)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-authentication#request-customer-account-activation-by-pin) --- This method confirms a customer's account registration process with the PIN code.
public static IApiCall confirmAccountActivationByPin(String pinCode, String email)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-authentication#confirm-customer-account-activation-by-pin) --- This method signs a customer in to obtain a JSON Web Token (JWT) which can be used in subsequent requests.
public static IApiCall signIn(@NonNull String email, @NonNull String password)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-authentication#sign-in-a-customer) --- This method signs a customer in to obtain a JSON Web Token (JWT) which can be used in subsequent requests.
public static IDataApiCall<AuthConditions> signInConditionally(@NonNull String email, @NonNull String password)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-authentication#sign-in-a-customer-conditionally) --- This method authenticates a customer with OAuth, Facebook, Google, Apple, or Synerise.
public static IApiCall authenticate(@NonNull String token, @NonNull ClientIdentityProvider provider, @Nullable Agreements agreements, @Nullable Attributes attributes, @Nullable String authId)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-authentication#authenticate-customer-by-identityprovider) --- This method authenticates a customer with OAuth, Facebook, Google, Apple, or Synerise.
public static IDataApiCall<AuthConditions> authenticateConditionally(@NonNull String token, @NonNull ClientIdentityProvider provider, @Nullable Agreements agreements, @Nullable Attributes attributes, @Nullable String authId)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-authentication#authenticate-customer-conditionally-by-identityprovider) --- This method authenticates a customer with OAuth.
public static IApiCall authenticateByOAuth(@NonNull String accessToken, @Nullable Agreements agreements, @Nullable Attributes attributes, @Nullable String authId)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-authentication#authenticate-customer-by-oauth-with-registration) - **REMOVED in version 6.0.0** --- This method authenticates a customer with OAuth.
public static IApiCall authenticateByOAuthIfRegistered(@NonNull String accessToken, @Nullable String authId)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-authentication#authenticate-customer-by-oauth-without-registration) - **REMOVED in version 6.0.0** --- This method authenticates a customer with Facebook.
public static IApiCall authenticateByFacebook(@NonNull String facebookToken, @Nullable Agreements agreements, @Nullable Attributes attributes, @Nullable String authId)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-authentication#authenticate-customer-by-facebook-with-registration) - **REMOVED in version 6.0.0** --- This method authenticates a customer with Facebook.
public static IApiCall authenticateByFacebookIfRegistered(@NonNull String facebookToken, @Nullable String authId)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-authentication#authenticate-customer-by-facebook-without-registration) - **REMOVED in version 6.0.0** --- This method signs in a customer in with the provided token payload.
public static IApiCall authenticateWithTokenPayload(TokenPayload tokenPayload, @NonNull String authId)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-authentication#authenticate-customer-with-token-payload) --- This method authenticates a customer with Simple Profile Authentication.
public static IApiCall simpleAuthentication(ClientData clientData, String authId)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-authentication#authenticate-customer-via-simple-profile-authentication) --- This method checks if a customer is signed in (via Synerise Authentication - RaaS, OAuth, Facebook, Apple).
public static boolean isSignedIn()
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-authentication#check-if-a-customer-is-signed-in-via-raas-oauth-facebook-apple) --- This method checks if a customer is signed in (via Simple Profile Authentication).
public static boolean isSignedInViaSimpleAuthentication()
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-authentication#check-if-a-customer-is-signed-in-via-simple-profile-authentication) --- This method signs out a customer out.
public static void signOut()
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-authentication#sign-out-customer) --- This method signs out a customer out with a chosen mode.
public static void signOut(ClientSignOutMode mode)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-authentication#sign-out-customer-with-mode) - **REMOVED in version 6.0.0** --- This method signs out a customer out with a chosen mode and Determines if the method should sign out all devices
public static IApiCall signOut(ClientSignOutMode mode, Boolean signOutFromAllDevices)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-authentication#sign-out-customer-with-mode-or-from-all-devices) --- This method refreshes the customer’s current token.
public static IApiCall refreshToken()
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-session#refresh-customer-token) --- This method retrieves the customer’s current, active token.
public static IDataApiCall<Token> retrieveToken()
    [(Click for more details)](/developers/mobile-sdk/method-reference/android/client-session#get-customer-token)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-session#retrieve-customer-token) --- This method retrieves the customer’s current UUID.
public static String getUuid()
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-session#get-current-customer-uuid) --- Retrieves the current UUID or generates a new one from a seed.
public static String getUuidForAuthentication(@NonNull String authId)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-session#get-customer-uuid-for-use-in-authentication) --- This method regenerates the UUID and clears the authentication token, login session, custom email, and custom identifier.
public static boolean regenerateUuid()
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-session#regenerate-customer) --- This method regenerates the UUID and clears the authentication token, login session, custom email, and custom identifier.
public static boolean regenerateUuid(String clientIdentifier)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-session#regenerate-customer-with-identifier) --- This method destroys the session completely.
public static void destroySession()
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-session#destroy-current-session) --- This method gets a customer’s account information.
public static IDataApiCall<GetAccountInformation> getAccount()
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-account#get-customer-account-information) --- This method retrieves events for an authenticated customer.
public static IDataApiCall<List<ClientEventData>> getEvents(ClientEventsQuery clientEventsQuery)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/tracking#get-customers-events) --- This method updates a customer’s account’s basic information (without identification data: uuid, customId, email).
public static IApiCall updateAccountBasicInformation(@NonNull UpdateAccountBasicInformation accountInformation)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-account#update-customer-account-basic-information) --- This method updates a customer’s account information.
public static IApiCall updateAccount(@NonNull UpdateAccountInformation accountInformation)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-account#update-customer-account-information) --- This method requests a customer’s password reset with email.
public static IApiCall requestPasswordReset(@NonNull PasswordResetRequest resetRequest)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-account#request-password-reset-for-customer-account) --- This method confirm a customer’s password reset with the new password and token provided by password reset request.
public static IApiCall confirmPasswordReset(@NonNull PasswordResetConfirmation resetConfirmation)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-account#confirm-password-reset-for-customer-account) --- This method changes a customer’s password.
public static IApiCall changePassword(@NonNull String oldPassword, @NonNull String password)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-account#change-customers-account-password) --- This method requests a customer's email change.
public static IApiCall requestEmailChange(String email, String password, @Nullable String externalToken, @Nullable String authId)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-account#request-email-change-for-customer-account) --- This method confirms an email change.
public static IApiCall confirmEmailChange(String token, boolean newsletterAgreement)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-account#confirm-email-change-for-customer-account) --- Requests a customer's phone update. A confirmation code is sent to the phone number.
public static IApiCall requestPhoneUpdate(String phone)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-account#request-phone-update-on-customer-account) --- This method confirms a phone number update. This action requires the new phone number and confirmation code as parameters.
public static IApiCall confirmPhoneUpdate(String phone, String confirmationCode, @Nullable Boolean smsAgreement)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-account#confirm-phone-update-on-customer-account) --- This method deletes a customer's account.
public static IApiCall deleteAccount(String clientAuthFactor, ClientIdentityProvider clientIdentityProvider, @Nullable String authId)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-account#delete-customer-account-by-identity-provider) --- This method deletes a customer's account.
public static IApiCall deleteAccount(String password)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-account#delete-customer-account) - **REMOVED in version 6.0.0** --- This method deletes a customer's account by OAuth.
public static IApiCall deleteAccountByOAuth(String accessToken, @Nullable String uuid)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-account#delete-customer-account-by-oauth) - **REMOVED in version 6.0.0** --- This method deletes a customer's account by Facebook.
public static IApiCall deleteAccountByFacebook(String facebookToken, @Nullable String uuid)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/client-account#delete-customer-account-by-facebook) - **REMOVED in version 6.0.0** --- This method passes the Firebase Token to Synerise for notifications and doesn't update the agreement of the profile.
public static IApiCall registerForPush(@NonNull String firebaseId)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/campaigns#register-for-push-notifications-without-agreement) --- This method passes the Firebase Token to Synerise for notifications.
public static IApiCall registerForPush(@NonNull String firebaseId, boolean mobilePushAgreement)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/campaigns#register-for-push-notifications) --- --- --- ### Tracker Module responsible for sending events. **Declared In:** `com.synerise.sdk.event.Tracker` **Declaration:**
```Java public abstract class Tracker ```
```Kotlin abstract class Tracker ```
**Properties:** There are no properties. **Initializers:** There are no initializers. **Methods:** This method sets a custom identifier in the parameters of every event.
public static void setCustomIdentifier(String customIdentifier)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/tracking#set-custom-identifier-for-events) --- This method sets a custom email in the parameters of every event.
public static void setCustomEmail(String customEmail)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/tracking#set-custom-email-for-events) --- This method sends an event.
public static void send(Event event)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/tracking#send-event) --- This method forces sending the events from the queue to the server.
public static void flush()
[(Click for more details)](/developers/mobile-sdk/method-reference/android/tracking#flush-events-from-tracker) --- --- --- ### Injector Module responsible for handling push notifications and in-app communication. **Declared In:** `com.synerise.sdk.injector.Injector` **Declaration:**
```Java public abstract class Injector ```
```Kotlin abstract class Injector ```
**Properties:** There are no properties. **Initializers:** There are no initializers. **Methods:** Closes an in-app message and sends an `inApp.discard` event. Usage examples: - Closing a top bar or bottom bar when the user taps outside the in-app area. - Automatically dismissing messages when navigating away from a screen. - Controlling in-app visibility based on app logic for a smoother user experience.
public static void closeInAppMessage(String campaignHash)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/campaigns#close-in-app-message) --- This method handles a notification payload and starts activity.
public static boolean handlePushPayload(Bundle bundle)
public static boolean handlePushPayload(Map<String, String> pushPayload)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/campaigns#handle-synerise-push-notification) --- This method decrypts the notification payload.
public static Map<String, String> decryptPushPayload(Map<String, String> pushPayload) throws DecryptionException
[(Click for more details)](/developers/mobile-sdk/method-reference/android/campaigns#decrypt-push-notification) --- This method verifies if a notification is encrypted.
public static boolean isPushEncrypted(Map<String, String> pushPayload)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/campaigns#check-if-push-notification-is-encrypted) --- This method verifies if a notification was sent by Synerise.
public static boolean isSynerisePush(Map<String, String> pushPayload)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/campaigns#check-if-push-notification-is-from-synerise) --- This method verifies if a notification's sender is Synerise and if the notification is a Silent Command.
public static boolean isSilentCommand(Map<String, String> pushPayload)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/campaigns#check-if-push-notification-is-a-silent-command) --- This method verifies if a notification's sender is Synerise and if the notification is a Silent SDK Command.
public static boolean isSilentCommandSdk(Map<String, String> pushPayload)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/campaigns#check-if-push-notification-is-a-silent-sdk-command) --- This method verifies if a notification’s sender is Synerise and if the notification is a Simple Push campaign
public static boolean isSyneriseSimplePush(Map<String, String> pushPayload)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/campaigns#check-if-push-notification-is-a-simple-push-campaign) --- This method verifies if a notification’s sender is Synerise and if the notification is a Banner campaign.
public static boolean isSyneriseBanner(Map<String, String> pushPayload)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/campaigns#check-if-push-notification-is-a-banner-campaign) - **REMOVED in version 6.0.0** --- This method converts push payload into SilentCommand object.
public static SilentCommand getSilentCommand(Map<String, String> payload) throws ValidationException
[(Click for more details)](/developers/mobile-sdk/method-reference/android/campaigns#get-a-silent-command) --- This method fetches a walkthrough.
public static void getWalkthrough()
[(Click for more details)](/developers/mobile-sdk/method-reference/android/campaigns#get-walkthrough) - **REMOVED in version 6.0.0** --- This method shows a walkthrough when it is loaded.
public static boolean showWalkthrough()
[(Click for more details)](/developers/mobile-sdk/method-reference/android/campaigns#show-walkthrough) - **REMOVED in version 6.0.0** --- This method checks if a walkthrough is loaded.
public static boolean isWalkthroughLoaded()
[(Click for more details)](/developers/mobile-sdk/method-reference/android/campaigns#check-if-walkthrough-is-loaded) - **REMOVED in version 6.0.0** --- This method checks if the walkthrough is unique compared to the previous one.
public static boolean isLoadedWalkthroughUnique()
[(Click for more details)](/developers/mobile-sdk/method-reference/android/campaigns#check-if-loaded-walkthrough-is-unique) - **REMOVED in version 6.0.0** --- This method fetches banners set for mobile campaigns and caches the valid ones.
public static void fetchBanners()
public static void fetchBanners(@NonNull final DataActionListener<List<TemplateBanner>> successListener,
                                    @NonNull final DataActionListener<ApiError> errorListener)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/campaigns#fetch-banners)- **REMOVED in version 6.0.0** --- This method provides valid banners directly from SDK cache.
public static List<TemplateBanner> getBanners()
[(Click for more details)](/developers/mobile-sdk/method-reference/android/campaigns#get-banners) --- This method shows a banner immediately.
public static void showBanner(TemplateBanner banner, boolean markPresented)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/campaigns#show-banner)- **REMOVED in version 6.0.0** --- This method fetches Push Notifications set for mobile campaigns.
public static IDataApiCall<List<SynerisePushResponse>> getPushes()
[(Click for more details)](/developers/mobile-sdk/method-reference/android/campaigns#get-pushes) --- --- --- ### Promotions Module responsible for managing promotions. **Declared In:** `com.synerise.sdk.promotions.Promotions` **Declaration:**
```Java public abstract class Promotions ```
```Kotlin abstract class Promotions ```
**Properties:** There are no properties. **Initializers:** There are no initializers. **Methods:** This method retrieves all available promotions that are defined for a customer.
public static IDataApiCall<PromotionResponse> getPromotions()
[(Click for more details)](/developers/mobile-sdk/method-reference/android/promotions#get-all-promotions-of-a-customer) --- This method retrieves all available promotions that are defined for a customer.
public static IDataApiCall<PromotionResponse> getPromotions(PromotionsApiQuery promotionsApiQuery)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/promotions#get-all-promotions-of-a-customer) --- This method retrieves the promotion with the specified UUID.
public static IDataApiCall<SinglePromotionResponse> getPromotionByUuid(@NonNull String uuid)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/promotions#get-promotion-by-uuid) --- This method retrieves the promotion with the specified code.
public static IDataApiCall<SinglePromotionResponse> getPromotionByCode(@NonNull String code)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/promotions#get-promotion-by-code) --- This method activates the promotion with the specified UUID.
public static IApiCall activatePromotionByUuid(@NonNull String uuid)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/promotions#activate-promotion-by-uuid) --- This method activates the promotion with the specified code.
public static IApiCall activatePromotionByCode(@NonNull String code)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/promotions#activate-promotion-by-code) --- This method deactivates the promotion with the specified UUID.
public static IApiCall deactivatePromotionByUuid(@NonNull String uuid)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/promotions#deactivate-promotion-by-uuid) --- This method deactivates the promotion with the specified code.
public static IApiCall deactivatePromotionByCode(@NonNull String code)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/promotions#deactivate-promotion-by-code) --- This method retrieves an assigned voucher code or assigns a voucher from a pool identified by UUID to the profile. When the voucher is assigned for the first time, a [voucherCode.assigned](/docs/assets/events/event-reference/loyalty#vouchercodeassigned) event is produced.
public static IDataApiCall<AssignVoucherResponse> getOrAssignVoucher(@NonNull String poolUuid)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/promotions#get-or-assign-voucher-from-pool) --- This method assigns a voucher from a pool identified by UUID to the profile. A [voucherCode.assigned](/docs/assets/events/event-reference/loyalty#vouchercodeassigned) event is produced.
public static IDataApiCall<AssignVoucherResponse> assignVoucherCode(@NonNull String poolUuid)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/promotions#assign-voucher-code-from-pool) --- This method retrieves voucher codes for a customer.
public static IDataApiCall<VoucherCodesResponse> getAssignedVoucherCodes()
[(Click for more details)](/developers/mobile-sdk/method-reference/android/promotions#get-voucher-codes-assigned-to-customer) --- --- --- ### Content Module responsible for managing documents, reccommendations and content widget. **Declared In:** `com.synerise.sdk.content.Content` **Declaration:**
```Java public abstract class Content ```
```Kotlin abstract class Content ```
**Properties:** There are no properties. **Initializers:** There are no initializers. **Methods:** This method generates the document assigned to a slug.
public static IDataApiCall<Object> getDocument(String slugName)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/content#get-document) - **REMOVED in version 6.0.0** --- This method generates the document that is defined for the provided slug.
public static IDataApiCall<Document> generateDocument(String slugName)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/content#generate-document) --- This method generates the document that is defined for parameters provided in the query object.
public static IDataApiCall<Document> generateDocument(DocumentApiQuery documentApiQuery)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/content#generate-document-with-query-parameters) --- This method generates documents that are defined for parameters provided in the query object.
public static IDataApiCall<List<Object>> getDocuments(DocumentsApiQuery documentsApiQuery)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/content#get-documents) - **REMOVED in version 6.0.0** --- This method generates recommendations that are defined for the options provided. The recommendations are generated by using a document with an insert. For instructions, see ["Displaying AI recommendations > With documents and screen views"](/developers/mobile-sdk/displaying-recommendations/documents).
public static IDataApiCall<RecommendationResponse> getRecommendations(String slugName, RecommendationRequestBody options)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/content#get-recommendations) - **REMOVED in version 6.0.0** --- This method generates recommendations that are defined for the options provided. The recommendations are generated by using a document with an insert. For instructions, see ["Displaying AI recommendations > With documents and screen views"](/developers/mobile-sdk/displaying-recommendations/documents).
public static IDataApiCall<RecommendationResponse> getRecommendationsV2(String slugName, RecommendationRequestBody options)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/content#get-recommendations-v2) --- This method generates the customer's highest-priority screen view campaign.
public static IDataApiCall<ScreenViewResponse> getScreenView()
[(Click for more details)](/developers/mobile-sdk/method-reference/android/content#get-screen-view) - **REMOVED in version 6.0.0** --- This method generates a customer's highest-priority screen view campaign from the feed with the provided feed slug.
public static IDataApiCall<ScreenView> generateScreenView(String feedSlug)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/content#generate-screen-view) --- This method generates customer's highest-priority screen view campaign that is defined for parameters provided in the query object.
public static IDataApiCall<ScreenView> generateScreenView(ScreenViewApiQuery screenViewApiQuery)
[(Click for more details)](/developers/mobile-sdk/method-reference/android/content#generate-screen-view-with-query-parameters) # Android ## Content Widget (Android) Content widget is a feature in the Software Development Kit that allows you to embed an easily customizable view with [recommendations](/docs/ai-hub/recommendations-v2) in your application. Two view layouts are available: - Horizontal slider - a single row view that slides horizontally on the screen. - Grid view - can be displayed as full- or half-screen grid layout within your app. Both views offer a number of configuration options that allow you to style the view consistently in the app. Additionally, the Content widget automatically tracks 4 events: - `recommendation.seen` or `recommendation.view` (depending on configuration) sent when a recommended item is visible to the customer.
Recommendation.seen event
Recommendation.seen event
- `recommendation.click` sent when a customer clicks the recommended item.
Recommendation.click event
Recommendation.click event
- `product.like` sent when a customer clicks a selectable button in the recommendation. (The button must be added)
Event sent when a user clicks the
Event sent when a user clicks the "like" button on an item
- `product.dislike` sent when a customer clicks a selectable button in the recommendation a second time. (The button must be added)
Product.dislike event
Product.dislike event
Currently, the widget can only be used for displaying AI recommendations.
### Prerequisites --- To use the content widget feature, you must: - Obtain a customer token from [Customer Authentication](/developers/mobile-sdk/user-identification-and-authorization/overview#authenticated-customers). - [Create an AI Recommendation](/docs/ai-hub/recommendations-v2). - [Create a document](/docs/assets/documents). Such a document should contain the following content:
{
      "name": "Similar Products",
      "recommendations": "{% recommendations_json3 campaignId=COhsCCOdu8Cg %} {% endrecommendations_json3 %}"
  }
- In the notepad, save the document's slug and the ID of the recommendation for later use.
It's a good practice to name slugs based on the area of the app that you want to place the content in, for example `product-details`, `menu`, and so on.
### Basic implementation --- Configure the `ContentWidgetOptions` and `ContentWidgetAppearance` settings first. | Class | Description | | --- | --- | | `ContentWidgetOptions` | Contains options for business logic, such as the slug, product identifier, and so on. [Read more](#widget-options).| | `ContentWidgetAppearance` | Contains the UI configuration. [Read more](#widget-options). | The example below is the most basic implementation.
```java String productId = "10214"; String slug = "similar"; ContentWidgetOptions options = new ContentWidgetRecommendationsOptions(this, slug, new OnRecommendationModelMapper() { @Override public ContentWidgetRecommendationDataModel onRecommendationMapping(Recommendation recommendation) { // Mapping provided by HashMap data = recommendation.getFeed(); String imageLink = (String) data.get("imageLink"); String productName = (String) data.get("title"); String price = null; String salePrice = null; try { JSONObject json = new JSONObject(data.get("price").toString()); price = json.getString("value"); if (data.containsKey("salePrice")) { JSONObject jsonSalePrice = new JSONObject(data.get("salePrice").toString()); salePrice = jsonSalePrice.getString("value"); } } catch (JSONException e) { e.printStackTrace(); } return new ContentWidgetRecommendationDataModel(productName, imageLink, price, salePrice, null); } }); options.attributes.put(ContentWidgetOptions.ContentWidgetOptionsAttributeKeyProductId, productId); ContentWidgetItemLayout itemLayoutDetails = new ContentWidgetItemLayout(); ContentWidgetHorizontalSliderLayout layout = new ContentWidgetHorizontalSliderLayout(); ContentWidgetAppearance contentWidgetAppearance = new ContentWidgetAppearance(layout, itemLayoutDetails); ContentWidget widget = new ContentWidget(options, contentWidgetAppearance); View view = widget.getView(); // our widget insertPoint.addView(view); // your view which will receive widget ```
```kotlin val productId = "10214" val slug = "similar" val options = ContentWidgetOptions(this, slug) options.attributes.put(ContentWidgetOptions.ContentWidgetOptionsAttributeKeyProductId, productId); val itemLayoutDetails = ContentWidgetItemLayout() val layout = ContentWidgetHorizontalSliderLayout() val contentWidgetAppearance = ContentWidgetAppearance(layout, itemLayoutDetails) val widget = ContentWidget(options, contentWidgetAppearance) val view = widget.getView() // our widget insertPoint.addView(view) // your view which will receive widget ```
### Widget options --- The [ContentWidgetRecommendationOptions](/developers/mobile-sdk/class-reference/android/content-widget#contentwidgetoptions) class is responsible for defining the business logic options of the widget, for example: - document slug - product identifier (which is stored inside class instance in attributes HashMap) - recommendation model mapper The table explains the parameters that can be configured in `ContentWidgetRecommendationOptions`. | Parameter | Type | Default | Description | | --- | --- | --- | --- | | activity | `Activity` | - | Activity to which you insert the widget (must be included) | | slug | `String` | - | Slug of a document | | attributes | `Hashmap` | - | Custom attributes for generating data | | mapper | `OnRecommendationModelMapper` | - | Mapper responsible for mapping data from feed to contentWidgetRecommendation model | | recommendationEventType | `RecommendationEventType` | - | Recommendation event type.
  • RECOMMENDATION_VIEW_EVENT sends all products in one event. We highly recommend using this type of event in content widget.
  • RECOMMENDATION_SEEN_EVENT sends each event as a separate event.
| #### Example
```java String productId = "10214"; String slug = "similar"; ContentWidgetOptions options = new ContentWidgetRecommendationsOptions(this, slug, new OnRecommendationModelMapper() { @Override public ContentWidgetRecommendationDataModel onRecommendationMapping(Recommendation recommendation) { // here you should implement your mapping to SyneriseModel HashMap data = recommendation.getFeed(); String imageLink = (String) data.get("imageLink"); String productName = (String) data.get("title"); String price = null; String salePrice = null; try { JSONObject json = new JSONObject(data.get("price").toString()); price = json.getString("value"); if (data.containsKey("salePrice")) { JSONObject jsonSalePrice = new JSONObject(data.get("salePrice").toString()); salePrice = jsonSalePrice.getString("value"); } } catch (JSONException e) { e.printStackTrace(); } return new ContentWidgetRecommendationDataModel(productName, imageLink, price, salePrice, null); } }); options.attributes.put(ContentWidgetOptions.ContentWidgetOptionsAttributeKeyProductId, productId); ```
```kotlin var productId = "10214" var slug = "similar" var options: ContentWidgetOptions = ContentWidgetRecommendationsOptions(this, slug, object : OnRecommendationModelMapper() { fun onRecommendationMapping(recommendation: Recommendation): ContentWidgetRecommendationDataModel? { // here you should implement your mapping to SyneriseModel val data = recommendation.getFeed() val imageLink = data["imageLink"] as String? val productName = data["title"] as String? var price: String? = null var salePrice: String? = null try { val json = JSONObject(data["price"].toString()) price = json.getString("value") if (data.containsKey("salePrice")) { val jsonSalePrice = JSONObject(data["salePrice"].toString()) salePrice = jsonSalePrice.getString("value") } } catch (e: JSONException) { e.printStackTrace() } return ContentWidgetRecommendationDataModel(productName, imageLink, price, salePrice, null) } }) options.attributes.put(ContentWidgetOptions.ContentWidgetOptionsAttributeKeyProductId, productId); ```
The recommendation response depends on your item feed. In order to map your item feed, override `onRecommendationMapping` and inside it return [ContentWidgetRecommendationDataModel](/developers/mobile-sdk/class-reference/android/content-widget#contentwidgetrecommendationdatamodel). The configuration of the data frames is available in [AI engine configuration](https://app.synerise.com/spa/modules/ai-v2/config). It is defined separately for each item feed.
### Appearance configuration --- The [ContentWidgetAppearance](/developers/mobile-sdk/class-reference/android/content-widget#contentwidgetappearance) class is responsible for defining the appearance of the widget. The class consists of parameters that define the widget's appearance, however, two of them are the most important: - **Main layout class**: defines the way of distributing elements in the widget. Currently, two layouts are provided: - `ContentWidgetHorizontalSliderLayout` - `ContentWidgetGridLayout` - **Item layout class**: defines appearance and parameters for the item in the widget. Currently, there is only one layout provided: `ContentWidgetBaseItemLayout`. The table explains the parameters that can be configured in [ContentWidgetAppearance](/developers/mobile-sdk/class-reference/android/content-widget#contentwidgetappearance). | Parameter | Type | Default | Description | | --- | --- | --- | --- | | layout | [ContentWidgetBaseLayout](/developers/mobile-sdk/class-reference/android/content-widget#contentwidgetbaselayout) | - | Class that inherits from `ContentWidgetBaseLayout`, contains the UI details of the widget's layout | | itemLayout | [ContentWidgetBaseItemLayout](/developers/mobile-sdk/class-reference/android/content-widget#contentwidgetbaseitemlayout) | - | Class that inherits from `ContentWidgetBaseItemLayout`, contains the UI details of a single item in a widget | ### Layouts #### Horizontal slider --- This layout is intended to present recommendations in a fixed-hight horizontal scrollable slider. Each item in the slider is called a *card*.
Click to see a screen with example widget with horizontal slider
Content Widget - Horizontal Slider
##### Parameters The table below contains the parameters that can be configured in [ContentWidgetHorizontalSliderLayout](/developers/mobile-sdk/class-reference/android/content-widget#contentwidgetsliderlayout). | Parameter | Type | Default | Description | | --- | --- | --- | --- | | cardViewSize | `ViewGroup.LayoutParams` | 0 | Size of a single item (cardView). You can provide this parameter in dp (recommended) or px. | | cardViewHorizontalSpacing | `Int` | 0 | Horizontal spacing between items. You can provide this parameter in dp (recommended) or px. | | cardViewBackgroundColor | `Int` | #fff | Background color of a cardView |
`CardViewSize` can be set either by attribution or by a setter.
##### Example
```java ContentWidgetHorizontalSliderLayout layout = new ContentWidgetHorizontalSliderLayout(); layout.setCardViewSize(250, 300); layout.cardViewHorizontalSpacing = 15; layout.cardViewBackgroundColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.regent); ```
```kotlin val layout = ContentWidgetHorizontalSliderLayout() layout.setCardViewSize(250, 300) layout.cardViewHorizontalSpacing = 15 layout.cardViewBackgroundColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.regent) ```
#### Grid view --- This layout presents recommendations in a vertical scrollable grid, with elements organized into columns and rows. You can create a full- or half-screen widget.
Click to see a screen with example widget with grid layout
Content Widget - Grid View
##### Constructor | Parameter | Type | Default | Description | | --- | --- | --- | --- | | preferredWidth | `Float` | - | Preferred width of your widget. You can pass the width in dp (recommended) or px |
```java float screenWidthDp = displayMetrics.widthPixels; ContentWidgetGridLayout layout = new ContentWidgetGridLayout(screenWidthDp); ```
```kotlin var screenWidthDp = displayMetrics.widthPixels var layout = ContentWidgetGridLayout(screenWidthDp) ```
##### Parameters The table contains the parameters that can be configured in [ContentWidgetGridLayout](/developers/mobile-sdk/class-reference/android/content-widget#contentwidgetgridlayout). | Parameter | Type | Default | Description | | --- | --- | --- | --- | | cardViewSize | `ViewGroup.LayoutParams` | 0 | Size of a single item (cardView) | | cardViewVerticalSpacing | `Int` | 0 | Vertical spacing between items in dp or px | | cardViewHorizontalSpacing | `Int` | 0 | Horizontal spacing between items in dp or px | | cardViewBackgroundColor | `Int` | #fff | Background color of a cardView | | includeEdgeSpacing | `Boolean` | false | When `true`, edge spacing is enabled |
CardViewSize and preferredWidth can be set by attribution or by a setter.
##### Example
```java float screenWidthDp = displayMetrics.widthPixels; ContentWidgetGridLayout layout = new ContentWidgetGridLayout(screenWidthDp); layout.setCardViewSize(250, 300); layout.cardViewHorizontalSpacing = 15; layout.cardViewVerticalSpacing = 20; layout.includeEdgeSpacing = false; layout.cardViewBackgroundColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.regent); ```
```kotlin val screenWidthDp = displayMetrics.widthPixels val layout = ContentWidgetGridLayout(screenWidthDp) layout.setCardViewSize(250, 300) layout.cardViewHorizontalSpacing = 15 layout.cardViewVerticalSpacing = 20 layout.includeEdgeSpacing = false layout.cardViewBackgroundColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.regent) ```
#### Basic item layout --- This is the basic layout for items. It contains: the image, the title, and the price from the uploaded data. ##### Parameters The table below contains parameters that can be configured in `ContentWidgetItemLayout`. | Parameter | Type | Default | Description | | --- | --- | --- | --- | | imageHeightToCardHeightRatio | `Double` | 0.6 | Image height. A ratio of `0.6` means that the image height equals 60% of the entire height of an item | | imageWidthToCardWidthRatio | `Double` | 1 | Image width. `1` means that the image width is equal to the width of the item | | imageScaleType | `ImageView.ScaleType` | ImageView.ScaleType.CENTER_INSIDE | Scaling type of the image | | imageMargin | `Int` | 0 | General margin of the image | | itemLabelStyle | `Typeface` | - | Typeface of the label | | itemLabelSize | `Int` | 12 | Size of the label | | itemLabelColor | `Int` | #000 | Label text color | | itemLabelMarginLeft | `Int` | 0 | Left margin of the label text | | itemLabelMarginRight | `Int` | 0 | Right margin of the label text | | itemLabelMarginBottom | `Int` | 0 | Bottom margin of the label text | | itemLabelMarginTop | `Int` | 0 | Top margin of the label text | | cardViewCornerRadius | `Float` | 0 | Corner radius of the cardView | | cardViewElevation | `Float` | 0 | Elevation of the cardView | | itemTitleStyle | `Typeface` | - | Typeface of the product title | | itemTitleSize | `Int` | 12 | Size of the title | | itemTitleColor | `Int` | #000 | Color of the title text | | itemTitleMarginLeft | `Int` | 0 | Left margin of the title text | | itemTitleMarginRight | `Int` | 0 | Right margin of the title text | | itemTitleMarginBottom | `Int` | 0 | Bottom margin of the title text | | itemTitleMarginTop | `Int` | 0 | Top margin of the title text | | itemPriceStyle | `Typeface` | - | Typeface of the price | | itemPriceSize | `Int` | 12 | Size of the price text | | itemPriceColor | `Int` | #000 | Color of the price text | | itemPriceMarginLeft | `Int` | 0 | Left margin of the price text | | itemPriceMarginRight | `Int` | 0 | Right margin of the price text | | itemPriceMarginTop | `Int` | 0 | Top margin of the price text | | itemPriceMarginBottom | `Int` | 0 | Bottom margin of the price text | | itemSalePriceStyle | `Typeface` | - | Typeface of the sale price | | itemSalePriceSize | `Int` | 12 | Size of the sale price | | itemSalePriceColor | `Int` | #000 | Color of the sale price text | | itemSalePriceGravity | `Int` | Gravity.LEFT | Gravity of the sale price text | | itemSalePriceMarginLeft | `Int` | 0 | Left margin of the sale price text | | itemSalePriceMarginRight | `Int` | 0 | Right margin of the sale price text | | itemSalePriceMarginTop | `Int` | 0 | Top margin of the sale price text | | itemSalePriceMarginBottom | `Int` | 0 | Bottom margin of the sale price text | | itemSalePriceOrientation | `Int` | LinearLayout.HORIZONTAL | Orientation of the sale price text | | isItemSalePriceVisible | `boolean` | false | Flag determining whether to show the sale price or not | | itemDiscountPercentageLabelStyle | `Typeface` | - | Typeface of discount percentage label | | itemDiscountPercentageLabelColor | `Int` | #000 | Color of discount percentage label | | itemDiscountPercentageLabelSize | `Int` | 12 | Size of the discount percentage label text | | itemDiscountPercentageLabelMarginLeft | `Int` | 0 | Left margin of the discount percentage label text | | itemDiscountPercentageLabelMarginRight | `Int` | 0 | Right margin of the discount percentage label text | | itemDiscountPercentageLabelMarginTop | `Int` | 0 | Top margin of the discount percentage label text | | itemDiscountPercentageLabelMarginBottom | `Int` | 0 | Bottom margin of the discount percentage label text | | isItemDiscountPercentageLabelVisible | `boolean` | false | Flag determining whether to show the discount percentage label or not | | itemActionButton | `ImageButtonCustomAction` | - | Object which stores all information about the ActionButton | | itemBadge | `ContentWidgetBadge` | - | Object which stores all information about the Badge | | imageButtonCustomActionGravity | `Int` | Gravity.TOP | Gravity of the actionButton |
- You can combine the `Gravity.*` parameters. For example, to align an item to top and right, use: ```Gravity.TOP | Gravity.RIGHT``` - All text elements are centered horizontally.
ItemTitleMargins, ItemPriceMargins, ItemLabelMargins, ItemSalePriceMargins, and ItemDiscountLabelMargins can be set using setters, as shown below.
```java public void setItemTitleMargins(int marginLeft, int marginRight, int marginTop, int marginBottom) ```
```kotlin fun setItemTitleMargins(marginLeft:Int, marginRight:Int, marginTop:Int, marginBottom:Int) ```
#### Example
```java ContentWidgetItemLayout itemLayoutDetails = new ContentWidgetItemLayout(); itemLayoutDetails.cardViewElevation = 5; itemLayoutDetails.cardViewCornerRadius = 10; itemLayoutDetails.imageHeightToCardHeightRatio = 0.6 itemLayoutDetails.imageWidthToCardWidthRatio = 1; itemLayoutDetails.imageMargin = 5; itemLayoutDetails.itemTitleStyle = Typeface.create("sans-serif-condensed", Typeface.NORMAL); itemLayoutDetails.itemTitleSize = 12; itemLayoutDetails.itemTitleColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.charcoal); itemLayoutDetails.itemTitleGravity = Gravity.LEFT; itemLayoutDetails.setItemTitleMargins(10, 0, 0, 0); itemLayoutDetails.itemPriceStyle = Typeface.create("sans-serif-light", Typeface.BOLD); itemLayoutDetails.itemPriceSize = 12; itemLayoutDetails.itemPriceColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.charcoal); itemLayoutDetails.itemPriceGravity = Gravity.LEFT; itemLayoutDetails.setItemPriceMargins(10, 0, 3, 0); ```
```kotlin val itemLayoutDetails = ContentWidgetItemLayout() itemLayoutDetails.cardViewElevation = 5 itemLayoutDetails.cardViewCornerRadius = 10 itemLayoutDetails.imageHeightToCardHeightRatio = 0.6 itemLayoutDetails.imageWidthToCardWidthRatio = 1 itemLayoutDetails.imageMargin = 5 itemLayoutDetails.itemTitleStyle = Typeface.create("sans-serif-condensed", Typeface.NORMAL) itemLayoutDetails.itemTitleSize = 12 itemLayoutDetails.itemTitleColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.charcoal) itemLayoutDetails.itemTitleGravity = Gravity.LEFT itemLayoutDetails.setItemTitleMargins(10, 0, 0, 0) itemLayoutDetails.itemPriceStyle = Typeface.create("sans-serif-light", Typeface.BOLD) itemLayoutDetails.itemPriceSize = 12 itemLayoutDetails.itemPriceColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.charcoal) itemLayoutDetails.itemPriceGravity = Gravity.LEFT itemLayoutDetails.setItemPriceMargins(10, 0, 3, 0) ```
## Interaction with the widget ### Public interface --- `load()` - Starts fetching data and creates a view structure of the widget. `getView()` - Gets the root view of the whole widget view structure. `onContentWidgetListener` is used to inform developers about the state of a widget. Read more below. ### Listener --- - `onLoading(ContentWidget contentWidget, boolean isLoading)` - Called when the widget loading state changes. - `onLoad(ContentWidget contentWidget)` - Called after the widget is loaded. - `onLoadingError(ContentWidget contentWidget, ApiError apiError)` - Called when an error occurs while loading. - `onSizeChange(ContentWidget contentWidget, ViewGroup.LayoutParams size)` - Called when the widget size changes. - `onClickActionReceive(ContentWidget contentWidget, BaseModel model)` - Called when the customer clicks a widget item. ## Image button custom action `ImageButtonCustomAction` is used to add `imageButton` to your widget. You can add a `singleStateButton` or a `selectableButton`. ### Parameters The following table contains the parameters that can be configured in `ImageButtonCustomAction`. | Parameter | Type | Default | Description | | --- | --- | --- | --- | | predefinedAction | `PredefinedActionType` | null | PredefinedAction determines which event is sent on click | | marginLeft | `Int` | 0 | Left margin of the image button | | marginRight | `Int` | 0 | Right margin of the image button | | marginTop | `Int` | - | Top margin of the image button | | marginBottom | `Int` | 0 | Bottom margin of the image button |
ImageButtonCustomAction margins can be set using setters, as shown below.
```java public void setImageButtonCustomActionMargins(int marginLeft, int marginRight, int marginTop, int marginBottom) ```
```kotlin fun setImageButtonCustomActionMargins(marginLeft:Int, marginRight:Int, marginTop:Int, marginBottom:Int) ```
The following table contains the parameters that can be configured in `ContentWidgetBadge`. | Parameter | Type | Default | Description | | --- | --- | --- | --- | | textStyle | `Typeface` | - | Typeface of the text badge | | textSize | `Int` | 12 | Size of the badge text | | rule | `Int` | RelativeLayout.ALIGN_LEFT | Rule deremining position of a badge. Can be ALIGN_LEFT or ALIGN_RIGHT | | paddingLeft | `Int` | 0 | Left padding of the badge text | | paddingRight | `Int` | 0 | Right padding of the badge text | | paddingTop | `Int` | 0 | Top padding of the badge text | | paddingBottom | `Int` | 0 | Bottom padding of the badge text | | marginLeft | `Int` | 0 | Left margin of the badge | | marginRight | `Int` | 0 | Right margin of the badge | | marginTop | `Int` | - | Top margin of the badge | | marginBottom | `Int` | 0 | Bottom margin of the badge |
ContentWidgetBadge margins and paddings can be set using setters, as shown below.
```java public void setMargins(int marginLeft, int marginRight, int marginTop, int marginBottom) ```
```kotlin fun setMargins(marginLeft:Int, marginRight:Int, marginTop:Int, marginBottom:Int) ```
```java public void setPaddings(int paddingLeft, int paddingRight, int paddingTop, int paddingBottom) ```
```kotlin fun setPaddings(paddingLeft:Int, paddingRight:Int, paddingTop:Int, paddingBottom:Int) ```
### setStateDrawables This method is responsible for passing icons to the image button. **Method name:** imageButtonCustomAction.setStateDrawables(dislikeIcon, likeIcon) #### Declaration
```java public void setStateDrawables(@NonNull Drawable defaultStateDrawable, @Nullable Drawable selectedStateDrawable) ```
```kotlin fun setStateDrawables(@NonNull defaultStateDrawable:Drawable, @Nullable selectedStateDrawable:Drawable) ```
#### Parameters | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | defaultStateDrawable | `Drawable` | yes | --- | Icon that appears in default and false state | | selectedStateDrawable | `Drawable` | no | --- | Icon that appears in the selected state | #### Return Value Void type #### Example
```Java Drawable likeHeart = ContextCompat.getDrawable(this, R.drawable.ic_heart); Drawable unlikeHeart = ContextCompat.getDrawable(this, R.drawable.ic_heart_outline); favouriteIcon.setStateDrawables(unlikeHeart, likeHeart); ```
```Kotlin val likeHeart = ContextCompat.getDrawable(this, R.drawable.ic_heart) val unlikeHeart = ContextCompat.getDrawable(this, R.drawable.ic_heart_outline) favouriteIcon.setStateDrawables(unlikeHeart, likeHeart) ```
If you want a `singleStateButton`, pass `null` instead of `selectedStateDrawable`.
### Public interface Set a listener by using `setOnItemActionListener`. `OnActionItemStateListener` is used to inform developers about the state of an ImageButton. ### Listener - `onReceiveClickAction(BaseModel model, boolean isSelected, ImageButton imageButton)` - called when the customer clicks the image button in the widget. - `onStateCheck(BaseModel model)` - called before showing the view, when `selectableImageButton` needs information about the button state. ### Example The example shows how to implement the "like" button.
```java ImageButtonCustomAction favouriteIcon = new ImageButtonCustomAction(); Drawable likeHeart = ContextCompat.getDrawable(this, R.drawable.ic_heart); Drawable unlikeHeart = ContextCompat.getDrawable(this, R.drawable.ic_heart_outline); favouriteIcon.setStateDrawables(unlikeHeart, likeHeart); favouriteIcon.setImageButtonCustomActionMargins(0, 0, 0, 0); favouriteIcon.predefinedAction = PredefinedActionType.SEND_LIKE_EVENT; favouriteIcon.setOnItemActionListener(new OnActionItemStateListener() { @Override public void onReceiveClickAction(BaseModel model, boolean isSelected, ImageButton imageButton) { Recommendation recommendation = (Recommendation) model; ViewUtils.pulse(imageButton); } @Override public boolean onStateCheck(BaseModel model) { return false; } }); itemLayoutDetails.setItemAction(favouriteIcon); ```
```kotlin val favouriteIcon = ImageButtonCustomAction() val likeHeart = ContextCompat.getDrawable(this, R.drawable.ic_heart) val unlikeHeart = ContextCompat.getDrawable(this, R.drawable.ic_heart_outline) favouriteIcon.setStateDrawables(unlikeHeart!!, likeHeart) favouriteIcon.setImageButtonCustomActionMargins(0, 0, 0, 0) favouriteIcon.predefinedAction = PredefinedActionType.SEND_LIKE_EVENT favouriteIcon.setOnItemActionListener(object : OnActionItemStateListener { override fun onReceiveClickAction(model: BaseModel, isSelected: Boolean, imageButton: ImageButton) { val recommendation = model as Recommendation ViewUtils.pulse(imageButton) } override fun onStateCheck(model: BaseModel): Boolean { return false } }) itemLayoutDetails.setItemAction(favouriteIcon) ```
## Sample implementations ### Horizontal slider Slider layout with a fixed height.
```java public void loadWidget() { String productId = "10214"; String slug = "similar"; ContentWidgetOptions options = new ContentWidgetRecommendationsOptions(this, slug, new OnRecommendationModelMapper() { @Override public ContentWidgetRecommendationDataModel onRecommendationMapping(Recommendation recommendation) { HashMap data = recommendation.getFeed(); String imageLink = (String) data.get("imageLink"); String productName = (String) data.get("title"); String price = null; String salePrice = null; try { JSONObject json = new JSONObject(data.get("price").toString()); price = json.getString("value"); if (data.containsKey("salePrice")) { JSONObject jsonSalePrice = new JSONObject(data.get("salePrice").toString()); salePrice = jsonSalePrice.getString("value"); } } catch (JSONException e) { e.printStackTrace(); } ContentWidgetBadgeDataModel badgeDataModel = new ContentWidgetBadgeDataModel("Example badge", Color.BLACK, Color.RED); ContentWidgetRecommendationDataModel dataModel = new ContentWidgetRecommendationDataModel(productName, imageLink, price, salePrice, "PLN"); dataModel.setBadgeDataModel(badgeDataModel); dataModel.setLabel("Black Week"); return dataModel; }}); options.attributes.put(ContentWidgetOptions.ContentWidgetOptionsAttributeKeyProductId, productId); ContentWidgetBasicProductItemLayout itemLayoutDetails = new ContentWidgetBasicProductItemLayout(); ContentWidgetHorizontalSliderLayout layout = new ContentWidgetHorizontalSliderLayout(); //CardView parameters if (!cardViewWidth.getEditText().getText().toString().matches("") && !cardViewHeight.getEditText().getText().toString().matches("")) layout.setCardViewSize(Integer.parseInt(cardViewWidth.getEditText().getText().toString()), Integer.parseInt(cardViewHeight.getEditText().getText().toString())); if (!cardViewElevation.getEditText().getText().toString().matches("")) itemLayoutDetails.cardViewElevation = Integer.parseInt(cardViewElevation.getEditText().getText().toString()); if (!cornerRadius.getEditText().getText().toString().matches("")) itemLayoutDetails.cardViewCornerRadius = Integer.parseInt(cornerRadius.getEditText().getText().toString()); if (!horizontalSpacing.getEditText().getText().toString().matches("")) layout.cardViewHorizontalSpacing = Integer.parseInt(horizontalSpacing.getEditText().getText().toString()); layout.cardViewBackgroundColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.regent); //Image size as ratio to cardview size if (!imageHeightRatio.getEditText().getText().toString().matches("")) itemLayoutDetails.imageHeightToCardHeightRatio = Float.parseFloat(imageHeightRatio.getEditText().getText().toString()); if (!imageWidthRatio.getEditText().getText().toString().matches("")) itemLayoutDetails.imageWidthToCardWidthRatio = Float.parseFloat(imageWidthRatio.getEditText().getText().toString()); itemLayoutDetails.imageScaleType = ImageView.ScaleType.CENTER_CROP; itemLayoutDetails.imageMargin = 0; //have to be set when you set cardViewElevation //TextView product label itemLayoutDetails.itemLabelSize = 12; itemLayoutDetails.itemLabelColor = Color.GREEN; itemLayoutDetails.setItemLabelMargins(0,0,2,0); //TextView product name itemLayoutDetails.itemTitleStyle = Typeface.create("sans-serif-condensed", Typeface.NORMAL); itemLayoutDetails.itemTitleSize = 12; itemLayoutDetails.itemTitleColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.charcoal); itemLayoutDetails.setItemTitleMargins(10, 0, 0, 0); //TextView Product price itemLayoutDetails.itemPriceStyle = Typeface.create("sans-serif-light", Typeface.BOLD); itemLayoutDetails.itemPriceSize = 13; itemLayoutDetails.itemPriceColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.charcoal); itemLayoutDetails.setItemPriceMargins(10, 0, 3, 0); //TextView Product Sale price itemLayoutDetails.isItemSalePriceVisible = true; itemLayoutDetails.itemSalePriceStyle = Typeface.create("sans-serif", Typeface.BOLD); itemLayoutDetails.itemSalePriceSize = 13; itemLayoutDetails.itemSalePriceColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.red); itemLayoutDetails.itemSalePriceOrientation = LinearLayout.HORIZONTAL; itemLayoutDetails.setItemSalePriceMargins(4, 0, 3, 0); // CrossedOut Price color itemLayoutDetails.itemRegularPriceColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.com_facebook_blue); itemLayoutDetails.priceDecimalSeparator = ','; itemLayoutDetails.priceGroupSeparator = ' '; // DiscountLabel itemLayoutDetails.itemDiscountPercentageLabelSize = 13; itemLayoutDetails.isItemDiscountPercentageLabelVisible = true; itemLayoutDetails.itemDiscountPercentageLabelColor = Color.BLUE; itemLayoutDetails.itemDiscountPercentageLabelStyle = Typeface.create("sans-serif", Typeface.BOLD); itemLayoutDetails.setItemDiscountLabelMargins(4, 0, 3, 0); // Badge ContentWidgetBadge badge = new ContentWidgetBadge(); badge.textSize = 12; badge.rule = RelativeLayout.ALIGN_LEFT; // left or right badge.setMargins(0,0,0,20); badge.setPaddings(10, 10, 0, 0); //ImageButton ImageButtonCustomAction favouriteIcon = new ImageButtonCustomAction(); Drawable likeHeart = ContextCompat.getDrawable(this, R.drawable.ic_heart); Drawable unlikeHeart = ContextCompat.getDrawable(this, R.drawable.ic_heart_outline); favouriteIcon.setStateDrawables(unlikeHeart, likeHeart); favouriteIcon.setImageButtonCustomActionMargins(0, 0, 0, 0); favouriteIcon.predefinedAction = PredefinedActionType.SEND_LIKE_EVENT; favouriteIcon.setOnItemActionListener(new OnActionItemStateListener() { @Override public void onReceiveClickAction(BaseModel model, boolean isSelected, ImageButton imageButton) { Recommendation recommendationModel = (Recommendation) model; ViewUtils.pulse(imageButton); } @Override public boolean onStateCheck(BaseModel model) { return false; } }); itemLayoutDetails.setBadge(badge); itemLayoutDetails.setItemAction(favouriteIcon); ContentWidgetAppearance contentWidgetAppearance = new ContentWidgetAppearance(layout, itemLayoutDetails); ContentWidget widget = new ContentWidget(options, contentWidgetAppearance); widget.setOnContentWidgetListener(new OnContentWidgetListener() { @Override public void onLoading(ContentWidget contentWidget, boolean isLoading) { } @Override public void onLoadingError(ContentWidget contentWidget, ApiError apiError) { Toast.makeText(getApplicationContext(), apiError.toString(),Toast.LENGTH_LONG).show(); } @Override public void onLoad(ContentWidget contentWidget) { insertPoint.removeAllViews(); View view = widget.getView(); // our widget insertPoint.addView(view); // your view which will receive widget } @Override public void onClickActionReceive(ContentWidget contentWidget, BaseModel model) { Recommendation recommendationModel = (Recommendation) model; String itemId = recommendationModel.getItemId(); startActivity(WidgetRecommendedProductDetailsActivity.createIntent(getApplicationContext(), itemId)); } @Override public void onSizeChange(ContentWidget contentWidget, ViewGroup.LayoutParams size) { ViewGroup.LayoutParams params = insertPoint.getLayoutParams(); params.height = size.height; insertPoint.setLayoutParams(params); } }); } ```
```kotlin fun loadWidget() { val productId = "10214" val slug = "similar" var options: ContentWidgetOptions = ContentWidgetRecommendationsOptions(this, slug, object : OnRecommendationModelMapper() { fun onRecommendationMapping(recommendation: Recommendation): ContentWidgetRecommendationDataModel? { // here you should implement your mapping to SyneriseModel val data = recommendation.getFeed() val imageLink = data["imageLink"] as String? val productName = data["title"] as String? var price: String? = null var salePrice: String? = null try { val json = JSONObject(data["price"].toString()) price = json.getString("value") if (data.containsKey("salePrice")) { val jsonSalePrice = JSONObject(data["salePrice"].toString()) salePrice = jsonSalePrice.getString("value") } } catch (e: JSONException) { e.printStackTrace() } val badgeDataModel = ContentWidgetBadgeDataModel("Example badge", Color.BLACK, Color.RED) val dataModel = ContentWidgetRecommendationDataModel(productName, imageLink, price, salePrice, "PLN") dataModel.setBadgeDataModel(badgeDataModel); dataModel.setLabel("Black Week"); return dataModel } }) options.attributes.put(ContentWidgetOptions.ContentWidgetOptionsAttributeKeyProductId, productId); val itemLayoutDetails = ContentWidgetItemLayout() val layout = ContentWidgetHorizontalSliderLayout() layout.setCardViewSize(250, 350) itemLayoutDetails.cardViewElevation = 5 itemLayoutDetails.cardViewCornerRadius = 10 layout.cardViewHorizontalSpacing = 20 layout.cardViewBackgroundColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.regent) //Image size as ratio to cardview size itemLayoutDetails.imageHeightToCardHeightRatio = 0.6 itemLayoutDetails.imageWidthToCardWidthRatio = 1 itemLayoutDetails.imageMargin = 5 //have to be set when you set cardViewElevation itemLayoutDetails.imageScaleType = ImageView.ScaleType.CENTER_CROP; //TextView product label itemLayoutDetails.itemLabelSize = 12; itemLayoutDetails.itemLabelColor = Color.GREEN; itemLayoutDetails.setItemLabelMargins(0,0,2,0); //TextView product name itemLayoutDetails.itemTitleStyle = Typeface.create("sans-serif-condensed", Typeface.NORMAL) itemLayoutDetails.itemTitleSize = 12 itemLayoutDetails.itemTitleColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.charcoal) itemLayoutDetails.itemTitleGravity = Gravity.LEFT itemLayoutDetails.setItemTitleMargins(10, 0, 0, 0) //TextView Product price itemLayoutDetails.itemPriceStyle = Typeface.create("sans-serif-light", Typeface.BOLD) itemLayoutDetails.itemPriceSize = 12 itemLayoutDetails.itemPriceColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.charcoal) itemLayoutDetails.itemPriceGravity = Gravity.LEFT itemLayoutDetails.setItemPriceMargins(10, 0, 3, 0) //TextView Product Sale Price itemLayoutDetails.itemSalePriceStyle = Typeface.create("sans-serif", Typeface.BOLD) itemLayoutDetails.itemSalePriceSize = 13 itemLayoutDetails.itemSalePriceColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.red) itemLayoutDetails.itemSalePriceOrientation = LinearLayout.HORIZONTAL itemLayoutDetails.isItemSalePriceVisible = true itemLayoutDetails.setItemSalePriceMargins(5, 0, 3, 0) // CrossedOut Price color itemLayoutDetails.itemRegularPriceColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.com_facebook_blue); itemLayoutDetails.priceDecimalSeparator = ','; itemLayoutDetails.priceGroupSeparator = ' '; // DiscountLabel itemLayoutDetails.itemDiscountPercentageLabelSize = 13; itemLayoutDetails.isItemDiscountPercentageLabelVisible = true; itemLayoutDetails.itemDiscountPercentageLabelColor = Color.BLUE; itemLayoutDetails.itemDiscountPercentageLabelStyle = Typeface.create("sans-serif", Typeface.BOLD); itemLayoutDetails.setItemDiscountLabelMargins(4, 0, 3, 0); // Badge val badge = ContentWidgetBadge(); badge.textSize = 12; badge.rule = RelativeLayout.ALIGN_LEFT; // left or right badge.setMargins(0,0,0,20); badge.setPaddings(10, 10, 0, 0); //ImageButton val favouriteIcon = ImageButtonCustomAction() val likeHeart = ContextCompat.getDrawable(this, R.drawable.ic_heart) val unlikeHeart = ContextCompat.getDrawable(this, R.drawable.ic_heart_outline) favouriteIcon.setStateDrawables(unlikeHeart, likeHeart) favouriteIcon.setImageButtonCustomActionMargins(0, 0, 0, 0) favouriteIcon.predefinedAction = PredefinedActionType.SEND_LIKE_EVENT favouriteIcon.setOnItemActionListener(object:OnActionItemStateListener() { fun onReceiveClickAction(model:BaseModel, isSelected:Boolean, imageButton:ImageButton) { val recommendation = model as Recommendation ViewUtils.pulse(imageButton) } fun onStateCheck(model:BaseModel):Boolean { // Here you should set buttonState based on a product and a customer. return false } }) itemLayoutDetails.setBadge(badge); itemLayoutDetails.setItemAction(favouriteIcon) val contentWidgetAppearance = ContentWidgetAppearance(layout, itemLayoutDetails) val widget = ContentWidget(options, contentWidgetAppearance) widget.setOnContentWidgetListener(object:OnContentWidgetListener() { fun onLoading(contentWidget:ContentWidget, isLoading:Boolean) { } fun onLoadingError(contentWidget:ContentWidget, apiError:ApiError) { Toast.makeText(getApplicationContext(), apiError.toString(), Toast.LENGTH_LONG).show() } fun onLoad(contentWidget:ContentWidget) { insertPoint.removeAllViews() val view = widget.getView() // our widget insertPoint.addView(view) // your view which will receive widget } fun onClickActionReceive(contentWidget:ContentWidget, model:BaseModel) { val recommendation = model as Recommendation startActivity(WidgetRecommendedProductDetailsActivity.createIntent(getApplicationContext(), recommendation.getProductRetailerPartNo())) } fun onSizeChange(contentWidget:ContentWidget, size:ViewGroup.LayoutParams) { val params = insertPoint.getLayoutParams() params.height = size.height insertPoint.setLayoutParams(params) } }) } ```
### Grid view --- If you want to avoid double scroll view, set the height as shown in the `widgetSizeDidChange` callback.
```java private void loadFullScreenWidget() { String slug = "similar"; String productId = "10214"; ContentWidgetOptions options = new ContentWidgetRecommendationsOptions(this, slug, new OnRecommendationModelMapper() { @Override public ContentWidgetRecommendationDataModel onRecommendationMapping(Recommendation recommendation) { HashMap data = recommendation.getFeed(); String imageLink = (String) data.get("imageLink"); String productName = (String) data.get("title"); String price = null; String salePrice = null; try { JSONObject json = new JSONObject(data.get("price").toString()); price = json.getString("value"); if (data.containsKey("salePrice")) { JSONObject jsonSalePrice = new JSONObject(data.get("salePrice").toString()); salePrice = jsonSalePrice.getString("value"); } } catch (JSONException e) { e.printStackTrace(); } return new ContentWidgetRecommendationDataModel(productName, imageLink, price, salePrice, null); }}); options.attributes.put(ContentWidgetOptions.ContentWidgetOptionsAttributeKeyProductId, productId); ContentWidgetItemLayout itemLayoutDetails = new ContentWidgetItemLayout(); DisplayMetrics displayMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); float screenWidthDp = displayMetrics.widthPixels; ContentWidgetGridLayout layout = new ContentWidgetGridLayout(screenWidthDp); //CardView parameters layout.setCardViewSize(250, 350); itemLayoutDetails.cardViewElevation = 5; itemLayoutDetails.cardViewCornerRadius = 5; layout.cardViewHorizontalSpacing = 10; layout.cardViewVerticalSpacing = 10; layout.includeEdgeSpacing = false; layout.cardViewBackgroundColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.regent); //Image size as ratio to cardview size itemLayoutDetails.imageHeightToCardHeightRatio = 0.7; itemLayoutDetails.imageWidthToCardWidthRatio = 1; itemLayoutDetails.imageMargin = 5; //have to be set when you set cardViewElevation //TextView product name itemLayoutDetails.itemTitleStyle = Typeface.create("sans-serif-condensed", Typeface.NORMAL); itemLayoutDetails.itemTitleSize = 12; itemLayoutDetails.itemTitleColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.charcoal); itemLayoutDetails.itemTitleGravity = Gravity.LEFT; itemLayoutDetails.setItemTitleMargins(10, 0, 10, 0); //TextView Product price itemLayoutDetails.itemPriceStyle = Typeface.create("sans-serif-light", Typeface.BOLD); itemLayoutDetails.itemPriceSize = 12; itemLayoutDetails.itemPriceColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.charcoal); itemLayoutDetails.itemPriceGravity = Gravity.LEFT; itemLayoutDetails.setItemPriceMargins(10, 0, 10, 0); //TextView Product Sale Price itemLayoutDetails.itemSalePriceStyle = Typeface.create("sans-serif", Typeface.BOLD) itemLayoutDetails.itemSalePriceSize = 13 itemLayoutDetails.itemSalePriceColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.red) itemLayoutDetails.itemSalePriceOrientation = LinearLayout.HORIZONTAL itemLayoutDetails.isItemSalePriceVisible = true itemLayoutDetails.setItemSalePriceMargins(5, 0, 3, 0) //ImageButton val favouriteIcon = ImageButtonCustomAction() val likeHeart = ContextCompat.getDrawable(this, R.drawable.ic_heart) val unlikeHeart = ContextCompat.getDrawable(this, R.drawable.ic_heart_outline) favouriteIcon.setStateDrawables(unlikeHeart, likeHeart) favouriteIcon.setImageButtonCustomActionMargins(0, 0, 0, 0) favouriteIcon.predefinedAction = PredefinedActionType.SEND_LIKE_EVENT favouriteIcon.setOnItemActionListener(object:OnActionItemStateListener() { fun onReceiveClickAction(model:BaseModel, isSelected:Boolean, imageButton:ImageButton) { val recommendation = model as Recommendation ViewUtils.pulse(imageButton) } fun onStateCheck(model:BaseModel):Boolean { // Here you should set buttonState based on a product and a customer. return false } }) itemLayoutDetails.setItemAction(favouriteIcon) ContentWidgetAppearance contentWidgetAppearance = new ContentWidgetAppearance(layout, itemLayoutDetails); ContentWidget widget = new ContentWidget(options, contentWidgetAppearance); widget.setOnContentWidgetListener(new OnContentWidgetListener() { @Override public void onLoading(ContentWidget contentWidget, boolean isLoading) { } @Override public void onLoadingError(ContentWidget contentWidget, ApiError apiError) { Toast.makeText(getApplicationContext(), apiError.toString(),Toast.LENGTH_LONG).show(); } @Override public void onLoad(ContentWidget contentWidget) { insertPoint.removeAllViews(); View view = widget.getView(); insertPoint.addView(view); } @Override public void onClickActionReceive(ContentWidget contentWidget, BaseModel model) { Recommendation recommendation = (Recommendation)model; startActivity(WidgetRecommendedProductDetailsActivity.createIntent(getApplicationContext(), recommendation.getProductRetailerPartNo())); } @Override public void onSizeChange(ContentWidget contentWidget, ViewGroup.LayoutParams size) { ViewGroup.LayoutParams params = insertPoint.getLayoutParams(); params.height = size.height; insertPoint.setLayoutParams(params); } }); } ```
```kotlin private fun loadFullScreenWidget() { val slug = "similar" val productId = "10214" var options: ContentWidgetOptions = ContentWidgetRecommendationsOptions(this, slug, object : OnRecommendationModelMapper() { fun onRecommendationMapping(recommendation: Recommendation): ContentWidgetRecommendationDataModel? { // here you should implement your mapping to SyneriseModel val data = recommendation.getFeed() val imageLink = data["imageLink"] as String? val productName = data["title"] as String? var price: String? = null var salePrice: String? = null try { val json = JSONObject(data["price"].toString()) price = json.getString("value") if (data.containsKey("salePrice")) { val jsonSalePrice = JSONObject(data["salePrice"].toString()) salePrice = jsonSalePrice.getString("value") } } catch (e: JSONException) { e.printStackTrace() } return ContentWidgetRecommendationDataModel(productName, imageLink, price, salePrice, null) } }) options.attributes.put(ContentWidgetOptions.ContentWidgetOptionsAttributeKeyProductId, productId); val itemLayoutDetails = ContentWidgetItemLayout() val displayMetrics = DisplayMetrics() getWindowManager().getDefaultDisplay().getMetrics(displayMetrics) val screenWidthDp = displayMetrics.widthPixels val layout = ContentWidgetGridLayout(screenWidthDp) //CardView parameters layout.setCardViewSize(250, 350) itemLayoutDetails.cardViewElevation = 5 itemLayoutDetails.cardViewCornerRadius = 5 layout.cardViewHorizontalSpacing = 10 layout.cardViewVerticalSpacing = 10 layout.includeEdgeSpacing = false layout.cardViewBackgroundColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.regent) //Image size as ratio to cardview size itemLayoutDetails.imageHeightToCardHeightRatio = 0.7 itemLayoutDetails.imageWidthToCardWidthRatio = 1 itemLayoutDetails.imageMargin = 5 //have to be set when you set cardViewElevation //TextView product name itemLayoutDetails.itemTitleStyle = Typeface.create("sans-serif-condensed", Typeface.NORMAL) itemLayoutDetails.itemTitleSize = 12 itemLayoutDetails.itemTitleColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.charcoal) itemLayoutDetails.itemTitleGravity = Gravity.LEFT itemLayoutDetails.setItemTitleMargins(10, 0, 10, 0) //TextView Product price itemLayoutDetails.itemPriceStyle = Typeface.create("sans-serif-light", Typeface.BOLD) itemLayoutDetails.itemPriceSize = 12 itemLayoutDetails.itemPriceColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.charcoal) itemLayoutDetails.itemPriceGravity = Gravity.LEFT itemLayoutDetails.setItemPriceMargins(10, 0, 10, 0) //TextView Product Sale Price itemLayoutDetails.itemSalePriceStyle = Typeface.create("sans-serif", Typeface.BOLD) itemLayoutDetails.itemSalePriceSize = 13 itemLayoutDetails.itemSalePriceColor = ContextCompat.getColor(Synerise.getApplicationContext(), R.color.red) itemLayoutDetails.itemSalePriceOrientation = LinearLayout.HORIZONTAL itemLayoutDetails.isItemSalePriceVisible = true itemLayoutDetails.setItemSalePriceMargins(5, 0, 3, 0) //ImageButton val favouriteIcon = ImageButtonCustomAction() val likeHeart = ContextCompat.getDrawable(this, R.drawable.ic_heart) val unlikeHeart = ContextCompat.getDrawable(this, R.drawable.ic_heart_outline) favouriteIcon.setStateDrawables(unlikeHeart, likeHeart) favouriteIcon.setImageButtonCustomActionMargins(0, 0, 0, 0) favouriteIcon.predefinedAction = PredefinedActionType.SEND_LIKE_EVENT favouriteIcon.setOnItemActionListener(object:OnActionItemStateListener() { fun onReceiveClickAction(model:BaseModel, isSelected:Boolean, imageButton:ImageButton) { val recommendation = model as Recommendation ViewUtils.pulse(imageButton) } fun onStateCheck(model:BaseModel):Boolean { // Here you should set buttonState based on a product and a customer. return false } }) itemLayoutDetails.setItemAction(favouriteIcon) val contentWidgetAppearance = ContentWidgetAppearance(layout, itemLayoutDetails) val widget = ContentWidget(options, contentWidgetAppearance) widget.setOnContentWidgetListener(object:OnContentWidgetListener() { fun onLoading(contentWidget:ContentWidget, isLoading:Boolean) { } fun onLoadingError(contentWidget:ContentWidget, apiError:ApiError) { Toast.makeText(getApplicationContext(), apiError.toString(), Toast.LENGTH_LONG).show() } fun onLoad(contentWidget:ContentWidget) { insertPoint.removeAllViews() val view = widget.getView() insertPoint.addView(view) } fun onClickActionReceive(contentWidget:ContentWidget, model:BaseModel) { val recommendation = model as Recommendation startActivity(WidgetRecommendedProductDetailsActivity.createIntent(getApplicationContext(), recommendation.getProductRetailerPartNo())) } fun onSizeChange(contentWidget:ContentWidget, size:ViewGroup.LayoutParams) { val params = insertPoint.getLayoutParams() params.height = size.height insertPoint.setLayoutParams(params) } }) } ```
### More information --- You can find more information under the following links: - [Sample App on GitHub](https://github.com/Synerise/android-sdk) - [Horizontal slider implementation in the Sample App on GitHub](https://github.com/Synerise/android-sdk/blob/master/sample/src/main/java/com/synerise/sdk/sample/ui/dev/content/WidgetHorizontalSliderActivity.java) - [Grid implementation in the Sample App on GitHub](https://github.com/Synerise/android-sdk/blob/master/sample/src/main/java/com/synerise/sdk/sample/ui/dev/content/WidgetGridViewActivity.java) ``` # SDK lifecycle ## Change Profile API Key dynamically --- This method changes a Profile (formerly Client) API key dynamically. **Method name:** Client.changeApiKey(newApiKey) **Declaration:**
```java public static void changeApiKey(@NonNull String newApiKey) ```
```kotlin fun changeApiKey(@NonNull newApiKey:String) ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **newApiKey** | String | yes | - | New API Key | **Return Value:** Void type method. **Example:**
```java Client.changeApiKey(apiKey); ```
```kotlin Client.changeApiKey(apiKey); ```
## Change Profile API Key dynamically with config --- This method changes a Profile (formerly Client) API key dynamically, with additional parameters. It can include a salt for [Simple Profile Authentication](/developers/mobile-sdk/user-identification-and-authorization/simple-authentication) requests. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.19.0 | 5.20.0 | 0.23.0 | 1.3.0 | **Method name:** Client.changeApiKey(apiKey, initializationConfig) **Declaration:**
```java public static void changeApiKey(String apiKey, InitializationConfig initializationConfig) ```
```kotlin fun changeApiKey(@NonNull apiKey:String, @Nullable initializationConfig:InitializationConfig) ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **apiKey** | String | yes | - | New API Key | | **initializationConfig** | [InitializationConfig](/developers/mobile-sdk/class-reference/android/lifecycle#initializationconfig) | no | - | Object for additional initialization settings after the API key change | **Return Value:** Void type method. **Example:**
```java Client.changeApiKey(apiKey, initializationConfig); ```
```kotlin Client.changeApiKey(apiKey, initializationConfig); ```
# Modules ### Synerise **Declared In:** Headers/SNRSynerise.h **Inherits From:** [NSObject](https://developer.apple.com/documentation/objectivec/nsobject) **Declaration:**
```Swift class Synerise: NSObject ```
```Objective-C @interface SNRSynerise : NSObject ```
**Properties:** | Property | Type | Description | | --- | --- | --- | | **settings** | [Settings](/developers/mobile-sdk/class-reference/ios/lifecycle#settings) | Settings module to configure the SDK |
The `settings` property is statically accessible.
**Methods:** This method sets an object for Synerise delegate methods.
```Swift static func setDelegate(_: SyneriseDelegate) ```
```Objective-C + (void)setDelegate:(nonnull id)delegate ```
[(Click for more details)](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#synerise-delegate) --- This method sets an object for notification delegate methods.
```Swift static func setNotificationDelegate(_: NotificationDelegate) ```
```Objective-C + (void)setNotificationDelegate:(id)delegate ```
[(Click for more details)](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#notification-delegate) --- This method initializes Synerise.
```Swift static func initialize(apiKey:) ```
```Objective-C + (void)initializeWithApiKey:(nonnull NSString *)apiKey ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/lifecycle#initialization) --- This method initializes Synerise SDK with custom environment settings.
```Swift static func initialize(apiKey:baseUrl:) ```
```Objective-C + (void)initializeWithApiKey:(nonnull NSString *)apiKey andBaseUrl:(nullable NSString *)baseUrl ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/lifecycle#initialize-with-custom-environment) --- This method sets the salt string for request validation.
```Swift static func setRequestValidationSalt(_: String?) ```
```Objective-C + (void)setRequestValidationSalt:(nullable NSString *)string ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/lifecycle#set-request-validation-salt) --- This method changes a Profile (formerly Client) API key dynamically.
```Swift static func changeApiKey(apiKey: String) ```
```Objective-C + (void)changeApiKey:(NSString *)apiKey ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/lifecycle#change-profile-api-key-dynamically) --- This method changes a Profile (formerly Client) API key dynamically, with additional parameters.
```Swift static func changeApiKey(_ apiKey: String, config: InitializationConfig?) -> Void ```
```Objective-C (void)changeApiKey:(NSString *)apiKey config:(nullable SNRInitializationConfig *)config; ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/lifecycle#change-profile-api-key-dynamically-with-config) --- This method sets the Synerise SDK host application type.
```Swift static func setHostApplicationType(_: HostApplicationType) ```
```Objective-C + (void)setHostApplicationType:(SNRHostApplicationType)type ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/lifecycle#set-up-host-application-type) --- This method sets the Synerise SDK plugin version.
```Swift static func setHostApplicationSDKPluginVersion(_: String) ```
```Objective-C + (void)setHostApplicationSDKPluginVersion:(NSString *)type ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/lifecycle#set-host-application-sdk-plugin-version) --- This method enables or disables console logs from Synerise SDK.
```Swift static func setDebugModeEnabled(_: Bool) ```
```Objective-C + (void)setDebugModeEnabled:(BOOL)enabled ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/lifecycle#enable-debug-mode) --- This method enables or disables crash handling by Synerise SDK.
```Swift static func setCrashHandlingEnabled(_: Bool) ```
```Objective-C + (void)setCrashHandlingEnabled:(BOOL)enabled ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/lifecycle#enable-crash-handling) --- This method sets the notification categories (including Synerise categories) that your app supports.
```Swift static func setNotificationCategories(_: Set) ```
```Objective-C + (void)setNotificationCategories:(NSSet *)notificationCategories ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/campaigns#set-notification-categories) --- This method sets identifiers for Background Tasks processing.
```Swift static func setBackgroundTaskIdentifiers(_: [String]) ```
```Objective-C + (void)setBackgroundTaskIdentifiers:(NSArray *)identifiers ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/campaigns#set-notification-categories) --- This method verifies if a notification was sent by Synerise.
```Swift static func isSyneriseNotification(_: [AnyHashable: Any]) -> Bool ```
```Objective-C + (BOOL)isSyneriseNotification:(nonnull NSDictionary *)userInfo ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/campaigns#check-if-push-notification-is-from-synerise) --- This method verifies if a notification’s sender is Synerise and if the notification is a Simple Push campaign
```Swift static func isSyneriseSimplePush(_: [AnyHashable: Any]) -> Bool ```
```Objective-C + (BOOL)isSyneriseSimplePush:(nonnull NSDictionary *)userInfo ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/campaigns#check-if-push-notification-is-a-simple-push-campaign) --- This method verifies if a notification’s sender is Synerise and if the notification is a Banner campaign.
```Swift static func isSyneriseBanner(_: [AnyHashable: Any]) -> Bool ```
```Objective-C + (BOOL)isSyneriseBanner:(nonnull NSDictionary *)userInfo ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/campaigns#check-if-push-notification-is-a-banner-campaign) **REMOVED in version 5.0.0** --- This method verifies if a notification's sender is Synerise and if the notification is a Silent Command.
```Swift static func isSyneriseSilentCommand(_: [AnyHashable: Any]) -> Bool ```
```Objective-C + (BOOL)isSyneriseSilentCommand:(nonnull NSDictionary *)userInfo ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/campaigns#check-if-push-notification-is-a-silent-command) --- This method verifies if a notification's sender is Synerise and if the notification is a Silent SDK Command.
```Swift static func isSyneriseSilentSDKCommand(_: [AnyHashable: Any]) -> Bool ```
```Objective-C + (BOOL)isSyneriseSilentSDKCommand:(nonnull NSDictionary *)userInfo ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/campaigns#check-if-push-notification-is-a-silent-sdk-command) --- This method verifies if a notification is encrypted.
```Swift static func isNotificationEncrypted(_: [AnyHashable: Any]) -> Bool ```
```Objective-C + (BOOL)isNotificationEncrypted:(nonnull NSDictionary *)userInfo ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/campaigns#check-if-push-notification-is-encrypted) --- This method decrypts the notification payload.
```Swift static func decryptNotification(_: [AnyHashable: Any]) -> [AnyHashable: Any]? ```
```Objective-C + (nullable NSDictionary *)decryptNotification:(nonnull NSDictionary *)userInfo ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/campaigns#decrypt-push-notification) --- This method handles a notification payload and starts activity.
```Swift static func handleNotification(_: [AnyHashable: Any]) ```
```Objective-C + (void)handleNotification:(nonnull NSDictionary *)userInfo ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/campaigns#handle-synerise-push-notification) --- This method handles a notification payload with a user interaction and starts activity.
```Swift static func handleNotification(_: [AnyHashable: Any], actionIdentifier: String) ```
```Objective-C + (void)handleNotification:(nonnull NSDictionary *)userInfo actionIdentifier:(nullable NSString *)actionIdentifier ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/campaigns#handle-synerise-push-notification-with-action) ---
- Synerise Domain is declared as a global string constant - `SNRSyneriseDomain` - Synerise Bundle Identifier is declared as a global string constant - `SNRSyneriseBundleIdentifier`
--- --- ### Client The module for managing customer account data, registration, authentication, and authorization. **Declared In:** Headers/SNRClient.h **Related To:** [ClientStateDelegate](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#client-state-delegate) [ClientRegisterAccountContext](/developers/mobile-sdk/class-reference/ios/client#clientregisteraccountcontext) [ClientConditionalAuthResult](/developers/mobile-sdk/class-reference/ios/client#clientconditionalauthresult) [ClientConditionalAuthenticationContext](/developers/mobile-sdk/class-reference/ios/client#clientconditionalauthenticationcontext) [ClientAuthenticationContext](/developers/mobile-sdk/class-reference/ios/client#clientauthenticationcontext) [ClientOAuthAuthenticationContext](/developers/mobile-sdk/class-reference/ios/client#clientoauthauthenticationcontext) [ClientFacebookAuthenticationContext](/developers/mobile-sdk/class-reference/ios/client#clientfacebookauthenticationcontext) [ClientAppleSignInAuthenticationContext](/developers/mobile-sdk/class-reference/ios/client#clientapplesigninauthenticationcontext) [ClientAccountInformation](/developers/mobile-sdk/class-reference/ios/client#clientaccountinformation) [ClientUpdateAccountContext](/developers/mobile-sdk/class-reference/ios/client#clientupdateaccountcontext) [ClientUpdateAccountBasicInformationContext](/developers/mobile-sdk/class-reference/ios/client#clientupdateaccountbasicinformationcontext) [ClientPasswordResetRequestContext](/developers/mobile-sdk/class-reference/ios/client#clientpasswordresetrequestcontext) [ClientPasswordResetConfirmationContext](/developers/mobile-sdk/class-reference/ios/client#clientpasswordresetconfirmationcontext) [Token](/developers/mobile-sdk/class-reference/ios/client#token) **Inherits From:** [NSObject](https://developer.apple.com/documentation/objectivec/nsobject) **Declaration:**
```Swift class Client: NSObject ```
```Objective-C @interface SNRTracker : NSObject ```
**Methods:** This method sets an object for a customers's state delegate methods.
```Swift static func setClientStateDelegate(_: ClientStateDelegate) ```
```Objective-C + (void)setClientStateDelegate:(nonnull id)delegate ```
[(Click for more details)](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#client-state-delegate) --- This method registers a new customer with an email, password, and optional data.
```Swift static func registerAccount(context: ClientRegisterAccountContext, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)registerAccount:(nonnull SNRClientRegisterAccountContext *)context success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-authentication#register-customer-account) --- This method confirms a customer account with the confirmation token.
```Swift static func confirmAccountActivation(token: String, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)confirmAccount:(nonnull NSString *)token success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-authentication#confirm-customer-account-activation) --- This method activates a customer with email.
```Swift static func requestAccountActivation(email: String, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)requestAccountActivation:(nonnull NSString *)email success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-authentication#request-customer-account-activation) --- This method requests a customer's account registration process with the PIN code.
```Swift static func requestAccountActivationByPin(email: String, success: ((Bool) -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)requestAccountActivationByPinWithEmail:(nonnull NSString *)email success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(SNRApiError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-authentication#request-customer-account-activation-by-pin) --- This method confirms a customer's account registration process with the PIN code.
```Swift static func confirmAccountActivationByPin(pinCode: String, email: String, success: ((Bool) -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)confirmAccountActivationByPin:(nonnull NSString *)pinCode email:(nonnull NSString *)email success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(SNRApiError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-authentication#confirm-customer-account-activation-by-pin) --- This method signs a customer in to obtain a JSON Web Token (JWT) which can be used in subsequent requests.
```Swift static func signIn(email: String, password: String, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)signInWithEmail:(nonnull NSString *)email password:(nonnull NSString *)password success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-authentication#sign-in-a-customer) --- This method signs a customer in to obtain a JSON Web Token (JWT) which can be used in subsequent requests.
```Swift static func signInConditionally(email: String, password: String, success: ((ClientAuthenticationResult) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)signInConditionallyWithEmail:(nonnull NSString *)email password:(nonnull NSString *)password success:(nonnull void (^)(SNRClientAuthenticationResult *authResult))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-authentication#sign-in-a-customer-conditionally) --- This method authenticates a customer with OAuth, Facebook, Google, Apple, or Synerise.
```Swift static func authenticate(token: AnyObject, clientIdentityProvider: ClientIdentityProvider, authID: String?, context: ClientAuthenticationContext?, success: ((Bool) -> Void), failure: ((ApiError) -> Void)) ```
```Objective-C + (void)authenticateWithToken:(id)token clientIdentityProvider:(SNRClientIdentityProvider)clientIdentityProvider authID:(nullable NSString *)authID context:(nullable SNRClientAuthenticationContext *)context success:(void (^)(BOOL isSuccess))success failure:(void (^)(SNRApiError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-authentication#authenticate-customer-by-identityprovider) --- This method authenticates a customer with OAuth, Facebook, Google, Apple, or Synerise.
```Swift static func authenticateConditionally(token: AnyObject, clientIdentityProvider: ClientIdentityProvider, authID: String?, context: ClientConditionalAuthenticationContext?, success: ((ClientAuthenticationResult) -> Void), failure: ((ApiError) -> Void)) ```
```Objective-C + (void)authenticateConditionallyWithToken:(id)token clientIdentityProvider:(SNRClientIdentityProvider)clientIdentityProvider authID:(nullable NSString *)authID context:(nullable SNRClientConditionalAuthenticationContext *)context success:(void (^)(SNRClientAuthenticationResult *authResult))success failure:(void (^)(SNRApiError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-authentication#authenticate-customer-conditionally-by-identityprovider) --- This method authenticates a customer with OAuth.
```Swift static func authenticateByOAuth(accessToken: String, authID: String?, context: ClientOAuthAuthenticationContext?, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)authenticateByOAuthWithAccessToken:(nonnull NSString *)accessToken authID:(nullable NSString *)authID context:(nullable SNRClientOAuthAuthenticationContext *)context success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-authentication#authenticate-customer-by-oauth-with-registration) - **REMOVED in version 5.0.0** --- This method authenticates a customer with OAuth.
```Swift static func authenticateByOAuthIfRegistered(accessToken: String, authID: String?, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)authenticateByOAuthIfRegisteredWithAccessToken:(nonnull NSString *)accessToken authID:(nullable NSString *)authID success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-authentication#authenticate-customer-by-oauth-without-registration) - **REMOVED in version 5.0.0** --- This method authenticates a customer with Facebook.
```Swift static func authenticateByFacebook(facebookToken: String, authID: String?, context: ClientFacebookAuthenticationContext?, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)authenticateByFacebookWithFacebookToken:(nonnull NSString *)facebookToken authID:(nullable NSString *)authID context:(nullable SNRClientFacebookAuthenticationContext *)context success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-authentication#authenticate-customer-by-facebook-with-registration) - **REMOVED in version 5.0.0** --- This method authenticates a customer with Facebook.
```Swift static func authenticateByFacebookIfRegistered(facebookToken: String, authID: String?, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)authenticateByFacebookIfRegisteredWithFacebookToken:(nonnull NSString *)facebookToken authID:(nullable NSString *)authID success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-authentication#authenticate-customer-by-facebook-without-registration) - **REMOVED in version 5.0.0** --- This method authenticates a customer with Sign In With Apple.
```Swift static func authenticateByAppleSignIn(identityToken: Data, authID: String?, context: ClientAppleSignInAuthenticationContext?, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)authenticateByAppleSignInWithIdentityToken:(nonnull NSData *)identityToken authID:(nullable NSString *)authID context:(nullable SNRClientAppleSignInAuthenticationContext *)context success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-authentication#authenticate-customer-by-sign-in-with-apple-with-registration) - **REMOVED in version 5.0.0** --- This method authenticates a customer with Sign In With Apple.
```Swift static func authenticateByAppleSignInIfRegistered(identityToken: Data, authID: String?, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)authenticateByAppleSignInIfRegisteredWithIdentityToken:(nonnull NSData *)identityToken authID:(nullable NSString *)authID success:(nonnull void (^)(BOOL isSuccess))success failure:nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-authentication#authenticate-customer-by-sign-in-with-apple-without-registration) - **REMOVED in version 5.0.0** --- This method signs in a customer in with the provided token payload.
```Swift static func authenticate(tokenPayload: TokenPayload, authID: String, success: (() -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)authenticateWithTokenPayload:(SNRTokenPayload *)tokenPayload authID:(NSString *)authID success:(void (^)(void))success failure:(void (^)(SNRApiError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-authentication#authenticate-customer-with-token-payload) --- This method authenticates a customer with Simple Profile Authentication.
```Swift static func simpleAuthentication(data: ClientSimpleAuthenticationData, authID: String, success: (() -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)simpleAuthentication:(SNRClientSimpleAuthenticationData *)data authID:(NSString *)authID success:(void (^)(void))success failure:(void (^)(SNRApiError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-authentication#authenticate-customer-via-simple-profile-authentication) --- This method checks if a customer is signed in (via Synerise Authentication - RaaS, OAuth, Facebook, Apple).
```Swift static func isSignedIn() -> Bool ```
```Objective-C + (BOOL)isSignedIn ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-authentication#check-if-a-customer-is-signed-in-via-raas-oauth-facebook-apple) --- This method checks if a customer is signed in (via Simple Profile Authentication).
```Swift static func isSignedInViaSimpleAuthentication() -> Bool ```
```Objective-C + (BOOL)isSignedInViaSimpleAuthentication ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-authentication#check-if-a-customer-is-signed-in-via-simple-profile-authentication) --- This method signs out a customer out.
```Swift static func signOut() ```
```Objective-C + (void)signOut ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-authentication#sign-out-customer) --- This method signs out a customer out with a chosen mode.
```Swift static func signOut(mode: ClientSignOutMode) ```
```Objective-C + (void)signOutWithMode:(SNRClientSignOutMode)mode ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-authentication#sign-out-customer-with-mode) - **REMOVED in version 5.0.0** --- This method signs out a customer out with a chosen mode and Determines if the method should sign out all devices
```Swift static func signOut(mode: ClientSignOutMode, fromAllDevices: Bool, success: (() -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)signOutWithMode:(SNRClientSignOutMode)mode fromAllDevices:(BOOL)fromAllDevices success:(void (^)(void))success failure:(void (^)(SNRApiError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-authentication#sign-out-customer-with-mode-or-from-all-devices) --- This method refreshes the customer’s current token.
```Swift static func refreshToken(success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)refreshTokenWithSuccess:(nonnull void (^)(void))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-session#refresh-customer-token) --- This method retrieves the customer’s current, active token.
```Swift static func retrieveToken(success: ((Token) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)retrieveTokenWithSuccess:(nonnull void (^)(SNRToken *token))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-session#retrieve-customer-token) --- This method retrieves the customer’s current UUID.
```Swift static func getUUID() -> String ```
```Objective-C + (NSString *)getUUID ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-session#get-current-customer-uuid) --- Retrieves the current UUID or generates a new one from a seed.
```Swift static func getUUIDForAuthentication(authID: String) -> String ```
```Objective-C + (NSString *)getUUIDForAuthenticationWithAuthID:(NSString *)authID; ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-session#get-customer-uuid-for-use-in-authentication) --- This method regenerates the UUID and clears the authentication token, login session, custom email, and custom identifier.
```Swift static func regenerateUUID() ```
```Objective-C + (BOOL)regenerateUUID ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-session#regenerate-customer) --- This method regenerates the UUID and clears the authentication token, login session, custom email, and custom identifier.
```Swift static func regenerateUUID(clientIdentifier: String) ```
```Objective-C + (BOOL)regenerateUUIDWithClientIdentifier:(nullable NSString *)clientIdentifier ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-session#regenerate-customer-with-identifier) --- This method destroys the session completely.
```Swift static func destroySession() ```
```Objective-C + (void)destroySession ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-session#destroy-current-session) --- This method gets a customer’s account information.
```Swift static func getAccount(success: ((ClientAccountInformation) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)getAccountWithSuccess:(void (^)(SNRClientAccountInformation *accountInformation))success failure:(void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-account#get-customer-account-information) --- This method retrieves events for an authenticated customer.
```Swift static func getEvents(apiQuery: ClientEventsApiQuery, success: (([ClientEventData]) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)getEventsWithApiQuery:(nonnull SNRClientEventsApiQuery *)apiQuery success:(nonnull void (^)(NSArray *events))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-account#get-customers-events) --- This method updates a customer’s account’s basic information (without identification data: uuid, customId, email).
```Swift static func updateAccountBasicInformation(context: ClientUpdateAccountBasicInformationContext, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)updateAccountBasicInformation:(nonnull SNRClientUpdateAccountBasicInformationContext *)context success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-account#update-customer-account-basic-information) --- This method updates a customer’s account information.
```Swift static func updateAccount(context: ClientUpdateAccountContext, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)updateAccount:(nonnull SNRClientUpdateAccountContext *)context success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-account#update-customer-account-information) --- This method requests a customer’s password reset with email.
```Swift static func requestPasswordReset(context: ClientPasswordResetRequestContext, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)requestPasswordReset:(nonnull SNRClientPasswordResetRequestContext *)context success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-account#request-password-reset-for-customer-account) --- This method confirm a customer’s password reset with the new password and token provided by password reset request.
```Swift static func confirmResetPassword(context: ClientPasswordResetConfirmationContext, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)confirmResetPassword:(nonnull SNRClientPasswordResetConfirmationContext *)context success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-account#confirm-password-reset-for-customer-account) --- This method changes a customer’s password.
```Swift static func changePassword(password: String, oldPassword: String, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)changePassword:(nonnull NSString *)password oldPassword:(nonnull NSString *)oldPassword success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-account#change-customers-account-password) --- This method requests a customer's email change.
```Swift static func requestEmailChange(email: String, password: String?, externalToken: AnyObject?, authID: String?, success: ((Bool) -> Void), failure: ((ApiError) -> Void)) ```
```Objective-C + (void)requestEmailChange:(NSString *)email password:(nullable NSString *)password externalToken:(nullable id)externalToken authID:(nullable NSString *)authID success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(SNRApiError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-account#request-email-change-for-customer-account) --- This method confirms an email change.
```Swift static func confirmEmailChange(token: String, newsletterAgreement: Bool, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)confirmEmailChange:(nonnull NSString *)token newsletterAgreement:(BOOL)newsletterAgreement success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-account#confirm-email-change-for-customer-account) --- Requests a customer's phone update. A confirmation code is sent to the phone number.
```Swift static func requestPhoneUpdate(phone: String, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)requestPhoneUpdate:(nonnull NSString *)phone success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-account#request-phone-update-on-customer-account) --- This method confirms a phone number update. This action requires the new phone number and confirmation code as parameters.
```Swift static func confirmPhoneUpdate(phone:confirmationCode: String, smsAgreement: Bool, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)confirmPhoneUpdate:(nonnull NSString *)phone confirmationCode:(nonnull NSString *)confirmationCode smsAgreement:(BOOL)smsAgreement success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-account#confirm-phone-update-on-customer-account) --- This method deletes a customer's account.
```Swift static func deleteAccount(clientAuthFactor: AnyObject, clientIdentityProvider: ClientIdentityProvider, authID: String, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)deleteAccount:(nonnull id)clientAuthFactor clientIdentityProvider:(SNRClientIdentityProvider)clientIdentityProvider authID:(nullable NSString *)authID success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-account#delete-customer-account-by-identity-provider) --- This method deletes a customer's account.
```Swift static func deleteAccount(password: String, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)deleteAccount:(nonnull NSString *)password success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/client-account#delete-customer-account) - **DEPRECATED in version 3.6.19** --- This method passes the Firebase Token to Synerise for notifications and doesn't update the agreement of the profile.
```Swift static func registerForPush(registrationToken: String, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)registerForPush:(nonnull NSString *)registrationToken success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/campaigns#register-for-push-notifications-without-agreement) --- This method passes the Firebase Token to Synerise for notifications.
```Swift static func registerForPush(registrationToken: String, mobilePushAgreement: Bool, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)registerForPush:(nonnull NSString *)registrationToken mobilePushAgreement:(BOOL)mobilePushAgreement success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/campaigns#register-for-push-notifications) --- --- ### Tracker The module for sending event tracking data to Synerise backend. Tracking is performed by creating pre-defined or custom event objects and sending these to Synerise. It also includes automatic event interception by the Auto-Tracking feature. **Declared In:** Headers/SNRTracker.h **Related To:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Inherits From:** [NSObject](https://developer.apple.com/documentation/objectivec/nsobject) **Declaration:**
```Swift class Tracker: NSObject ```
```Objective-C @interface SNRTracker : NSObject ```
**Methods:** This method sets an object for Tracker module delegate methods.
```Swift static func setDelegate(_: TrackerDelegate) ```
```Objective-C + (void)setDelegate:(nonnull id)delegate ```
[Click for more details](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#tracker-delegate) --- This method sets a custom identifier in the parameters of every event.
```Swift static func setCustomIdentifier(_: String?) ```
```Objective-C + (void)setCustomIdentifier:(nullable NSString *)customIdentifier ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/tracking#set-custom-identifier-for-events) --- This method sets a custom email in the parameters of every event.
```Swift static func setCustomEmail(_: String?) ```
```Objective-C + (void)setCustomEmail:(nullable NSString *)customEmail ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/tracking#set-custom-email-for-events) --- This method sends an event.
```Swift static func send(_: Event) ```
```Objective-C + (void)send:(SNREvent *)event ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/tracking#send-event) --- This method forces sending the events from the queue to the server.
```Swift static func flushEvents(completionHandler: (() -> Void)?) ```
```Objective-C + (void)flushEventsWithCompletionHandler:(nullable void (^)(void))completion ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/tracking#flush-events-from-tracker) --- --- ### Injector The module for handling Synerise UI activities such as walkthrough, banner, simple push, and so on. **Declared In:** Headers/SNRInjector.h **Inherits From:** [NSObject](https://developer.apple.com/documentation/objectivec/nsobject) **Declaration:**
```Swift class Injector: NSObject ```
```Objective-C @interface SNRInjector : NSObject ```
**Methods:** This method sets an object for in-app messages delegate methods.
```Swift static func setInAppMessageDelegate(_: InjectorInAppMessageDelegate) ```
```Objective-C + (void)setInAppMessageDelegate:(id)delegate ```
[(Click for more details)](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#injector-in-app-message-delegate) --- Closes an in-app message and sends an `inApp.discard` event. Usage examples: - Closing a top bar or bottom bar when the user taps outside the in-app area. - Automatically dismissing messages when navigating away from a screen. - Controlling in-app visibility based on app logic for a smoother user experience.
```swift static func closeInAppMessage(campaignHash: String) -> Void ```
```objective-c + (void)closeInAppMessage:(nonnull NSString *)campaignHash ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/campaigns#close-in-app-message) --- This method fetches a walkthrough.
```Swift static func getWalkthrough() ```
```Objective-C + (void)getWalkthrough ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/campaigns#get-walkthrough) - **REMOVED in version 5.0.0** --- This method shows a walkthrough when it is loaded.
```Swift static func showWalkthrough() ```
```Objective-C + (void)showWalkthrough ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/campaigns#show-walkthrough) - **REMOVED in version 5.0.0** --- This method checks if a walkthrough is loaded.
```Swift static func isWalkthroughLoaded() -> Bool ```
```Objective-C + (BOOL)isWalkthroughLoaded ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/campaigns#check-if-walkthrough-is-loaded) - **REMOVED in version 5.0.0** --- This method checks if the walkthrough is unique compared to the previous one.
```Swift static func isLoadedWalkthroughUnique() -> Bool ```
```Objective-C + (BOOL)isLoadedWalkthroughUnique ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/campaigns#check-if-loaded-walkthrough-is-unique) - **REMOVED in version 5.0.0** --- This method fetches Push Notifications set for mobile campaigns.
```Swift static func getPushes(success: (([[AnyHashable: Any]]) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)getPushesWithSuccess:(nonnull void (^)(NSArray *pushes))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/campaigns#get-pushes) - **REMOVED in version 5.0.0** --- This method provides valid banners directly from SDK cache.
```Swift static func getBanners() -> [[AnyHashable: Any]] ```
```Objective-C + (nonnull NSArray *)getBanners ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/campaigns#get-banners) - **REMOVED in version 4.6.0** --- This method fetches banners set for mobile campaigns and caches the valid ones.
```Swift static func fetchBanners(success: (([[AnyHashable: Any]]) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)fetchBannersWithSuccess:(nonnull void (^)(NSArray *banners))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/campaigns#fetch-banners) - **REMOVED in version 4.6.0** --- This method shows a banner immediately.
```Swift static func showBanner(_: [AnyHashable: Any], markPresented: Bool) ```
```Objective-C + (void)showBanner:(nonnull NSDictionary *)bannerDictionary markPresented:(BOOL)markPresented ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/campaigns#show-banner) - **REMOVED in version 4.6.0** --- --- ### Promotions The module for handling promotions and vouchers from Synerise SDK. **Declared In:** Headers/SNRPromotions.h **Related To:** [PromotionsApiQuery](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotionsapiquery) [PromotionIdentifier](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotionidentifier) [PromotionResponse](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotionresponse) [Promotion](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotion) [AssignVoucherResponse](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#assignvoucherresponse) [VoucherCodesResponse](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#vouchercodesresponse) **Inherits From:** [NSObject](https://developer.apple.com/documentation/objectivec/nsobject) **Declaration:**
```Swift class Promotions: NSObject ```
```Objective-C @interface SNRPromotions : NSObject ```
**Methods:** This method retrieves all available promotions that are defined for a customer.
```Swift static func getPromotions(success: ((PromotionResponse) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)getPromotionsWithSuccess:(nonnull void (^)(SNRPromotionResponse *promotionResponse))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/promotions#get-all-promotions-of-a-customer) --- This method retrieves promotions that match the parameters defined in an API query.
```Swift static func getPromotions(apiQuery: PromotionsApiQuery, success: ((PromotionResponse) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)getPromotionsWithApiQuery:(nonnull SNRPromotionsApiQuery *)apiQuery success:(nonnull void (^)(SNRPromotionResponse *promotionResponse))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/promotions#get-promotions-with-query-parameters) --- This method retrieves the promotion with the specified UUID.
```Swift static func getPromotion(uuid: String, success: ((Promotion) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)getPromotionByUuid:(nonnull NSString *)uuid success:(nonnull void (^)(SNRPromotion *promotion))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/promotions#get-promotion-by-uuid) --- This method retrieves the promotion with the specified code.
```Swift static func getPromotion(code: String, success: ((Promotion) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)getPromotionByCode:(nonnull NSString *)code success:(nonnull void (^)(SNRPromotion *promotion))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/promotions#get-promotion-by-code) --- This method activates the promotion with the specified UUID.
```Swift static func activatePromotion(uuid: String, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)activatePromotionByUuid:(nonnull NSString *)uuid success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/promotions#activate-promotion-by-uuid) --- This method activates the promotion with the specified code.
```Swift static func activatePromotion(code: String, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)activatePromotionByCode:(nonnull NSString *)code success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/promotions#activate-promotion-by-code) --- This method activates promotions with a code or with UUID in a batch.
```Swift static func activatePromotions(identifiers: [PromotionIdentifier], success: ((Bool) -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)activatePromotionsWithIdentifiers:(nonnull NSArray *)identifiers success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(SNRApiError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/promotions#activate-promotions-in-a-batch) --- This method deactivates the promotion with the specified UUID.
```Swift static func deactivatePromotion(uuid: String, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)deactivatePromotionByUuid:(nonnull NSString *)uuid success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/promotions#deactivate-promotion-by-uuid) --- This method deactivates the promotion with the specified code.
```Swift static func deactivatePromotion(code: String, success: ((Bool) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)deactivatePromotionByUuid:(nonnull NSString *)uuid success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/promotions#deactivate-promotion-by-code) --- This method deactivates promotions with a code or with UUID in a batch.
```Swift static func deactivatePromotions(identifiers: [PromotionIdentifier], success: ((Bool) -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)deactivatePromotionsWithIdentifiers:(nonnull NSArray *)identifiers success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(SNRApiError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/promotions#deactivate-promotions-in-a-batch) --- This method retrieves an assigned voucher code or assigns a voucher from a pool identified by UUID to the profile. When the voucher is assigned for the first time, a [voucherCode.assigned](/docs/assets/events/event-reference/loyalty#vouchercodeassigned) event is produced.
```Swift static func getOrAssignVoucher(poolUUID: String, success: ((AssignVoucherResponse) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)getOrAssignVoucherWithPoolUUID:(NSString *)poolUUID success:(void (^)(SNRAssignVoucherResponse *assignVoucherResponse))success failure:(void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/promotions#get-or-assign-voucher-from-pool) --- This method assigns a voucher from a pool identified by UUID to the profile. A [voucherCode.assigned](/docs/assets/events/event-reference/loyalty#vouchercodeassigned) event is produced.
```Swift static func assignVoucherCode(poolUUID: String, success: ((AssignVoucherResponse) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)assignVoucherCodeWithPoolUUID:(nonnull NSString *)poolUUID success:(nonnull void (^)(SNRAssignVoucherResponse *assignVoucherResponse))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/promotions#assign-voucher-code-from-pool) --- This method retrieves voucher codes for a customer.
```Swift static func getAssignedVoucherCodes(success: ((VoucherCodesResponse) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)getAssignedVoucherCodesWithSuccess:(nonnull void (^)(SNRVoucherCodesResponse *voucherCodesResponse))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/promotions#get-voucher-codes-assigned-to-customer) --- --- ### Content The module for handling content from Synerise backend such as documents, recommendations, and so on. **Declared In:** Headers/SNRContent.h **Related To:** [Document](/developers/mobile-sdk/class-reference/ios/recommendations-and-documents#document) [DocumentApiQuery](/developers/mobile-sdk/class-reference/ios/recommendations-and-documents#documentapiquery) [DocumentsApiQuery](/developers/mobile-sdk/class-reference/ios/recommendations-and-documents#documentsapiquery) [RecommendationResponse](/developers/mobile-sdk/class-reference/ios/recommendations-and-documents#recommendationresponse) [Recommendation](/developers/mobile-sdk/class-reference/ios/recommendations-and-documents#recommendation) [ScreenView](/developers/mobile-sdk/class-reference/ios/miscellaneous#screenview) [ScreenViewApiQuery](/developers/mobile-sdk/class-reference/ios/miscellaneous#screenviewapiquery) **Inherits From:** [NSObject](https://developer.apple.com/documentation/objectivec/nsobject) **Declaration:**
```Swift class Content: NSObject ```
```Objective-C @interface SNRContent : NSObject ```
**Methods:** This method generates the document assigned to a slug.
```Swift static func getDocument(slug: String, success: (([AnyHashable: Any]) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)getDocument:(nonnull NSString *)slug success:(nonnull void (^)(NSDictionary *document))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/content#get-document) - **REMOVED in version 5.0.0** --- This method generates the document that is defined for the provided slug.
```Swift static func generateDocument(slug: String, success: ((Document) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)generateDocument:(nonnull NSString *)slug success:(nonnull void (^)(SNRDocument *document))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/content#generate-document) --- This method generates the document that is defined for parameters provided in the query object.
```Swift static func generateDocument(apiQuery: DocumentApiQuery, success: ((Document) -> Void), failure: ((ApiError) -> Void)) ```
```Objective-C + (void)generateDocumentWithApiQuery:(SNRDocumentApiQuery *)apiQuery success:(void (^)(SNRDocument *document))success failure:(void (^)(SNRApiError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/content#generate-document-with-query-parameters) --- This method generates documents that are defined for parameters provided in the query object.
```Swift static func getDocuments(apiQuery: DocumentsApiQuery, success: (([[AnyHashable: Any]]) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)getDocumentsWithApiQuery:(nonnull SNRDocumentsApiQuery *)apiQuery success:(nonnull void (^)(NSArray *documents))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/content#get-documents) - **REMOVED in version 5.0.0** --- This method generates recommendations that are defined for the options provided. The recommendations are generated by using a document with an insert. For instructions, see ["Displaying AI recommendations > With documents and screen views"](/developers/mobile-sdk/displaying-recommendations/documents).
```Swift static func getRecommendations(options: RecommendationOptions, success: ((RecommendationResponse) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)getRecommendations:(nonnull SNRRecommendationOptions *)options success:(nonnull void (^)(SNRRecommendationResponse *recommendationResponse))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/content#get-recommendations) - **REMOVED in version 5.0.0** --- This method generates recommendations that are defined for the options provided. The recommendations are generated by using a document with an insert. For instructions, see ["Displaying AI recommendations > With documents and screen views"](/developers/mobile-sdk/displaying-recommendations/documents).
```Swift static func getRecommendationsV2(options: RecommendationOptions, success: ((RecommendationResponse) -> Void), failure: ((Error) -> Void)) ```
```Objective-C + (void)getRecommendationsV2:(nonnull SNRRecommendationOptions *)options success:(nonnull void (^)(SNRRecommendationResponse *recommendationResponse))success failure:(nonnull void (^)(NSError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/content#get-recommendations-v2) --- This method generates the customer's highest-priority screen view campaign.
```Swift static func getScreenView(success: ((ScreenViewResponse) -> Void), failure: ((ApiError) -> Void)) ```
```Objective-C + (void)getScreenViewWithSuccess:(nonnull void (^)(SNRScreenViewResponse *screenViewResponse))success failure:(nonnull void (^)(SNRApiError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/content#get-screen-view) - **REMOVED in version 5.0.0** --- This method generates a customer's highest-priority screen view campaign from the feed with the provided feed slug.
```Swift static func generateScreenView(feedSlug: String, success: ((ScreenView) -> Void), failure: ((ApiError) -> Void)) ```
```Objective-C + (void)generateScreenView:(NSString *)feedSlug success:(nonnull void (^)(SNRScreenView *screenView))success failure:(nonnull void (^)(SNRApiError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/content#generate-screen-view) --- This method generates customer's highest-priority screen view campaign that is defined for parameters provided in the query object.
```Swift static func generateScreenView(apiQuery: ScreenViewApiQuery, success: ((ScreenView) -> Void), failure: ((ApiError) -> Void)) ```
```Objective-C + (void)generateScreenView:(SNRScreenViewApiQuery *)apiQuery success:(nonnull void (^)(SNRScreenView *screenView))success failure:(nonnull void (^)(SNRApiError *error))failure ```
[(Click for more details)](/developers/mobile-sdk/method-reference/ios/content#generate-screen-view-with-query-parameters) # SDK Lifecycle ### InitializationConfig Class for additional initialization parameters. **Declared In:** lib/classes/models/Misc/InitializationConfig.js **Declaration:**
class InitializationConfig
**Properties:** | Property | Type | Description | | --- | --- | --- | | **requestValidationSalt** | string | [Simple Profile Authentication](/developers/mobile-sdk/user-identification-and-authorization/simple-authentication) salt | --- --- ### Synerise **Declared In:** lib/main/Synerise.js **Declaration:**
class Synerise
**Properties:** | Property | Type | Description | | --- | --- | --- | | **Initializer** | [SyneriseInitializer](/developers/mobile-sdk/class-reference/react-native/lifecycle#syneriseinitializer) | Returns the [SyneriseInitializer](/developers/mobile-sdk/class-reference/react-native/lifecycle#syneriseinitializer) object used for initialization | | **Settings** | [SettingsModule](/developers/mobile-sdk/class-reference/react-native/modules#settings) | Returns the Settings module when Synerise is initialized | | **Client** | [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) | Returns the Client module when Synerise is initialized | | **Tracker** | [TrackerModule](/developers/mobile-sdk/class-reference/react-native/modules#tracker) | Returns the Tracker module when Synerise is initialized | | **Notifications** | [NotificationsModule](/developers/mobile-sdk/class-reference/react-native/modules#notifications) | Returns the Notifications module when Synerise is initialized| | **Injector** | [InjectorModule](/developers/mobile-sdk/class-reference/react-native/modules#injector) | Returns the Injector module when Synerise is initialized | | **Promotions** | [PromotionsModule](/developers/mobile-sdk/class-reference/react-native/modules#promotions) | Returns the Promotions module when Synerise is initialized | | **Content** | [ContentModule](/developers/mobile-sdk/class-reference/react-native/modules#content) | Returns the Content module when Synerise is initialized | **Methods:** This method sets the callback function that is invoked when the Synerise SDK is initialized.
public static onReady(callback: () => void)
[(Click for more details)](/developers/mobile-sdk/listeners-and-delegates/react-native-listeners#initialization) --- This method sets the callback function that is invoked when an error occurs while initializing the Synerise SDK.
public static onError(callback: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/listeners-and-delegates/react-native-listeners#initialization) --- This method checks if Synerise is initialized.
public static isInitialized(): boolean
--- This method changes the Profile API Key (formerly Client API Key) dynamically.
public static changeApiKey(ApiKey: string, config?: InitializationConfig | undefined)
--- --- --- ### SyneriseInitializer Class responsible for initialization of the SDK. **Declared In:** lib/main/Synerise.js **Declaration:**
class SyneriseInitializer
**Methods:** This method sets Profile API Key (formerly Client API Key) for the SDK initialization.
public withApiKey(ApiKey: string)
Before version 1.0.0, this method was called `withClientApiKey`.
--- This method sets the Synerise API base URL for SDK initialization in a custom environment.
public withBaseUrl(baseUrl: string)
--- This method sets the salt string for request validation.
public withRequestValidationSalt(requestValidationSalt: string)
--- This method enables or disables console logs from Synerise SDK.
public withDebugModeEnabled(debugModeEnabled: boolean)
--- This method enables or disables crash handling by Synerise SDK.
public withCrashHandlingEnabled(crashHandlingEnabled: boolean)
--- This method sets the required settings prior to the Synerise initialization.
public withSettings(settings: ISettingsOptions)
--- This method initializes Synerise.
public init()
--- --- --- # Android ## Installation and configuration (Android) In this article, you will find out how to install, configure, and initialize the Synerise SDK in an Android mobile application. While performing the actions from this guide, keep the presented order.
The [Settings](/developers/mobile-sdk/settings#pre-initialization-settings) article contains additional information about SDK behaviors you may need prior to configuration.
If you want to find out what kind of benefits you can get from integrating with mobile SDK, go [here](/developers/mobile-sdk/overview). ### Requirements --- You need: * Access to a [workspace](/docs/settings/workspace) * A Profile [API Key](/docs/settings/tool/api#adding-api-keys) When creating the API key, use allowlisting or denylisting to only allow the events you intend to use. * Minimum Android SDK version: 24 * Supported targetSDKVersion: 34 #### 3rd Party Frameworks - [RxJava](https://github.com/ReactiveX/RxJava) - [RxAndroid](https://github.com/ReactiveX/RxAndroid) - [OkHttp](https://github.com/square/okhttp) - [Retrofit](https://github.com/square/retrofit) - [OkHttp](https://github.com/square/okhttp) - [Picasso](https://github.com/square/picasso) - [Fresco](https://github.com/facebook/fresco) - [ConstraintLayout](https://github.com/androidx/constraintlayout) - [Joda-Time](https://github.com/JodaOrg/joda-time) ### Installation --- 1. Set maven path in your `root/build.gradle` file:
...
       allprojects {
           repositories {
               google()
               jcenter()
               maven { url 'https://pkgs.dev.azure.com/Synerise/AndroidSDK/_packaging/prod/maven/v1' }
           }
       }
2. Add dependency to your `project/build.gradle` file:
buildscript {
           repositories {
               google()
               jcenter()
           }
           dependencies {
               classpath 'com.android.tools.build:gradle:3.4.2'
           }
       }
We guarantee stability only on Android Gradle plugin 3.4.2 or lower.
3. Import dependency in your `app/build.gradle` file and apply the plugin:
apply plugin: 'com.android.application'

       ...
       dependencies {
       ...
       // Synerise Android SDK;
       implementation 'com.synerise.sdk:synerise-mobile-sdk:ANDROID_SDK_VERSION'
       // Replace ANDROID_SDK_VERSION with the version, for example 5.4.0;
       // Check latest version at https://github.com/Synerise/android-sdk/blob/master/CHANGELOG.md
       }
4. *For Android Studio versions older than 3.5*: Go to **File > Settings > Build, Execution, Deployment > Instant Run** and make sure that Instant Run is disabled. ### Configuration --- For your convenience, [Synerise.Builder](/developers/mobile-sdk/class-reference/android/lifecycle#synerise-builder) makes it possible to configure SDK behavior depending on your needs.
The `Synerise.Builder.with(..)` method is mandatory.
The basic callbacks you need: - [.pushRegistrationRequired(OnRegisterForPushListener)](/developers/mobile-sdk/class-reference/android/lifecycle#synerise-builder) - Synerise SDK may request registering a customer for push notifications. This callback is called after a customer signs in, signs up, or deletes an account. - [.baseUrl(String)](/developers/mobile-sdk/class-reference/android/lifecycle#synerise-builder) - This callback lets you provide your custom base URL to use your own domain for connecting to the Synerise API.
If you use Synerise hosted on: - Google Cloud ([app.geb.synerise.com](https://app.geb.synerise.com)), use `baseUrl(https://api.geb.snrapi.com)` - Microsoft Azure USA ([app.azu.synerise.com](https://app.azu.synerise.com)), use `baseUrl(https://api.azu.snrapi.com)`
- `.mesaggingServiceType(MessagingServiceType)` - This callback sets the messaging provider: Huawei Mobile Services (HMS) or Google Mobile Services (GMS). When publishing the app to appGallery, we recommend using HMS.
Click to expand the full list of callbacks
Callbacks Description
.build() Builds the Synerise SDK with the provided data. The `Synerise.Builder.build()` method can be called only once during the entire application lifecycle, so you must call this method in your `Application` class.
.crashHandlingEnabled(boolean) For more information, see the Crash Handling section.
.notificationDefaultChannelId(String) Sets the ID of Push Notification Channel.
.notificationDefaultChannelName(String) Sets the name of Push Notification Channel.
.notificationHighPriorityChannelId(String) Sets the ID of High Priority Push Notification Channel.
.notificationHighPriorityChannelName(String) Sets the name of High Priority Push Notification Channel.
`.rxJavaErrorHandlingEnabled(boolean)` If set to true, Synerise handles rxJava errors.
If false, you need to call rxJavaPlugins.setErrorHandler on your own.
.syneriseDebugMode(boolean) When true, enables full network traffic logs. It is not recommended to use debug mode in a release version of your app. Debug mode is disabled by default.
`Synerise.settings.injector.automatic = boolean;` When true, enables automatic mode in the injector.
`Synerise.settings.tracker.autoTracking.trackMode = TrackMode` Sets the mode for view tracking.
`Synerise.settings.tracker.locationAutomatic = boolean;` Use to obtain customer location and send the location event automatically.
`Synerise.settings.tracker.setAutoFlushTimeout(int);` Sets the maximum time (in ms) since the last event queue was sent before attempting to automatically send another queue. Default value: 5000 ms. Minimum value: 50 ms.
`Synerise.settings.tracker.setMaximumBatchSize(int);` Sets the maximum number of events which may be sent in a single batch. Default value: 100. You can set the value between 1 and 100.
`Synerise.settings.tracker.setMinimumBatchSize(int);` Sets the minimum number of events in queue required to send them. Default value: 10. You can set the value between 1 and 100.
### Initialization ---
Synerise SDK must be initialized in the [Application class](https://developer.android.com/reference/android/app/Application). This is because Synerise SDK performs some operations while the application is running in the background.
1. Initialize Synerise Android SDK by using the `with` method and provide: - `Application name` - `Application instance` - [API Key](/docs/settings/tool/api) 1. To get the Profile (client) API key, go to **Synerise > Settings > API keys**. 2. On the list of the keys, select the one you created as a part of [requirements](#requirements). 3. In the **General** section, click **Show**. 4. Copy the API key. 2. Add the key in your `Application` sub-class:
```Swift public class App extends MultiDexApplication { @Override public void onCreate() { super.onCreate(); initSynerise(); } private void initSynerise() { String syneriseClientApiKey = getString(R.string.synerise_clientool/api_key); String appId = getString(R.string.app_name); Synerise.settings.tracker.autoTracking.trackMode = FINE; Synerise.settings.tracker.setMinimumBatchSize(10); Synerise.settings.tracker.setMaximumBatchSize(100); Synerise.settings.tracker.setAutoFlushTimeout(5000); Synerise.settings.injector.automatic = false; Synerise.settings.tracker.locationAutomatic = true; Synerise.Builder.with(this, syneriseClientApiKey, appId) .notificationIcon(R.drawable.notification_icon) .notificationIconColor(ContextCompat.getColor(this, R.color.amaranth)) .syneriseDebugMode(true) .pushRegistrationRequired(this) .locationUpdateRequired(this) .notificationDefaultChannelId("your-channel-id") .notificationDefaultChannelName("your-channel-name") .notificationHighPriorityChannelId("your-high-channel-id") .notificationHighPriorityChannelName("your-high-channel-name") .baseUrl("http://your-base-url.com/") .setRequestValidationSalt("YOUR_REQUEST_VALIDATION_SALT") .build(); } } ```
```kotlin class App : MultiDexApplication() { override fun onCreate() { super.onCreate() initSynerise() } private fun initSynerise() { val syneriseClientApiKey = accountManager!!.getClientProfileApiKey() val appId = getString(R.string.app_name) Synerise.settings.tracker.autoTracking.trackMode = FINE; Synerise.settings.tracker.setMinimumBatchSize(10); Synerise.settings.tracker.setMaximumBatchSize(100); Synerise.settings.tracker.setAutoFlushTimeout(5000); Synerise.settings.injector.automatic = false; Synerise.settings.tracker.locationAutomatic = true; Synerise.Builder.with(this, syneriseClientApiKey, appId) .notificationIcon(R.drawable.ic_cart) .notificationIconColor(ContextCompat.getColor(this, R.color.amaranth)) .syneriseDebugMode(true) .pushRegistrationRequired(this) .locationUpdateRequired(this) .notificationDefaultChannelId("your-channel-id") .notificationDefaultChannelName("your-channel-name") .notificationHighPriorityChannelId("your-high-channel-id") .notificationHighPriorityChannelName("your-high-channel-name") .baseUrl("http://your-base-url.com/") .setRequestValidationSalt("YOUR_REQUEST_VALIDATION_SALT") .build() } } ```
3. Add the key in your `/values` strings file (for example, `strings.xml`):
<resources>

       <string name="app_name" translatable="false">Your GREAT application name</string>
       <string name="synerise_client_api_key" translatable="false">EF1AD0E0-532B-6AEE-6010-DEDC78F6E155</string> <!-- replace with valid client api key -->

       ...

   </resources>
Secure sensitive keys (for example, `apiKey` and `requestValidationSalt`) with mechanisms like string obfuscation or encryption.
### Troubleshooting --- #### MultiDex {id=troubleshooting-multidex} Sometimes, MultiDex errors may occur. In that case, enable MultiDex as follows (API >= 21):
defaultConfig {
    applicationId "com.your.app"
    minSdkVersion 21
    ...
    multiDexEnabled true
}
or for API < 21:
defaultConfig {
    applicationId "com.your.app"
    minSdkVersion 20
    ...
    multiDexEnabled true
}
dependencies {
    ...
    // MultiDex
    implementation 'com.android.support:multidex:1.0.3'
    ...
}
public class YourApp extends MultiDexApplication {

    @Override
    public void onCreate() {
        super.onCreate();
        ...
    }
You can find more information about MultiDex at [this link](https://developer.android.com/studio/build/multidex.html). #### AndroidManifest Merger {id=troubleshooting-androidmanifest-merger} Sometimes, AndroidManifest Merger errors may occur. In that case, paste the following code in your AndroidManifest application tag.
<application
    ...
    tools:replace="android:theme">
Also, if your app did not ask for location permission, remove it from your app with:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" tools:node="remove"/>
### Work Manager Work Manager is a mechanism to schedule and run code in the background to keep your app up to date. Synerise supports using Work Manager since SDK version **5.21.0**. #### Benefits Currently, the SDK uses background tasks only to refresh the registration token for push notifications every 20 days. In these situations, the SDK invokes the [onRegisterForPushRequired(origin:)](/developers/mobile-sdk/listeners-and-delegates/android-listeners#on-register-for-push-listener-on-register-for-push-required-with-origin) callback method or [onRegisterForPushRequired()](/developers/mobile-sdk/listeners-and-delegates/android-listeners#on-register-for-push-listener-on-register-for-push-required) callback method. #### Setting up Work Manager is configured out of the box without any special configuration. ### Proguard configuration The Synerise Android SDK obfuscates code on its own. We highly recommend keeping the entire SDK. Rules: ```plaintext # keep entire Synerise SDK -keep class com.synerise.sdk.** { *; } -keepclassmembers class com.synerise.sdk.** { *; } -keepclassmembers class com.synerise.sdk.** { public (); } ``` # SDK lifecycle --- ## Initialization --- This method initializes Synerise.
This method must be called before any other Synerise SDK method and only once during the application's lifecycle.
**Declared In:** lib/main/Synerise.js **Related To:** [Synerise](/developers/mobile-sdk/class-reference/react-native/lifecycle#synerise) [SyneriseInitializer](/developers/mobile-sdk/class-reference/react-native/lifecycle#syneriseinitializer) **Class:** [PromotionsModule](/developers/mobile-sdk/class-reference/react-native/modules#promotions) **Builder Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **withBaseUrl** | string | no | - | Synerise API custom environment base URL | | **withApiKey** | string | yes | - | Synerise Profile (formerly Client) API Key | | **withDebugModeEnabled** | **boolean** | no | - | Enables or disables console logs | | **withCrashHandlingEnabled** | **boolean** | no | - | Enables or disables crash handling | | **withSettings** | **object** | no | - | Settings that have to be configured before Synerise is initialized |
Before version 1.0.0, the `withApiKey` method was called `withClientApiKey`.
**Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Initializer() .withBaseUrl("YOUR_API_BASE_URL") .withApiKey('YOUR_PROFILE_API_KEY') .withDebugModeEnabled(true) .withCrashHandlingEnabled(true) .withSettings({ sdk: { enabled: true }) .init(); ```
## Change Profile API key dynamically --- This method changes a Profile (formerly Client) API key dynamically. **Declared In:** lib/main/Synerise.js **Declaration:**
public static changeApiKey(ApiKey: string, config?: InitializationConfig | undefined)
Before version 1.0.0, this method was called `changeClientApiKey`.
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **apiKey** | string | yes | - | New API key | | **config** | [InitializationConfig](/developers/mobile-sdk/class-reference/react-native/lifecycle#initializationconfig) | no | - | Object for additional initialization settings after the API key change | **Return Value:** No value is returned. **Example:**
```JavaScript Synerise.changeApiKey(apiKey); ```
## Change Profile API Key dynamically with config --- This method changes a Profile (formerly Client) API key dynamically, with additional parameters. It can include a salt for [Simple Profile Authentication](/developers/mobile-sdk/user-identification-and-authorization/simple-authentication) requests. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.19.0 | 5.20.0 | 0.23.0 | 1.3.0 | **Declared In:** lib/main/Synerise.js **Declaration:**
public static changeApiKey(ApiKey: string, config?: InitializationConfig | undefined)
Before version 1.0.0, this method was called `changeClientApiKey`.
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **apiKey** | string | yes | - | New API key | | **config** | [InitializationConfig](/developers/mobile-sdk/class-reference/react-native/lifecycle#initializationconfig) | no | - | Object for additional initialization settings after the API key change | **Return Value:** No value is returned. **Example:**
```JavaScript Synerise.changeApiKey(apiKey); ```
# SDK lifecycle ## Set Synerise delegate --- This method sets an object for Synerise delegate methods. **Declared In:** Headers/SNRSynerise.h **Related To:** [SyneriseDelegate](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#synerise-delegate) **Class:** Synerise **Declaration:**
```Swift static func setDelegate(_ delegate: SyneriseDelegate) ```
```Objective-C + (void)setDelegate:(SNRSyneriseDelegate *)delegate ```
**Discussion:** Learn more about the methods and the purpose of this listener [here](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#synerise-delegate). ## Initialization --- This method initializes Synerise.
This method must be called before any other Synerise SDK method and only once during the application's lifecycle.
**Declared In:** Headers/SNRSynerise.h **Class:** [Synerise](/developers/mobile-sdk/class-reference/ios/modules#synerise) **Declaration:**
```Swift static func initialize(apiKey: String) -> Void ```
```Objective-C + (void)initializeWithApiKey:(NSString *)apiKey ```
Before version 5.0.0, this method was called `Synerise.initialize(clientApiKey:)`.
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **apiKey** | String | yes | - | Synerise Profile (formerly Client) API Key | **Return Value:** No value is returned. **Example:**
```Swift let apiKey = "YOUR_PROFILE_API_KEY" Synerise.initialize(apiKey: apiKey) ```
```Objective-C static NSString *apiKey = @"YOUR_PROFILE_API_KEY"; [SNRSynerise initializeWithApiKey:apiKey]; ```
## Initialize with custom environment --- This method initializes Synerise SDK with custom environment settings.
This method must be called before any other Synerise SDK method and only once during the application's lifecycle.
**Declared In:** Headers/SNRSynerise.h **Class:** [Synerise](/developers/mobile-sdk/class-reference/ios/modules#synerise) **Declaration:**
```Swift static func initialize(apiKey: String, baseUrl: String?) -> Void ```
```Objective-C + (void)initializeWithApiKey:(NSString *)apiKey andBaseUrl:(nullable NSString *)baseUrl ```
Before version 5.0.0, this method was called `Synerise.initialize(clientApiKey:baseUrl:)`.
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **apiKey** | String | yes | - | Synerise Profile (formerly Client) API Key | | **baseUrl** | String | no | - | Synerise API custom environment base URL | You can use one of the constants:
**SyneriseApiUrls.SYNERISE_AZ_API_URL** - `https://api.snrapi.com` **SyneriseApiUrls.SYNERISE_AZU_API_URL** - `https://api.azu.snrapi.com` **SyneriseApiUrls.SYNERISE_GEB_API_URL** - `https://api.geb.snrapi.com`
**SNR_SYNERISE_AZ_API_URL** - `https://api.snrapi.com` **SNR_SYNERISE_AZU_API_URL** - `https://api.azu.snrapi.com` **SNR_SYNERISE_GEB_API_URL** - `https://api.geb.snrapi.com`
**Return Value:** No value is returned. **Example:**
```Swift let apiKey = "YOUR_PROFILE_API_KEY" let apiBaseUrl = "YOUR_API_BASE_URL" Synerise.initialize(apiKey: apiKey, baseUrl: apiBaseUrl) ```
```Objective-C static NSString *apiKey = @"YOUR_PROFILE_API_KEY"; static NSString *apiBaseUrl = @"YOUR_API_BASE_URL"; [SNRSynerise initializeWithApiKey:apiKey andBaseUrl:apiBaseUrl]; ```
## Change Profile API Key dynamically --- This method changes a Profile (formerly Client) API key dynamically. **Declared In:** Headers/SNRSynerise.h **Class:** [Synerise](/developers/mobile-sdk/class-reference/ios/modules#synerise) **Declaration:**
```Swift static func changeApiKey(_ apiKey: String) -> Void ```
```Objective-C + (void)changeApiKey:(nonnull NSString *)apiKey ```
Before version 5.0.0, this method was called `Synerise.changeClientApiKey(_ clientApiKey:)`.
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **apiKey** | String | yes | - | Synerise Profile API Key (formerly Client API key) | **Return Value:** No value is returned. ## Change Profile API Key dynamically with config --- This method changes a Profile (formerly Client) API key dynamically, with additional parameters. It can include a salt for [Simple Profile Authentication](/developers/mobile-sdk/user-identification-and-authorization/simple-authentication) requests. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.19.0 | 5.20.0 | 0.23.0 | 1.3.0 | **Declared In:** Headers/SNRSynerise.h **Class:** [Synerise](/developers/mobile-sdk/class-reference/ios/modules#synerise) **Declaration:**
```Swift static func changeApiKey(_ apiKey: String, config: InitializationConfig?) -> Void ```
```Objective-C + (void)changeApiKey:(nonnull NSString *)apiKey config:(nullable SNRInitializationConfig *)config; ```
Before version 5.0.0, this method was called `Synerise.changeClientApiKey(_ clientApiKey:config:)`.
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **apiKey** | String | yes | - | Synerise Profile API Key (formerly Client API key) | | **config** | [InitializationConfig](/developers/mobile-sdk/class-reference/ios/lifecycle#initializationconfig) | no | - | Object for additional initialization settings after the API key change | **Return Value:** No value is returned. ## Set Request Validation Salt --- This method sets the salt string for request validation. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.14.0 | 5.7.1 | 0.15.0 | 0.7.0 | **Declared In:** Headers/SNRSynerise.h **Class:** [Synerise](/developers/mobile-sdk/class-reference/ios/modules#synerise) **Declaration:**
```Swift static func setRequestValidationSalt(_: String?) -> Void ```
```Objective-C + (void)setRequestValidationSalt:(nullable NSString *)string ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **salt** | String | no | - | Synerise Profile salt string for request validation | **Return Value:** No value is returned. ## Set up host application type --- This method sets the Synerise SDK host application type. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.1 | 3.6.22 | - | - | **Declared In:** Headers/SNRSynerise.h **Class:** [Synerise](/developers/mobile-sdk/class-reference/ios/modules#synerise) **Declaration:**
```Swift static func setHostApplicationType(_ type: HostApplicationType) -> Void ```
```Objective-C + (void)setHostApplicationType:(SNRHostApplicationType)type ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **type** | [HostApplicationType](/developers/mobile-sdk/class-reference/ios/miscellaneous#hostapplicationtype) | yes | - | Specifies the type of host application | **Return Value:** No value is returned. ## Set host application SDK plugin version --- This method sets the Synerise SDK plugin version. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.14.6 | 5.11.0 | - | - | **Declared In:** Headers/SNRSynerise.h **Class:** [Synerise](/developers/mobile-sdk/class-reference/ios/modules#synerise) **Declaration:**
```Swift static func setHostApplicationSDKPluginVersion(_ version: String) -> Void ```
```Objective-C + (void)setHostApplicationSDKPluginVersion:(NSString *)version ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **version** | String | yes | - | Specifies the version of the Synerise SDK plugin in the host application | **Return Value:** No value is returned. ## Enable Debug Mode --- This method enables or disables console logs from Synerise SDK.
It is not recommended to use debug mode in the release version of your application.
**Declared In:** Headers/SNRSynerise.h **Class:** [Synerise](/developers/mobile-sdk/class-reference/ios/modules#synerise) **Declaration:**
```Swift static func setDebugModeEnabled(_: Bool) -> Void ```
```Objective-C + (void)setDebugModeEnabled:(BOOL)enabled; ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **enabled** | Bool | yes | - | Enables or disables console logs | **Return Value:** No value is returned. ## Enable Crash Handling --- This method enables or disables crash handling by Synerise SDK.
If set to true, Synerise SDK will send the `client.applicationCrashed` event with information about crash.
**Declared In:** Headers/SNRSynerise.h **Class:** [Synerise](/developers/mobile-sdk/class-reference/ios/modules#synerise) **Declaration:**
```Swift static func setCrashHandlingEnabled(_: Bool) -> Void ```
```Objective-C + (void)setCrashHandlingEnabled:(BOOL)enabled ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **enabled** | Bool | yes | - | Enables or disables crash handling | **Return Value:** No value is returned. ## Set Background Task identifiers --- This method sets identifiers for Background Tasks processing. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.23.0 | - | - | - |
Do not use those identifiers for other Background Tasks in your app.
**Declared In:** Headers/SNRSynerise.h **Class:** [Synerise](/developers/mobile-sdk/class-reference/ios/modules#synerise) **Declaration:**
```Swift static func setBackgroundTaskIdentifiers(_: [String]) -> Void ```
```Objective-C + (void)setBackgroundTaskIdentifiers:(NSArray *)identifiers ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **identifiers** | [String] | yes | - | Identifiers for Background Tasks registered in the host appliaction. | **Return Value:** No value is returned. # Action handling ## Types of actions in campaigns --- Campaigns can have three action types: - **OPEN APP** - This option opens your app after clicking the notification. If the app is already in the foreground, clicking the notification doesn't have any effect. - **OPEN URL** - This option opens a URL. Depending on your implementation, the link is opened in the browser by default or in your custom implementation, such as a webview in your application. - **DEEP LINKING** - This option lets you transfer users to a specific view in your app by system methods or by your custom implementation. ## Handling actions from campaigns {id=handling-actions-from-campaigns} --- You can handle actions from campaigns by using dedicated listeners and delegates: - [OnInjectorListener](/developers/mobile-sdk/listeners-and-delegates/android-listeners#on-injector-listener) for [handling actions in Android](/developers/mobile-sdk/campaigns/action-handling#handling-actions-from-campaigns-in-android) - [SyneriseDelegate](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#synerise-delegate) for [handling actions in iOS](/developers/mobile-sdk/campaigns/action-handling#handling-actions-from-campaigns-in-ios) - [InjectorListener](/developers/mobile-sdk/listeners-and-delegates/react-native-listeners#injector-listener) for [handling actions in React Native](/developers/mobile-sdk/campaigns/action-handling#handling-actions-from-campaigns-in-react-native) - [InjectorListener](/developers/mobile-sdk/listeners-and-delegates/flutter-listeners#injector-listener) for [handling actions in Flutter](/developers/mobile-sdk/campaigns/action-handling#handling-actions-from-campaigns-in-flutter) If you don't implement listener/delegate for handling actions in your customized way: - The SDK runs the default browser with the requested URL address for **OPEN URL**. - The SDK tries to handle the deep link in the host app by a system method for **DEEP LINKING**.
On iOS, deep links require special attention. The default SDK behaviour uses the [UIApplication.shared.canOpenURL(_:)](https://developer.apple.com/documentation/uikit/uiapplication/1622952-canopenurl) method. That method verifies a whitelist of deep links in `LSApplicationQueriesSchemes` key in the `\*.plist` file. Read more in [Apple documentation](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/LaunchServicesKeys.html#//apple_ref/doc/plist/info/LSApplicationQueriesSchemes).
### Android {id=handling-actions-from-campaigns-in-android} You can handle actions from each type of campaign in your own customized way by using [OnInjectorListener](/developers/mobile-sdk/listeners-and-delegates/android-listeners#on-injector-listener) methods. The [OnInAppListener](/developers/mobile-sdk/listeners-and-delegates/android-listeners#on-in-app-listener) monitors when a [JS method is used in an in-app message](/docs/campaign/in-app-messages/creating-inapp-templates/creating-inapp-template#javascript-methods-in-in-app-messages). In extended methods for handling **OPEN URL** and **DEEP LINKING**, the following parameters are available: - URL value from the action of the activity. - Deep link value from the action of the activity. - [`SyneriseSource`](/developers/mobile-sdk/class-reference/android/campaigns#synerisesource): enum that defines the kind of activity from the action that was sent. #### Configuration {id=configuration-for-handling-actions-from-campaigns-in-android} 1. Make your activity available for deep linking by including the following parameters in your AndroidManifest:
<activity
         android:name=".ui.linking.DeepLinkingActivity">
         <intent-filter>
             <action android:name="syne://test" />
             <category android:name="android.intent.category.DEFAULT" />
              <data 
                 android:scheme="syne"
                 android:host="test" />
         </intent-filter>
      </activity>
For the configuration above, the sample **deep link** parameter is `syne://test?param=value`, where: - `syne` and `test` are the scheme and host provided in the intent filter. - `parameter` is the parameter name. - `value` is the parameter value.
Your action name must be the same as your URI scheme and host.
2. **Optional**: Define an activity to be called after closing the activity that was initiated by deep linking. Provide an additional intent category:
<activity
         android:name=".ui.linking.DeepLinkingActivity"
         android:parentActivityName=".ui.linking.ParentDeepLinkingActivity">
         <intent-filter>
             <action android:name="android.intent.action.VIEW" />
             <category android:name="android.intent.category.DEFAULT" />
             <category android:name="android.intent.category.BROWSABLE" />
             <data
                 android:host="test"
                 android:scheme="syne" />
         </intent-filter>
      </activity>
If your deep link doesn't contain the `://` characters after the scheme, it is treated as a regular string key and set to the Intent's action. This means that you can set an action name (in your AndroidManifest activity's intent filter) to any string and then match it with the provided deep link.
#### Sample implementation {id=handling-open-url-deeplink-actions-in-android}
InjectorActionHandler.setOnInjectorListener(new OnInjectorListener() {
  @Override
  public boolean onOpenUrl(SyneriseSource source, String url) {
    //your implementation of OPEN URL action
    return false;
  }

  @Override
  public boolean onDeepLink(SyneriseSource source, String deepLink) {
    //your implementation of DEEP LINKING action
    return false;
  }
});
If you don't configure a custom action, the SDK applies the default behavior, as described [earlier](/developers/mobile-sdk/campaigns/action-handling#handling-actions-from-campaigns).
### iOS {id=handling-actions-from-campaigns-in-ios} You can handle actions from each type of campaign in your own customized way by using [SyneriseDelegate](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#synerise-delegate) methods. The [InjectorInAppMessageDelegate](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#injector-in-app-message-delegate) monitors when a [JS method is used in an in-app message](/docs/campaign/in-app-messages/creating-inapp-templates/creating-inapp-template#javascript-methods-in-in-app-messages). In extended methods for handling **OPEN URL** and **DEEP LINKING**, the following parameters are available: - URL value from the action of the activity. - Deep link value from the action of the activity. - [`SyneriseSource`](/developers/mobile-sdk/class-reference/ios/campaigns#synerisesource): enum that defines the kind of activity from the action that was sent. This enum replaces the deprecated [`SyneriseActivity` enum](/developers/mobile-sdk/class-reference/ios/campaigns#syneriseactivity). - `SyneriseActivityCompletionHandler`: block/closure that defines whether an activity should be hidden or not and what code should be invoked after. #### Sample implementation of OPEN URL action {id=handling-open-url-action-in-ios} This way you can, for example, check the type of activity or use your own webview to show the web page.
// MARK: - SyneriseDelegate

func snr_handledAction(url: URL, source: SyneriseSource) {
  if source == .simplePush {
    if UIApplication.shared.canOpenURL(url) {
      UIApplication.shared.openURL(url)
    }
    return
  }

  if source == .simplePush {
    //...
    return
  }
}
#### Sample implementation of DEEP LINKING action {id=handling-deeplink-action-in-ios} This way you can, for example, check the type of activity and handle your deep link in a custom way.
// MARK: - SyneriseDelegate

func snr_handledAction(deepLink: String, source: SyneriseSource) {
  if source == .inAppMessage {
    goToHelpWithId(deepLink)
    return
  }

  if source == .simplePush {
    goToMessageWithId(deepLink)
    return
  }
}
#### System method to handle deep links The code below presents a system method sample implementation to handle deep links. See [Apple Developer - UIApplication.open(_:options:completionHandler:)](https://developer.apple.com/documentation/uikit/uiapplication/1648685-open) method for more details.
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  //...
  //other methods
  func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
    let sourceApplication: String? = options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String
    let annotation: Any? = options[UIApplication.OpenURLOptionsKey.annotation]
        
    let handled: Bool = ApplicationDelegate.shared.application(app, open: url, sourceApplication: sourceApplication, annotation: annotation)
      if handled == true {
        return true
      }
        
      if url.scheme == "sample-swift" {
        applicationController.getMainCoordinator()?.didReceiveDeeplink(host: url.host!, pathComponents: url.pathComponents)
        return true
      }
        
    return false
  }
}
If you don't configure a custom action, the SDK applies the default behavior, as described [earlier](/developers/mobile-sdk/campaigns/action-handling#handling-actions-from-campaigns).
### React Native {id=handling-actions-from-campaigns-in-react-native} You can specify your custom action when a customer interacts with your simple push, banner, walkthrough, or in-app message. You can handle actions from each type of campaign in your own customized way by using [InjectorListener](/developers/mobile-sdk/listeners-and-delegates/react-native-listeners#injector-listener) methods. In listener methods for handling **OPEN URL** and **DEEP LINKING**, the following parameters are available: - URL value from the action of the activity. - Deep link value from the action of the activity. - [`SyneriseSource`](/developers/mobile-sdk/class-reference/react-native/campaigns#synerisesource): enum that defines the kind of activity from the action that was sent.
```JavaScript Synerise.Injector.setListener({ onOpenUrl: function(url, source) { //your implementation of OPEN URL action Linking.openURL(url); }, onDeepLink: function(deepLink, source) { //your implementation of DEEP LINKING action } //... //other listener's methods }); ```
If you don't configure a custom action, the SDK applies the default behavior, as described [earlier](/developers/mobile-sdk/campaigns/action-handling#handling-actions-from-campaigns).
### Flutter {id=handling-actions-from-campaigns-in-flutter} You can specify your custom action when a customer interacts with your simple push, banner, walkthrough, or in-app message. You can handle actions from each type of campaign in your own customized way by using [InjectorListener](/developers/mobile-sdk/listeners-and-delegates/flutter-listeners#injector-listener) methods. In listener methods for handling **OPEN URL** and **DEEP LINKING**, the following parameters are available: - URL value from the action of the activity. - Deep link value from the action of the activity. - [`SyneriseSource`](/developers/mobile-sdk/class-reference/flutter/campaigns#synerisesource): enum that defines the kind of activity from the action that was sent.
```Dart Synerise.injector.listener((listener) { listener.onOpenUrl = (url, source) { //your implementation of OPEN URL action }; listener.onDeepLink = (deepLink, source) { //your implementation of DEEP LINKING action }; //... //other listener's methods }); ```
If you don't configure a custom action, the SDK applies the default behavior, as described [earlier](/developers/mobile-sdk/campaigns/action-handling#handling-actions-from-campaigns).
## Universal linking --- Universal links help your users follow links to content in your app or to your website. When they open a universal link, their mobile OS checks whether any installed app is registered for that domain. If there is no configured application URL for a given path, the user stays on the website.
In order to send universal links from Synerise, you must use the **OPEN URL** action in your campaign configuration on Synerise UI.
### Android {id=universal-linking-in-android} In order to implement universal links, you need to configure them in the `AndroidManifest.xml` file in your application. Add data to your activity in order to connect a URL with a screen.
<activity
  android:name=".ui.dev.tracker.TrackerViewActivity"
  android:screenOrientation="portrait">
  <intent-filter>
      <action android:name="android.intent.action.VIEW" />
      <category android:name="android.intent.category.DEFAULT" />
      <category android:name="android.intent.category.BROWSABLE" />
      <data
          android:host="synerise.com"
          android:pathPrefix="/tracker"
          android:scheme="https" />
      <!-- note that the leading "/" is required for pathPrefix-->
  </intent-filter>
</activity>
### iOS {id=universal-linking-in-ios} To implement universal links: 1. On your app identifier, enable `Associated Domains` 2. In your Xcode project, enable `Associated Domain` (in capabilities). 3. Configure your website to host the `apple-app-site-association` file.
{
         "applinks": {
           "apps": [],
           "details": [
             {
               "appID": “<<TEAM_ID>>.com.synerise.sdk.sample",
               "paths": [
                 "*"
               ]
             }
           ]
         }
       }
4. Configure your app to handle universal links.
```Swift func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool { if userActivity.activityType == NSUserActivityTypeBrowsingWeb { let url = userActivity.webpageURL! print(url.absoluteString) // handle url and run app action that you want } return true } ```
```Objective-C - (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray * _Nullable))restorationHandler{ if ([userActivity.activityType isEqualToString: NSUserActivityTypeBrowsingWeb]) { NSURL *url = userActivity.webpageURL; NSLog(@"URL: %@", url.absoluteString); // handle url and run app action that you want } return YES; } ```
For more details, see [Apple Developer - Universal Links for Developers](https://developer.apple.com/ios/universal-links/). ## Handling actions from campaigns (older SDK versions) {id=handling-actions-from-campaigns-in-older-sdk-versions} --- ### Android (version 5.12.0 and lower) {id=legacy-handling-actions-from-campaigns-in-android} You can handle actions in your own customized way by using: - [InjectorListener](/developers/mobile-sdk/listeners-and-delegates/android-listeners#on-injector-listener) methods for simple push. - [InAppMessageListener](/developers/mobile-sdk/listeners-and-delegates/android-listeners#on-in-app-listener) methods for in-app messages.
You cannot handle actions in your own customized way for simple push. It works as default, so **OPEN URL** opens the browser and **DEEP LINKING** opens an activity associated with this deep link.
#### Configuration {id=legacy-configuration-for-handling-actions-from-campaigns-in-android} 1. Make your activity available for deep linking by including the following parameters in your AndroidManifest:
<activity
         android:name=".ui.linking.DeepLinkingActivity">
         <intent-filter>
             <action android:name="syne://test" />
             <category android:name="android.intent.category.DEFAULT" />
              <data 
                 android:scheme="syne"
                 android:host="test" />
         </intent-filter>
      </activity>
Your action name must be the same as your URI scheme and host.
2. **Optional**: Define an activity to be called after closing the activity that was initiated by deep linking. Provide an additional intent category:
<activity
         android:name=".ui.linking.DeepLinkingActivity"
         android:parentActivityName=".ui.linking.ParentDeepLinkingActivity">
         <intent-filter>
             <action android:name="android.intent.action.VIEW" />
             <category android:name="android.intent.category.DEFAULT" />
             <category android:name="android.intent.category.BROWSABLE" />
             <data
                 android:host="test"
                 android:scheme="syne" />
         </intent-filter>
      </activity>
For the configuration above, the sample **deep link** parameter is `syne://test?param=value`, where: - `syne` and `test` are the scheme and host provided in the intent filter. - `parameter` is the parameter name. - `value` is the parameter value.
Your action name must be the same as your URI scheme and host.
2. **Optional**: Define an activity to be called after closing the activity that was initiated by deep linking. Provide an additional intent category:
<activity
         android:name=".ui.linking.DeepLinkingActivity"
         android:parentActivityName=".ui.linking.ParentDeepLinkingActivity">
         <intent-filter>
             <action android:name="android.intent.action.VIEW" />
             <category android:name="android.intent.category.DEFAULT" />
             <category android:name="android.intent.category.BROWSABLE" />
             <data
                 android:host="test"
                 android:scheme="syne" />
         </intent-filter>
      </activity>
If your deep link doesn't contain the `://` characters after the scheme, it is treated as a regular string key and set to the Intent's action. This means that you can set an action name (in your AndroidManifest activity's intent filter) to any string and then match it with the provided deep link.
#### Simple Push {id=legacy-handling-simple-push-actions-in-android} The SDK handle those actions by default, so **OPEN URL** opens the browser and **DEEP LINKING** opens an activity associated with this deep link. #### In-app messages {id=legacy-handling-in-app-message-actions-in-android} The SDK allows you to handle those actions. By default, an **OPEN URL** opens the browser and **DEEP LINKING** opens an activity associated with this deep link. You can specify your custom action when a customer interacts with your in-app messages.
The callbacks presented below work only with in-app message.
If you want to implement your own behavior, refer to the following code:
```Java public static OnInAppListener NULL = new OnInAppListener() { @Override public void onHandledOpenUrl(InAppMessageData inAppMessageData) { //your implementation of OPEN URL action } @Override public void onHandledOpenDeepLink(InAppMessageData inAppMessageData) { //your implementation of DEEP LINKING action } }; ```
```Kotlin var inAppCallbacks: OnInAppListener = object : OnInAppListener() { override fun onHandledOpenUrl(inAppMessageData: InAppMessageData) { //your implementation of OPEN URL action } override fun onHandledOpenDeepLink(inAppMessageData: InAppMessageData) { //your implementation of DEEP LINKING action } } ```
- `onHandledOpenUrl(InAppMessageData)` - callback is fired when a customer interacts with the **OPEN URL** action. Returns **true** if the activity is closed after the action is executed, **false** otherwise. - `onHandledOpenDeepLink(InAppMessageData)` - callback is fired when a customer interacts with the **DEEP LINKING** action. Returns **true** if the activity is closed after the action is executed, **false** otherwise. ### React Native (version 0.17.0 and lower) {id=legacy-handling-actions-from-campaigns-in-react-native}
React Native SDK (version 0.17.0 and lower) cannot handle actions by default, you must implement it.
You can handle actions in your own customized way by using: - [InjectorListener](/developers/mobile-sdk/listeners-and-delegates/react-native-listeners#injector-listener) methods for simple push, banner and walkthrough - [InjectorInAppMessageListener](/developers/mobile-sdk/listeners-and-delegates/react-native-listeners#injector-in-app-message-listener) methods for in-app messages. #### Simple Push, Banner and Walkthrough {id=legacy-handling-simple-push-banner-walkthrough-actions-in-react-native} You can specify your custom action when a customer interacts with your simple push, banner, or walkthrough.
On Android, you cannot handle actions in your own customized way for simple push. It works as default so **OPEN URL** opens the browser and **DEEP LINKING** opens an activity.
```JavaScript Synerise.Injector.setListener({ onOpenUrl: function(url) { //your implementation of OPEN URL action Linking.openURL(url); }, onDeepLink: function(deepLink) { //your implementation of DEEP LINKING action } //... //other listener's methods }); ```
#### In-app messages {id=legacy-handling-in-app-message-actions-in-react-native} You can specify your custom action when a customer interacts with your in-app messages.
```JavaScript Synerise.Injector.setInAppMessageListener({ onOpenUrl: function(data, url) { //your implementation of OPEN URL action }, onDeepLink: function(data, deepLink) { //your implementation of DEEP LINKING action }, //... //other listener's methods }); ```
### Flutter (version 0.7.4 and lower) {id=legacy-handling-actions-from-campaigns-in-flutter}
Flutter SDK (version 0.7.4 and lower) cannot handle actions by default, you must implement it.
You can handle actions in your own customized way by using: - [InjectorListener](/developers/mobile-sdk/listeners-and-delegates/flutter-listeners#injector-listener) methods for simple push, banner and walkthrough - [InjectorInAppMessageListener](/developers/mobile-sdk/listeners-and-delegates/flutter-listeners#injector-in-app-message-listener) methods for in-app messages. #### Simple Push, Banner and Walkthrough {id=legacy-handling-simple-push-banner-walkthrough-actions-in-flutter} You can specify your custom action when a customer interacts with your simple push, banner, or walkthrough.
On Android, you cannot handle actions in your own customized way for simple push. It works as default so **OPEN URL** opens the browser and **DEEP LINKING** opens an activity.
```Dart Synerise.injector.listener((listener) { listener.onOpenUrl = (url) { //your implementation of OPEN URL action }; listener.onDeepLink = (deepLink) { //your implementation of DEEP LINKING action }; //... //other listener's methods }); ```
#### In-app messages {id=legacy-handling-in-app-message-actions-in-flutter} You can specify your custom action when a customer interacts with your in-app messages.
```Dart Synerise.injector.inAppMessageListener((listener) { listener.onOpenUrl = (data, url) { //your implementation of OPEN URL action }; listener.onDeepLink = (data, deepLink) { //your implementation of DEEP LINKING action }; //... //other listener's methods }); ```
# Profile management
**Upcoming breaking change (effective July 6, 2026):** Synerise is introducing changes to how user identifiers and UUIDs are handled. These changes may affect profiles with accented or diacritical characters in identifiers, profiles with leading or trailing whitespace in identifiers, and profiles with duplicate UUIDs. For details and recommended actions, see [Upcoming changes to handling identifiers](/docs/settings/configuration/identifier-standardization).
When the customer is authenticated with a JWT token in your application, You can retrieve or update customer details by using the SDK methods. These methods can be used only by recognized profiles, except [updating a customer account's basic information](#update-a-customer-accounts-basic-information), which can be used for anonymous profile too.
You must synchronize your data with Synerise backend after deleting an account on your side.
## Profile management methods ### Get a customer account details You can use this method to retrieve all information about a customer from Synerise. You can then present that information in the app. | OS | Method | |--------------|--------------------------------------------------------------------------------------------------------------------------------| | Android | [Client.getAccount()](/developers/mobile-sdk/method-reference/android/client-account#get-customer-account-information) | | iOS | [Client.getAccount(success:failure:)](/developers/mobile-sdk/method-reference/ios/client-account#get-customer-account-information) | | React Native | [Synerise.Client.getAccount(onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/client-account#get-customer-account-information) | | Flutter | [Synerise.client.getAccount()](/developers/mobile-sdk/method-reference/flutter/client-account#get-customer-account-information) | ### Update a customer account's basic information You can use this method to let customers update their own basic information, except for updating identifiers: `uuid`, `customId`, `email`. | OS | Method | |--------------|--------------------------------------------------------------------------------------------------------------------------------------------| | Android | [Client.updateAccountBasicInformation(accountInformation)](/developers/mobile-sdk/method-reference/android/client-account#update-customer-account-basic-information) | | iOS | [Client.updateAccountBasicInformation(context:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-account#update-customer-account-basic-information) | | React Native | [Synerise.Client.updateAccountBasicInformation(context, onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/client-account#update-customer-account-basic-information) | | Flutter | [Synerise.client.updateAccountBasicInformation(context)](/developers/mobile-sdk/method-reference/flutter/client-account#update-customer-account-basic-information) |
This method can be used by recognized and anonymous profiles.
### Update a customer account's details You can use this method to let customers update their own information, including updating identifiers: `uuid`, `customId`, `email`. | OS | Method | |--------------|--------------------------------------------------------------------------------------------------------------------------------------------| | Android | [Client.updateAccount(accountInformation)](/developers/mobile-sdk/method-reference/android/client-account#update-customer-account-information) | | iOS | [Client.updateAccount(context:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-account#update-customer-account-information) | | React Native | [Synerise.Client.updateAccount(context, onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/client-account#update-customer-account-information) | | Flutter | [Synerise.client.updateAccount(context)](/developers/mobile-sdk/method-reference/flutter/client-account#update-customer-account-information) |
This method can be used only by recognized profiles.
### Change a customer's password Separately from customer information updates, a customer may want to change their password. The default password policy is: - Minimum 6 characters - At least one uppercase letter - At least one lowercase letter - At least one digit - At least one non-alphanumeric character Passwords are PBKDF2-encrypted.
You can define the password policy in the Synerise platform (`app.synerise.com`). You can find more information about it [here](/docs/settings/tool/iam-for-apps/synerise#password-policy).
This method allows a customer to change their password, but they must provide their current password first. | OS | Method | |--------------|----------------------------------------------------------------------------------------------------------------------------------------------------| | Android | [Client.changePassword(oldPassword, password)](/developers/mobile-sdk/method-reference/android/client-account#change-customers-account-password) | | iOS | [Client.changePassword(password:oldPassword:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-account#change-customers-account-password) | | React Native | [Synerise.Client.changePassword()](/developers/mobile-sdk/method-reference/react-native/client-account#change-customers-account-password) | | Flutter | [Synerise.client.changePassword(oldPassword, password)](/developers/mobile-sdk/method-reference/flutter/client-account#change-customers-account-password) | ### Request and confirm email change These methods allow customers request and confirm the change of their email address. | OS | Method | |--------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Android | - [Client.requestEmailChange(email, password, externalToken, authId)](/developers/mobile-sdk/method-reference/android/client-account#request-email-change-for-customer-account)
- [Client.confirmEmailChange(token, newsletterAgreement)](/developers/mobile-sdk/method-reference/android/client-account#confirm-email-change-for-customer-account) | | iOS | - [Client.requestEmailChange(email:password:externalToken:authID:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-account#request-email-change-for-customer-account)
- [Client.confirmEmailChange(token:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-account#confirm-email-change-for-customer-account) | | React Native | - [Synerise.Client.requestEmailChange(email, password, onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/client-account#request-email-change-for-customer-account)
- [Synerise.Client.confirmEmailChange(token, newsletterAgreement, onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/client-account#confirm-email-change-for-customer-account) | | Flutter | n/a | ### Request and confirm phone number change These methods allow customers to request and confirm the change of their phone number. | OS | Method | |--------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Android | - [requestPhoneUpdate(phone:success:failure:)](/developers/mobile-sdk/method-reference/android/client-account#request-phone-update-on-customer-account)
- [Client.confirmPhoneUpdate(phone, confirmationCode, smsAgreement)](/developers/mobile-sdk/method-reference/android/client-account#confirm-phone-update-on-customer-account) | | iOS | - [Client.requestPhoneUpdate(phone:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-account#request-phone-update-on-customer-account)
- [Client.confirmPhoneUpdate(phone:confirmationCode:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-account#confirm-phone-update-on-customer-account) | | React Native | - [Synerise.Client.requestPhoneUpdate(phone, onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/client-account#request-phone-update-on-customer-account)
- [Synerise.Client.confirmPhoneUpdate(phone, confirmationCode, smsAgreement, onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/client-account#confirm-phone-update-on-customer-account) | | Flutter | n/a | ### Remove a customer To allow a customer to remove their account, implement the following method: | OS | Method | |--------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Android | [Client.deleteAccount(clientAuthFactor, clientIdentityProvider, authId)](/developers/mobile-sdk/method-reference/android/client-account#delete-customer-account-by-identity-provider) | | iOS | [Client.deleteAccount(clientAuthFactor:clientIdentityProvider:authID:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-account#delete-customer-account-by-identity-provider) | | React Native | [Synerise.Client.deleteAccountByIdentityProvider(clientAuthFactor, clientIdentityProvider, authID, onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/client-account#delete-customer-account-by-identity-provider) | | Flutter | [Synerise.client.deleteAccount(clientAuthFactor, identityProvider, authId)](/developers/mobile-sdk/method-reference/flutter/client-account#delete-customer-account) | # Session management ## UUID regeneration mechanism The UUID is regenerated when: * the application is reinstalled and UUID cannot be recovered * one of the UUID regeneration methods is invoked: - [Regenerate customer](#regenerate-customer) - [Regenerate customer with identifier](#regenerate-customer-with-identifier) * the destroy session method is invoked - [Destroy customer session](#destroy-customer-session) * the SDK is reinitialized by changing the **Profile API Key** with one of these methods: - [Change Profile API Key dynamically](/developers/mobile-sdk/method-reference/android/lifecycle#change-profile-api-key-dynamically) for Android SDK - [Change Profile API Key dynamically](/developers/mobile-sdk/method-reference/ios/lifecycle#change-profile-api-key-dynamically) for iOS SDK - [Change Profile API Key dynamically](/developers/mobile-sdk/method-reference/react-native/lifecycle#change-profile-api-key-dynamically) for React Native SDK - [Change Profile API Key dynamically](/developers/mobile-sdk/method-reference/flutter/lifecycle#change-profile-api-key-dynamically) for Flutter SDK * the customer is authenticated by [Simple Profile Authentication](/developers/mobile-sdk/user-identification-and-authorization/simple-authentication) with your own UUID set * the customer is authenticated by one of the following options and the **authId/authID** parameter is used: - [Simple Profile Authentication](/developers/mobile-sdk/user-identification-and-authorization/simple-authentication#authentication-methods) - [Registration as a Service](/developers/mobile-sdk/user-identification-and-authorization/simple-authentication#authentication-methods) - [OAuth](/developers/mobile-sdk/user-identification-and-authorization/oauth#authentication-methods) - [External Providers](/developers/mobile-sdk/user-identification-and-authorization/authenticate-external-providers)
the **authId/authID** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer)
* the customer is signed out with **SESSION_DESTROY** mode * the customer is removed by the [removal methods](/developers/mobile-sdk/user-identification-and-authorization/identification-and-user-management#remove-a-customer) ## Session management methods ### Refresh customer token This method refreshes the customer’s current token. | OS | Method | |--------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Android | [Client.refreshToken()](/developers/mobile-sdk/method-reference/android/client-session#refresh-customer-token) | | iOS | [Client.refreshToken()](/developers/mobile-sdk/method-reference/ios/client-session#refresh-customer-token) | | React Native | [Synerise.Client.refreshToken()](/developers/mobile-sdk/method-reference/react-native/client-session#refresh-customer-token) | | Flutter | [Synerise.client.refreshToken()](/developers/mobile-sdk/method-reference/flutter/client-session#refresh-customer-token) | ### Retrieve customer token This method retrieves the customer’s current, active token. Authentication required. | OS | Method | |--------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Android | [Client.retrieveToken()](/developers/mobile-sdk/method-reference/android/client-session#retrieve-customer-token) | | iOS | [Client.retrieveToken()](/developers/mobile-sdk/method-reference/ios/client-session#retrieve-customer-token) | | React Native | [Synerise.Client.retrieveToken()](/developers/mobile-sdk/method-reference/react-native/client-session#retrieve-customer-token) | | Flutter | [Synerise.client.retrieveToken()](/developers/mobile-sdk/method-reference/flutter/client-session#retrieve-customer-token) | ### Get current customer UUID This method retrieves the customer’s current UUID. | OS | Method | |--------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Android | [Client.getUuid()](/developers/mobile-sdk/method-reference/android/client-session#get-current-customer-uuid) | | iOS | [Client.getUUID()](/developers/mobile-sdk/method-reference/ios/client-session#get-current-customer-uuid) | | React Native | [Synerise.Client.getUUID()](/developers/mobile-sdk/method-reference/react-native/client-session#get-current-customer-uuid) | | Flutter | [Synerise.client.getUUID()](/developers/mobile-sdk/method-reference/flutter/client-session#get-current-customer-uuid) | ### Regenerate customer This method regenerates the UUID and clears the authentication token, login session, custom email, and custom identifier. This operation works only if the customer is anonymous. | OS | Method | |--------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Android | [Client.regenerateUuid()](/developers/mobile-sdk/method-reference/android/client-session#regenerate-customer) | | iOS | [Client.regenerateUUID()](/developers/mobile-sdk/method-reference/ios/client-session#regenerate-customer) | | React Native | [Synerise.Client.regenerateUUID()](/developers/mobile-sdk/method-reference/react-native/client-session#regenerate-customer) | | Flutter | [Synerise.client.regenerateUUID()](/developers/mobile-sdk/method-reference/flutter/client-session#regenerate-customer) | ### Regenerate customer with identifier This method regenerates the UUID and clears the authentication token, login session, custom email, and custom identifier. The optional clientIdentifier parameter is a seed for UUID generation. | OS | Method | |--------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Android | [Client.regenerateUuid(clientIdentifier)](/developers/mobile-sdk/method-reference/android/client-session#regenerate-customer-with-identifier) | | iOS | [Client.regenerateUUID](/developers/mobile-sdk/method-reference/ios/client-session#regenerate-customer-with-identifier) | | React Native | [Synerise.Client.regenerateUUIDWithClientIdentifier()](/developers/mobile-sdk/method-reference/react-native/client-session#regenerate-customer-with-identifier) | | Flutter | n/a | ### Destroy customer session This method clears all session data and creates a new anonymous session with a new profile UUID. | OS | Method | |--------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Android | [Client.destroySession()](/developers/mobile-sdk/method-reference/android/client-session#destroy-current-session) | | iOS | [Client.destroySession()](/developers/mobile-sdk/method-reference/ios/client-session#destroy-current-session) | | React Native | [Synerise.Client.destroySession()](/developers/mobile-sdk/method-reference/react-native/client-session#destroy-current-session) | | Flutter | [Synerise.client.destroySession()](/developers/mobile-sdk/method-reference/flutter/client-session#destroy-current-session) | # Simple Profile Authentication
**Upcoming breaking change (effective July 6, 2026):** Synerise is introducing changes to how user identifiers and UUIDs are handled. These changes may affect profiles with accented or diacritical characters in identifiers, profiles with leading or trailing whitespace in identifiers, and profiles with duplicate UUIDs. For details and recommended actions, see [Upcoming changes to handling identifiers](/docs/settings/configuration/identifier-standardization).
Simple Profile Authentication is an approach to authenticate customers once they provide their email address or custom ID. It allows for synchronization of data between Synerise and your database, ensuring consistency and an accurate profiling of customers. However, once you create a customer's profile using this authentication method, it cannot be deleted. When configuring Simple Profile Authentication, you can enable an authentication salt. It's a randomized string that your application must send with the authentication request. This provides an additional layer of security by reducing the risk of requests being made from outside the application. We strongly recommend using this option. The implementation of this authentication method is straightforward, requiring the usage of a single method. Unlike other authentication standards, it does not involve intercommunication between your application's backend and Synerise's backend. Instead, customer data is transmitted through a device for validation and authorization. Additionally, in the Synerise platform (`app.synerise.com`) you can define the following settings: - [Assignment of loyalty card](/docs/settings/tool/iam-for-apps/general#loyalty-card-assignment) - [JWT longevity](/docs/settings/tool/iam-for-apps/general#jwt-lifetime) Simple Profile Authentication proves particularly useful in scenarios when: - you have a large customer base - you don't require [OAuth](/developers/mobile-sdk/user-identification-and-authorization/oauth), which in most cases is recommended
Currently this authentication is available only for: - Android (from `5.7.1` version) - iOS (from `4.14.0` version) - React Native (from `0.15.0` version) - Flutter(from `0.7.0` version)
## Integration process --- 1. In the Synerise platform (`app.synerise.com`), go to **Settings > API keys** and create or update the Profile key. 1. In the **Permissions** section, enable the following permissions: - `SAUTH_SIMPLE_AUTH_CREATE` (the **Auth** group) - `API_PERSONAL_INFORMATION_CLIENT_READ` - `SAUTH_LOGOUT_CLIENT_CREATE` 2. In the **Simple Profile Authentication** section: 1. Enable the **Simple Profile Authentication** toggle. 2. If you want to use a salt when authenticating, enable the **Authentication salt** toggle. **Result**: A randomized salt is generated. It will need to be included in your mobile application (described further in this article).
We recommend enabling the salt. This improves the security of your requests by adding a layer of client/server authentication.
Simple Profile Authentication with salt enabled (recommended)
Simple Profile Authentication with salt enabled (recommended)
3. In the **Profile modification allowlist** section, allow modification of the following profile attributes: - `UUID` - `email` or `customId` (choose the identifier you will use in [this method](#authentication-methods))
You can learn more about creating API keys in the Synerise platform [here](/docs/settings/tool/api).
1. **If you enabled the Authentication salt**: Insert the salt into the initialization script.
It is your responsibility to ensure the secure storage of the salt in your application. We highly recommend keeping the salt encrypted.
You can find the Synerise initialization scripts in the articles below: - [Android](/developers/mobile-sdk/installation-and-configuration/android#initialization) - [iOS](/developers/mobile-sdk/installation-and-configuration/ios#initialization) - [React Native](/developers/mobile-sdk/installation-and-configuration/react-native#initialization) - [Flutter](/developers/mobile-sdk/installation-and-configuration/flutter#initialization) 2. As a sign-in method, implement [this method](#authentication-methods). In the customer's data object, `authId` (unique identifier of a customer in your data base), `email` or `customId` parameters are required. As a result of this method, the `client.simpleAuthLogin` event is generated on the activity list of a customer in the Synerise platform in **Behavioral Data Hub**.
Click here to see the event body
{ "action": "client.simpleAuthLogin", "eventUUID": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "unique": null, "createDate": 1689166104952, "label": "Simple Profile Auth client login", "params": { "ip": "xxx.xx.xxx.xx" } }
A customer logged in with this method is assigned with a Simple Profile Authentication token (a JWT) whose [longevity you can define in the Synerise platform](/docs/settings/tool/iam-for-apps/general#jwt-lifetime). 1. To check if a customer is signed in through Simple Profile Authentication, use [this method](#check-if-a-customer-is-signed-in).
To check if a customer is signed in with other authentication types, use [this method](/developers/mobile-sdk/user-identification-and-authorization/synerise-authentication#check-if-a-customer-is-signed-in)
## Authentication use cases --- | Use case | Outcome | |------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | An anonymous customer signs in to a new account | 1. Before signing in, a user is only assigned with UUID and clientId.
2. When signed in, they receive authID, and email and custom ID are assigned. The customer can update their data. | | An anonymous customer signs in to an existing account | 1. Before signing in, a user is only assigned with UUID and clientId.
2. A customer signs in to their account on the interface with their credentials (authID)
3. A customer is [merged](/developers/api/clients/merging-profiles).
4. A customer is signed in and can update their data. | | Signed-in customer signs in to a new account | 1. A customer is already recognized.
2. A customer provides new sign-in credentials and the customer is signed in to a new account (a new account is created). This customer receives authID, and email and custom ID are assigned. The customer can update their data. | | Signed-in customer signs in to an existing account | 1. A customer is already recognized.
2. A customer re-signs in to other existing account on the interface with credentials (authID).
3. A customer is signs in and can update their data. | ## Troubleshooting --- - If the `authID` value is not unique, there is a risk of generating the same UUID for various customers which results in an error. This is because the UUID is generated based on the `authID` value - An error may occur when `email` or `customId` is not unique and there is an attempt to update a customer with other's customer `email` or `customId`. ## Best practices --- - Check if a customer is signed in with [this method](#check-if-a-customer-is-signed-in). - Use the [Simple Profile Authentication method](#authentication-methods) only for logging in and updating a customer's data. - Provide a sign-out feature with [this method](#customer-sign-out). ## Authentication methods --- This method authenticates a customer with Simple Profile Authentication. | OS | Method | |--------------|-------------------------------------------------------------------------------------------------------------------------------------------| | Android | [Client.simpleAuthentication(clientData, authId)](/developers/mobile-sdk/method-reference/android/client-authentication#authenticate-customer-via-simple-profile-authentication) | | iOS | [Client.simpleAuthentication(data:authID:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-authentication#authenticate-customer-via-simple-profile-authentication) | | React Native | [Synerise.Client.simpleAuthentication(data, authID, onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/client-authentication#authenticate-customer-via-simple-profile-authentication) | | Flutter | [Synerise.client.simpleAuthentication(clientData, authId)](/developers/mobile-sdk/method-reference/flutter/client-authentication#authenticate-customer-via-simple-profile-authentication) |
**authId/authID** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
## Other methods --- ### Check if a customer is signed in This method checks if a customer is signed in through Simple Profile Authentication.
This method returns `false` if a customer is authenticated through [RaaS](/developers/mobile-sdk/user-identification-and-authorization/synerise-authentication), [oAuth](/developers/mobile-sdk/user-identification-and-authorization/oauth), [Facebook or Apple](/developers/mobile-sdk/user-identification-and-authorization/authenticate-external-providers).
| OS | Method | |--------------|-------------------------------------------------------------------------------------------------------------------------------------------| | Android | [Client.isSignedInViaSimpleAuthentication()](/developers/mobile-sdk/method-reference/android/client-authentication#check-if-a-customer-is-signed-in-via-simple-profile-authentication) | | iOS | [Client.isSignedInViaSimpleAuthentication()](/developers/mobile-sdk/method-reference/ios/client-authentication#check-if-a-customer-is-signed-in-via-simple-profile-authentication) | | React Native | [Synerise.Client.isSignedInViaSimpleAuthentication()](/developers/mobile-sdk/method-reference/react-native/client-authentication#check-if-a-customer-is-signed-in-via-simple-profile-authentication) | | Flutter | [Synerise.client.isSignedInViaSimpleAuthentication()](/developers/mobile-sdk/method-reference/flutter/client-authentication#check-if-a-customer-is-signed-in-via-simple-profile-authentication) | ### Customer sign out This method signs out the customer. The method terminates the JWT token and ends the customer session. | OS | Method | |--------------|-----------------------------------------------------------------------------------------------------------------------| | Android | - [Client.signOut()](/developers/mobile-sdk/method-reference/android/client-authentication#sign-out-customer)
- [Client.signOut(mode, signOutFromAllDevices)](/developers/mobile-sdk/method-reference/android/client-authentication#sign-out-customer-with-mode-or-from-all-devices) | | iOS | - [Client.signOut()](/developers/mobile-sdk/method-reference/ios/client-authentication#sign-out-customer)
- [Client.signOut(mode:fromAllDevices:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-authentication#sign-out-customer-with-mode-or-from-all-devices) | | React Native | - [Synerise.Client.signOut()](/developers/mobile-sdk/method-reference/react-native/client-authentication#sign-out-a-customer)
- [Synerise.Client.signOutWithMode(mode, fromAllDevices, onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/client-authentication#sign-out-customer-with-mode-or-from-all-devices) | | Flutter | [Synerise.client.signOut()](/developers/mobile-sdk/method-reference/flutter/client-authentication#sign-out-a-customer) | ## What's next --- When the customer's is signed in, you can implement [profile management methods](/developers/mobile-sdk/user-identification-and-authorization/identification-and-user-management#profile-management-methods) and [session management methods](/developers/mobile-sdk/user-identification-and-authorization/session-management). # Client ## ClientIdentityProvider **Declared In:** lib/classes/models/Client/ClientIdentityProvider.js **Declaration:**
enum ClientIdentityProvider {
  Facebook = 'FACEBOOK',
  Google = 'GOOGLE',
  Oauth = 'OAUTH',
  Synerise = 'SYNERISE',
  Unknown = 'UNKNOWN',
}
**Functions:** Converts from `ClientIdentityProvider` to string.
function ClientIdentityProviderToString(clientIdentityProvider: ClientIdentityProvider): string
--- Converts from string to `ClientIdentityProvider`.
function ClientIdentityProviderFromString(string: string): ClientIdentityProvider
--- --- ## ClientAuthContext **Declared In:** lib/classes/models/Client/ClientAuthContext.js **Related To:** [ClientAgreements](/developers/mobile-sdk/class-reference/react-native/client#clientagreements) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
interface IClientAuthContext {
  authID?: string;
  agreements?: IClientAgreements;
  attributes?: object;
}
class ClientAuthContext extends BaseModel
**Properties:** Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/react-native/client#clientagreements) | yes | nil | Object that stores all agreements of a customer | | **attributes** | object | yes | [] | Additional custom attributes of a customer | | **authID** | string | yes | [] | Optional identifier of authorization |
**authID** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Initializers:**
constructor(modelObject?: IClientAuthContext)
--- --- ## ClientSimpleAuthenticationData **Declared In:** lib/main/modules/ClientModule.js **Related To:** [ClientSex](/developers/mobile-sdk/class-reference/react-native/client#clientsex) [ClientAgreements](/developers/mobile-sdk/class-reference/react-native/client#clientagreements) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
class ClientSimpleAuthenticationData extends BaseModel
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **email** | string | yes | Customer's email | | **phone** | string | yes | Customer's phone | | **customId** | string | yes | Customer's custom ID | | **uuid** | string | yes | Customer's UUID | | **firstName** | string | yes | Customer's first name | | **lastName** | string | yes | Customer's last name | | **displayName** | string | yes | Customer's display name | | **sex** | [ClientSex](/developers/mobile-sdk/class-reference/react-native/client#clientsex) | yes | Customer's sex | | **company** | string | yes | Customer's company | | **address** | string | yes | Customer's address | | **city** | string | yes | Customer's city | | **province** | string | yes | Customer's province | | **zipCode** | string | yes | Customer's ZIP code | | **countryCode** | string | yes | Customer's country code | | **birthDate** | string | yes | Customer's birthdate | | **avatarUrl** | string | yes | Customer's avatar URL | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/react-native/client#clientagreements) | yes | Customer's agreements | | **attributes** | object | yes | Customer's attributes | --- --- ## ClientSessionEndReason **Declared In:** lib/classes/models/Client/ClientSessionEndReason.js **Declaration:**
enum ClientSessionEndReason {
  NotSpecified = 'NOT_SPECIFIED',
  SessionExpiration = 'SESSION_EXPIRATION',
  SecurityException = 'SECURITY_EXCEPTION',
  UserSignOut = 'USER_SIGN_OUT',
  SystemSignOut = 'SYSTEM_SIGN_OUT',
  SessionDestroyed = 'SESSION_DESTROYED',
  ClientRejected = 'CLIENT_REJECTED',
  UserAccountDeleted = 'USER_ACCOUNT_DELETED'
}
**Functions:** Converts from **ClientSessionEndReason** to **string**.
function ClientSessionEndReasonToString(reason: ClientSessionEndReason): string
--- Converts from **string** to **ClientSessionEndReason**.
function ClientSessionEndReasonFromString(string: string): ClientSessionEndReason
--- --- ## ClientSignOutMode **Declared In:** lib/classes/models/Client/ClientSignOutMode.js **Declaration:**
enum ClientSignOutMode {
  SignOut = 'SIGN_OUT',
  SignOutWithSessionDestroy = 'SIGN_OUT_WITH_SESSION_DESTROY'
}
**Functions:** Converts from **ClientSignOutMode** to **string**.
function ClientSignOutModeToString(mode: ClientSignOutMode): string
--- --- ## ClientAccountInformation Model representating the customer information.
This is a read-only class and it is not meant to be instantiated directly.
**Declared In:** lib/classes/models/Client/ClientAccountInformation.js **Related To:** [ClientSex](/developers/mobile-sdk/class-reference/react-native/client#clientsex) [ClientAgreements](/developers/mobile-sdk/class-reference/react-native/client#clientagreements) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
class ClientAccountInformation extends BaseModel
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **clientId** | number | no | Customer's ID | | **email** | string | no | Customer's email | | **phone** | string | yes | Customer's phone | | **customId** | string | yes | Customer's custom ID | | **uuid** | string | no | Customer's UUID | | **firstName** | string | yes | Customer's first name | | **lastName** | string | yes | Customer's last name | | **displayName** | string | yes | Customer's display name | | **sex** | [ClientSex](/developers/mobile-sdk/class-reference/react-native/client#clientsex) | no | Customer's sex | | **company** | string | yes | Customer's company | | **address** | string | yes | Customer's address | | **city** | string | yes | Customer's city | | **province** | string | yes | Customer's province | | **zipCode** | string | yes | Customer's ZIP code | | **countryCode** | string | yes | Customer's country code | | **birthDate** | string | yes | Customer's birthdate | | **lastActivityDate** | Date | no | Customer's last activity date | | **avatarUrl** | string | yes | Customer's avatar URL | | **anonymous** | boolean | no | Customer's anonymous flag | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/react-native/client#clientagreements) | no | Customer's agreements | | **attributes** | Array | yes | Customer's attributes | | **tags** | Array | yes | Customer's tags | --- --- ## ClientAccountUpdateBasicInformationContext **Declared In:** lib/classes/models/Client/ClientAccountUpdateBasicInformationContext.js **Related To:** [ClientSex](/developers/mobile-sdk/class-reference/react-native/client#clientsex) [ClientAgreements](/developers/mobile-sdk/class-reference/react-native/client#clientagreements) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
class ClientAccountUpdateBasicInformationContext extends BaseModel
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **firstName** | string | yes | Customer's first name | | **lastName** | string | yes | Customer's last name | | **displayName** | string | yes | Customer's display name | | **sex** | [ClientSex](/developers/mobile-sdk/class-reference/react-native/client#clientsex) | yes | Customer's sex | | **phone** | string | yes | Customer's phone number | | **company** | string | yes | Customer's company | | **address** | string | yes | Customer's address | | **city** | string | yes | Customer's city | | **province** | string | yes | Customer's province | | **zipCode** | string | yes | Customer's ZIP code | | **countryCode** | string | yes | Customer's country code | | **birthDate** | string | yes | Customer's birthdate | | **avatarUrl** | string | yes | Customer's avatar URL | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/react-native/client#clientagreements) | no | Customer's agreements | | **attributes** | object | yes | Customer's attributes | **Initializers:**
constructor(modelObject?: IClientAccountUpdateBasicInformationContext)
--- --- ## ClientAccountUpdateContext **Declared In:** lib/classes/models/Client/ClientAccountUpdateContext.js **Related To:** [ClientSex](/developers/mobile-sdk/class-reference/react-native/client#clientsex) [ClientAgreements](/developers/mobile-sdk/class-reference/react-native/client#clientagreements) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
class ClientAccountUpdateContext extends BaseModel
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **email** | string | yes | Customer's email | | **customId** | string | yes | Customer's custom ID | | **uuid** | string | yes | Customer's UUID | | **firstName** | string | yes | Customer's first name | | **lastName** | string | yes | Customer's last name | | **displayName** | string | yes | Customer's display name | | **sex** | [ClientSex](/developers/mobile-sdk/class-reference/react-native/client#clientsex) | yes | Customer's sex | | **phone** | string | yes | Customer's phone number | | **company** | string | yes | Customer's company | | **address** | string | yes | Customer's address | | **city** | string | yes | Customer's city | | **province** | string | yes | Customer's province | | **zipCode** | string | yes | Customer's ZIP code | | **countryCode** | string | yes | Customer's country code | | **birthDate** | string | yes | Customer's birthdate | | **avatarUrl** | string | yes | Customer's avatar URL | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/react-native/client#clientagreements) | no | Customer's agreements | | **attributes** | object | yes | Customer's attributes | **Initializers:**
constructor(modelObject?: IClientAccountUpdateContext)
--- --- ## ClientAccountRegisterContext **Declared In:** lib/classes/models/Client/ClientAccountRegisterContext.js **Related To:** [ClientSex](/developers/mobile-sdk/class-reference/react-native/client#clientsex) [ClientAgreements](/developers/mobile-sdk/class-reference/react-native/client#clientagreements) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
class ClientAccountRegisterContext extends BaseModel
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **email** | string | no | Customer's email | | **password** | string | no | Customer's password | | **firstName** | string | yes | Customer's first name | | **lastName** | string | yes | Customer's last name | | **customId** | string | yes | Customer's custom ID | | **sex** | [ClientSex](/developers/mobile-sdk/class-reference/react-native/client#clientsex) | yes | Customer's sex | | **phone** | string | yes | Customer's phone | | **company** | string | yes | Customer's company | | **address** | string | yes | Customer's address | | **city** | string | yes | Customer's city | | **province** | string | yes | Customer's province code | | **zipCode** | string | yes | Customer's ZIP code | | **countryCode** | string | yes | Customer's country code | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/react-native/client#clientagreements) | yes | Customer's agreements | | **attributes** | object | yes | Customer's attributes | **Initializers:**
constructor(email: string, password: string, modelObject?: IClientAccountRegisterContext)
--- --- ## ClientSex **Declared In:** lib/classes/models/Client/ClientSex.js **Declaration:**
enum ClientSex {
  NotSpecified = 'NOT_SPECIFIED',
  Male = 'MALE',
  Female = 'FEMALE',
  Other = 'OTHER'
}
**Functions:** Converts from **ClientSex** to **string**.
function ClientSexToString(clientSex: ClientSex): string
--- Converts from **string** to **ClientSex**.
function ClientSexFromString(string: string): ClientSex
--- --- ## ClientAgreements **Declared In:** lib/classes/models/Client/ClientAgreements.js **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
interface IClientAgreements {
  email?: boolean;
  sms?: boolean;
  push?: boolean;
  bluetooth?: boolean;
  rfid?: boolean;
  wifi?: boolean;
}
class ClientAgreements extends BaseModel
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **email** | boolean | no | Email agreement | | **sms** | boolean | no | SMS agreement | | **push** | boolean | no | Push notifications agreement | | **bluetooth** | boolean | no | Bluetooth agreement | | **rfid** | boolean | no | RFID agreement | | **wifi** | boolean | no | WIFI agreement | **Initializers:**
constructor()
constructor(modelObject?: IClientAgreements)
--- --- ## Token **Declared In:** lib/classes/models/Token/Token.js **Related To:** [TokenOrigin](/developers/mobile-sdk/class-reference/react-native/client#tokenorigin) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
class Token extends BaseModel
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **tokenString** | string | no | Token as a raw string | | **tokenOrigin** | [TokenOrigin](/developers/mobile-sdk/class-reference/react-native/client#tokenorigin) | no | Token's origin | | **expirationDate** | string | yes | Token's expiration time | --- --- ## TokenOrigin **Declared In:** lib/classes/models/Token/TokenOrigin.js **Declaration:**
enum TokenOrigin {
  Unknown = 'UNKNOWN',
  Synerise = 'SYNERISE',
  Facebook = 'FACEBOOK',
  Oauth = 'OAUTH',
}
**Functions:** Converts from **TokenOrigin** to **string**.
function TokenOriginToString(tokenOrigin: TokenOrigin): string
--- Converts from **string** to **TokenOrigin**.
function TokenOriginFromString(string: string): TokenOrigin
--- --- ## Removed symbols --- ### ClientOAuthAuthenticationContext{#clientoauthauthenticationcontext} | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.11 | 3.6.13 | 0.9.12 | n/a | | Deprecated in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | n/a | **Declared In:** lib/classes/models/Client/ClientOAuthAuthenticationContext.js **Related To:** [ClientAgreements](/developers/mobile-sdk/class-reference/react-native/client#clientagreements) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
interface IClientOAuthAuthenticationContext {
  authID?: string;
  agreements?: IClientAgreements;
  attributes?: object;
}
class ClientOAuthAuthenticationContext extends BaseModel
**Properties:** Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/react-native/client#clientagreements) | yes | nil | Object that stores all agreements of a customer | | **attributes** | object | yes | [] | Additional custom attributes of a customer | **Initializers:**
constructor()
constructor(modelObject?: IClientOAuthAuthenticationContext)
--- --- ### ClientFacebookAuthenticationContext{#clientfacebookauthenticationcontext} | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.3.8 | 3.3.0 | 0.9.7 | n/a | | Deprecated in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | n/a | **Declared In:** lib/classes/models/Client/ClientOAuthAuthenticationContext.js **Related To:** [ClientAgreements](/developers/mobile-sdk/class-reference/react-native/client#clientagreements) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
interface IClientOAuthAuthenticationContext {
  authID?: string;
  agreements?: IClientAgreements;
  attributes?: object;
}
class ClientOAuthAuthenticationContext extends BaseModel
**Properties:** Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/react-native/client#clientagreements) | yes | nil | Object that stores all agreements of a customer | | **attributes** | object | yes | [] | Additional custom attributes of a customer | **Initializers:**
constructor()
constructor(modelObject?: IClientOAuthAuthenticationContext)
--- --- ### ClientAppleSignInAuthenticationContext{#clientapplesigninauthenticationcontext} | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.11 | n/a | 0.9.12 | n/a | | Deprecated in: | 3.7.6 | n/a | 0.9.19 | n/a | | Removed in: | 5.0.0 | n/a | 1.0.0 | n/a | **Declared In:** lib/classes/models/Client/ClientAppleSignInAuthenticationContext.js **Related To:** [ClientAgreements](/developers/mobile-sdk/class-reference/react-native/client#clientagreements) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
interface IClientAppleSignInAuthenticationContext {
  authID?: string;
  agreements?: IClientAgreements;
  attributes?: object;
}
class ClientAppleSignInAuthenticationContext extends BaseModel
**Properties:** Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/react-native/client#clientagreements) | yes | nil | Object that stores all agreements of a customer | | **attributes** | object | yes | [] | Additional custom attributes of a customer | **Initializers:**
constructor()
---
constructor(modelObject?: IClientAppleSignInAuthenticationContext)
# Modules ### BaseModule Main module abstract class for inheriting classes. **Declared In:** lib/main/modules/BaseModule.js **Declaration:**
class BaseModule
--- --- ### Settings The module for managing the SDK settings. **Declared In:** lib/main/modules/SettingsModule.js **Inherits From:** [Module](/developers/mobile-sdk/class-reference/react-native/modules#basemodule) **Declaration:**
class SettingsModule extends Module
**Properties:** | Property | Type | Description | | --- | --- | --- | | **sdk** | ISettingsOptions | [General settings](/developers/mobile-sdk/settings#general) - This group contains options related to the general functioning of mobile SDK | | **notifications** | ISettingsOptions | [Notifications settings](/developers/mobile-sdk/settings#notifications) - This group contains options related to push notifications | | **tracker** | ISettingsOptions | [Tracker](/developers/mobile-sdk/settings#tracker) - This group contains options related to tracking the customer activities in a mobile application | | **inAppMessaging** | ISettingsOptions | [In-app messaging](/developers/mobile-sdk/settings#in-app-messaging) - This group contains options related to the [in-app messages](/docs/campaign/in-app-messages) feature | | **injector** | ISettingsOptions | [Injector](/developers/mobile-sdk/settings#injector) - This group contains options related to displaying [campaigns](/docs/campaign/Mobile) | **Note:** Learn more about settings [here](/developers/mobile-sdk/settings) --- --- ### Notifications The module for managing notifications. **Declared In:** lib/main/modules/NotificationsModule.js **Inherits From:** [Module](/developers/mobile-sdk/class-reference/react-native/modules#basemodule) **Declaration:**
class NotificationsModule extends Module
**Methods:** This method sets an object for Notifications listener methods.
public setListener(listener: INotificationsListener)
[(Click for more details)](/developers/mobile-sdk/listeners-and-delegates/react-native-listeners#notifications-listener) --- This method passes the Firebase Token to Synerise for notifications.
public registerForNotifications(registrationToken: string, mobileAgreement: boolean | null, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/campaigns#register-for-push-notifications) --- This method verifies if a notification was sent by Synerise.
public isSyneriseNotification(payload: object): boolean
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/campaigns#check-if-push-notification-is-from-synerise) --- This method verifies if a notification’s sender is Synerise and if the notification is a Simple Push campaign
public isSyneriseSimplePush(payload: object): boolean
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/campaigns#check-if-push-notification-is-a-simple-push-campaign) --- This method verifies if a notification’s sender is Synerise and if the notification is a Banner campaign.
public isSyneriseBanner(payload: object): boolean
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/campaigns#check-if-push-notification-is-a-banner-campaign) - **REMOVED in version 1.0.0** --- This method verifies if a notification's sender is Synerise and if the notification is a Silent Command.
public isSilentCommand(payload: object): boolean
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/campaigns#check-if-push-notification-is-a-silent-command) --- This method verifies if a notification's sender is Synerise and if the notification is a Silent SDK Command.
public isSilentSDKCommand(payload: object): boolean
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/campaigns#check-if-push-notification-is-a-silent-sdk-command) --- This method verifies if a notification is encrypted.
public isNotificationEncrypted(payload: object): boolean
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/campaigns#check-if-push-notification-is-encrypted) --- This method decrypts the notification payload.
public decryptNotification(payload: object): object | null
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/campaigns#decrypt-push-notification) --- This method handles a notification payload with a user interaction and starts activity.
public handleNotification(payload: object, actionIdentifier: string | null)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/campaigns#handle-synerise-push-notification) --- --- --- ### Client The module for managing customer account data, registration, and authorization. **Declared In:** lib/main/modules/ClientModule.js **Related To:** [ClientAccountRegisterContext](/developers/mobile-sdk/class-reference/react-native/client#clientaccountregistercontext) [ClientIdentityProvider](/developers/mobile-sdk/class-reference/react-native/client#clientidentityprovider) [ClientAuthContext](/developers/mobile-sdk/class-reference/react-native/client#clientauthcontext) [ClientOAuthAuthenticationContext](/developers/mobile-sdk/class-reference/react-native/client#clientoauthauthenticationcontext) [ClientFacebookAuthenticationContext](/developers/mobile-sdk/class-reference/react-native/client#clientfacebookauthenticationcontext) [ClientAppleSignInAuthenticationContext](/developers/mobile-sdk/class-reference/react-native/client#clientapplesigninauthenticationcontext) [ClientAccountInformation](/developers/mobile-sdk/class-reference/react-native/client#clientaccountinformation) [ClientAccountUpdateContext](/developers/mobile-sdk/class-reference/react-native/client#clientaccountupdatecontext) [Token](/developers/mobile-sdk/class-reference/react-native/client#token) **Inherits From:** [Module](/developers/mobile-sdk/class-reference/react-native/modules#basemodule) **Declaration:**
class ClientModule extends Module
**Methods:** This method sets an object for customer's state listener methods.
public setClientStateChangeListener(listener: IClientStateChangeListener)
[(Click for more details)](/developers/mobile-sdk/listeners-and-delegates/react-native-listeners#client-state-listener) --- This method registers a new customer with an email, password, and optional data.
public registerAccount(context: ClientAccountRegisterContext, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-authentication#register-customer-account) --- This method confirms a customer account with the confirmation token.
public confirmAccountActivation(token: string, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-authentication#confirm-customer-account-activation) --- This method activates a customer with email.
public requestAccountActivation(email: string, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-authentication#request-customer-account-activation) --- This method signs a customer in to obtain a JSON Web Token (JWT) which can be used in subsequent requests.
public signIn(email: string, password: string, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-authentication#sign-in-a-customer) --- This method signs a customer in to obtain a JSON Web Token (JWT) which can be used in subsequent requests.
public signInConditionally(email: string, password: string, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-authentication#sign-in-a-customer-conditionally) --- This method authenticates a customer with OAuth, Facebook, Google, Apple, or Synerise.
public authenticate(token: string, provider: ClientIdentityProvider, context: ClientAuthContext, onSuccess: (authResult: ClientConditionalAuthResult) => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-authentication#authenticate-customer-by-identityprovider) --- This method authenticates a customer with OAuth, Facebook, Google, Apple, or Synerise.
public authenticateConditionally(token: string, provider: ClientIdentityProvider, context: ClientAuthContext, onSuccess: (authResult: ClientConditionalAuthResult) => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-authentication#authenticate-customer-conditionally-by-identityprovider) --- This method authenticates a customer with OAuth.
public authenticateByOAuth(accessToken: string, context: ClientOAuthAuthenticationContext, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-authentication#authenticate-customer-by-oauth-with-registration) - **REMOVED in version 1.0.0** --- This method authenticates a customer with OAuth.
public authenticateByOAuthIfRegistered(accessToken: string, authID: string | null, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-authentication#authenticate-customer-by-oauth-without-registration) - **REMOVED in version 1.0.0** --- This method authenticates a customer with Facebook.
public authenticateByFacebook(facebookToken: string, context: ClientFacebookAuthenticationContext, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-authentication#authenticate-customer-by-facebook-with-registration) - **REMOVED in version 1.0.0** --- This method authenticates a customer with Facebook.
public authenticateByFacebookIfRegistered(facebookToken: string, authID: string | null, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-authentication#authenticate-customer-by-facebook-without-registration) - **REMOVED in version 1.0.0** --- This method authenticates a customer with Sign In With Apple.
public authenticateByAppleSignIn(identityToken: string, context: ClientAppleSignInAuthenticationContext, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-authentication#authenticate-customer-by-sign-in-with-apple-with-registration) - **REMOVED in version 1.0.0** --- This method authenticates a customer with Sign In With Apple.
public authenticateByAppleSignInIfRegistered(identityToken: string, authID: string, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-authentication#authenticate-customer-by-sign-in-with-apple-without-registration) - **REMOVED in version 1.0.0** --- This method authenticates a customer with Simple Profile Authentication.
public simpleAuthentication(data: ClientSimpleAuthenticationData, authID: string, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-authentication#authenticate-customer-via-simple-profile-authentication) --- This method checks if a customer is signed in (via Synerise Authentication - RaaS, OAuth, Facebook, Apple).
public isSignedIn(): boolean
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-authentication#check-if-a-customer-is-signed-in-via-raas-oauth-facebook-apple) --- This method checks if a customer is signed in (via Simple Profile Authentication).
public isSignedInViaSimpleAuthentication(): boolean
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-authentication#check-if-a-customer-is-signed-in-via-simple-profile-authentication) --- This method signs out a customer out.
public signOut()
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-authentication#sign-out-a-customer) --- This method signs out a customer out with a chosen mode and Determines if the method should sign out all devices
public signOutWithMode(mode: ClientSignOutMode, fromAllDevices: boolean, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-authentication#sign-out-customer-with-mode-or-from-all-devices) --- This method refreshes the customer’s current token.
public refreshToken(onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-session#refresh-customer-token) --- This method retrieves the customer’s current, active token.
public retrieveToken(onSuccess: (token: Token) => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-session#retrieve-customer-token) --- This method retrieves the customer’s current UUID.
public getUUID(): string
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-session#get-current-customer-uuid) --- This method regenerates the UUID and clears the authentication token, login session, custom email, and custom identifier.
public regenerateUUID()
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-session#regenerate-customer) --- This method regenerates the UUID and clears the authentication token, login session, custom email, and custom identifier.
public regenerateUUIDWithClientIdentifier(clientIdentifier: string)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-session#regenerate-customer-with-identifier) --- This method destroys the session completely.
public destroySession()
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-session#destroy-current-session) --- This method gets a customer’s account information.
public getAccount(onSuccess: (clientAccountInformation: ClientAccountInformation) => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-account#get-customer-account-information) --- This method updates a customer’s account’s basic information (without identification data: uuid, customId, email).
public updateAccountBasicInformation(context: ClientAccountUpdateBasicInformationContext, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-account#update-customer-account-basic-information) --- This method updates a customer’s account information.
public updateAccount(context: ClientAccountUpdateContext, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-account#update-customer-account-information) --- This method requests a customer’s password reset with email.
public requestPasswordReset(email: string, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-account#request-password-reset-for-customer-account) --- This method confirm a customer’s password reset with the new password and token provided by password reset request.
public confirmPasswordReset(password: string, token: string, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-account#confirm-password-reset-for-customer-account) --- This method changes a customer’s password.
public changePassword(oldPassword: string, newPassword: string, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-account#change-customers-account-password) --- This method requests a customer's email change.
public requestEmailChange(email: string, password: string | null, externalToken: string | null, authID: string | null, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-account#request-email-change-for-customer-account) --- This method confirms an email change.
public confirmEmailChange(token: string, newsletterAgreement: boolean, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-account#confirm-email-change-for-customer-account) --- Requests a customer's phone update. A confirmation code is sent to the phone number.
public requestPhoneUpdate(phone: string, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-account#request-phone-update-on-customer-account) --- This method confirms a phone number update. This action requires the new phone number and confirmation code as parameters.
public confirmPhoneUpdate(phone: string, confirmationCode: string, smsAgreement: boolean, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-account#confirm-phone-update-on-customer-account) --- This method requests a customer's account registration process with the PIN code.
public requestAccountActivationByPin(email: string, onSuccess: () => void, onError: (error: Error)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-authentication#request-customer-account-activation-by-pin) --- This method confirms a customer's account registration process with the PIN code.
public confirmAccountActivationByPin(pinCode: string, email: string, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-authentication#confirm-customer-account-activation-by-pin) --- This method deletes a customer's account.
public deleteAccountByIdentityProvider(clientAuthFactor: string, clientIdentityProvider: ClientIdentityProvider, authID: string | null, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-account#delete-customer-account-by-identity-provider) --- This method deletes a customer's account.
public deleteAccount(password: string, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-account#delete-customer-account) --- This method deletes a customer's account by OAuth.
public deleteAccountByOAuth(password: string, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-account#delete-customer-account-by-oauth) --- This method deletes a customer's account by Facebook.
public deleteAccountByFacebook(password: string, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/client-account#delete-customer-account-by-facebook) --- --- ### Tracker The module for sending event tracking data to Synerise backend. Tracking is performed by creating pre-defined or custom event objects and sending these to Synerise. It also includes automatic event interception by the Auto-Tracking feature. **Declared In:** lib/main/modules/TrackerModule.js **Related To:** [Event](/developers/mobile-sdk/class-reference/react-native/events#event) **Inherits From:** [Module](/developers/mobile-sdk/class-reference/react-native/modules#basemodule) **Declaration:**
class TrackerModule extends Module
**Methods:** This method sets a custom identifier in the parameters of every event.
public setCustomIdentifier(identifier: string)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/tracking#set-custom-identifier-for-events) --- This method sets a custom email in the parameters of every event.
public setCustomEmail(email: string)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/tracking#set-custom-email-for-events) --- This method sends an event.
public send(event: Event)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/tracking#send-event) --- This method forces sending the events from the queue to the server.
public flushEvents(onSuccess: () => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/tracking#flush-events-from-tracker) --- --- ### Injector The module for handling Synerise UI activities such as walkthrough, banner, simple push, and so on. **Declared In:** lib/main/modules/InjectorModule.js **Inherits From:** [Module](/developers/mobile-sdk/class-reference/react-native/modules#basemodule) **Declaration:**
class InjectorModule extends Module
**Methods:** Closes an in-app message and sends an `inApp.discard` event. Usage examples: - Closing a top bar or bottom bar when the user taps outside the in-app area. - Automatically dismissing messages when navigating away from a screen. - Controlling in-app visibility based on app logic for a smoother user experience.
public closeInAppMessage(campaignHash: string)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/campaigns#close-in-app-message) --- This method sets an object for Injector listener methods.
public setListener(listener: IInjectorListener)
[(Click for more details)](/developers/mobile-sdk/listeners-and-delegates/react-native-listeners#injector-listener) --- This method sets an object for in-app message listener methods.
public setInAppMessageListener(listener: IInjectorInAppMessageListener)
[(Click for more details)](/developers/mobile-sdk/listeners-and-delegates/react-native-listeners#injector-in-app-message-listener) --- This method sets if banners should be shown or not.
public setShouldBannerPresentFlag(shouldPresentBanner: boolean)
--- This method fetches banners set for mobile campaigns and caches the valid ones.
public fetchBanners(onSuccess: (banners: Array<Object>) => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/campaigns#fetch-banners) - **REMOVED in 0.12.0** --- This method provides valid banners directly from SDK cache.
public getBanners(): Array<Object>
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/campaigns#get-banners) - **REMOVED in 0.12.0** --- This method shows a banner immediately.
public showBanner(banner: Object, markPresented: boolean)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/campaigns#show-banner) - **REMOVED in 0.12.0** --- This method fetches a walkthrough.
public getWalkthrough()
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/campaigns#get-walkthrough) - **REMOVED in version 1.0.0** --- This method shows a walkthrough when it is loaded.
public showWalkthrough()
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/campaigns#show-walkthrough) - **REMOVED in version 1.0.0** --- This method checks if a walkthrough is loaded.
public isWalkthroughLoaded(): boolean
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/campaigns#check-if-walkthrough-is-loaded) - **REMOVED in version 1.0.0** --- This method checks if the walkthrough is unique compared to the previous one.
public isLoadedWalkthroughUnique(): boolean
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/campaigns#check-if-is-loaded-walkthrough-unique) - **REMOVED in version 1.0.0** --- --- ### Promotions The module for handling promotions and vouchers from Synerise SDK. **Declared In:** lib/main/modules/PromotionsModule.js **Related To:** [PromotionResponse](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotionresponse) [Promotion](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotion) [AssignVoucherResponse](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#assignvoucherresponse) [VoucherCodesResponse](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#vouchercodesresponse) **Inherits From:** [Module](/developers/mobile-sdk/class-reference/react-native/modules#basemodule) **Declaration:**
class PromotionsModule extends Module
**Methods:** This method retrieves all available promotions that are defined for a customer.
public getAllPromotions(onSuccess: (promotionResponse: PromotionResponse) => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/promotions#get-all-promotions-of-a-customer) --- This method retrieves promotions that match the parameters defined in an API query.
public getPromotions(apiQuery: PromotionsApiQuery, onSuccess: (promotionResponse: PromotionResponse) => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/promotions#get-promotions-with-query-parameters) --- This method retrieves the promotion with the specified UUID.
public getPromotionByUUID(uuid: string, onSuccess: (promotion: Promotion) => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/promotions#get-promotion-by-uuid) --- This method retrieves the promotion with the specified code.
public getPromotionByCode(code: string, onSuccess: (promotion: Promotion) => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/promotions#get-promotion-by-code) --- This method activates the promotion with the specified UUID.
public activatePromotionByUUID(uuid: string, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/promotions#activate-promotion-by-uuid) --- This method activates the promotion with the specified code.
public activatePromotionByCode(code: string, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/promotions#activate-promotion-by-code) --- This method activates promotions with a code or with UUID in a batch.
public activatePromotionsBatch(promotionsIdentifiers: Array<PromotionIdentifier>, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/promotions#activate-promotions-in-a-batch) --- This method deactivates the promotion with the specified UUID.
public deactivatePromotionByUUID(uuid: string, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/promotions#deactivate-promotion-by-uuid) --- This method deactivates the promotion with the specified code.
public deactivatePromotionByCode(code: string, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/promotions#deactivate-promotion-by-code) --- This method deactivates promotions with a code or with UUID in a batch.
public deactivatePromotionsBatch(promotionsIdentifiers: Array<PromotionIdentifier>, onSuccess: () => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/promotions#deactivate-promotions-in-a-batch) --- This method retrieves an assigned voucher code or assigns a voucher from a pool identified by UUID to the profile. When the voucher is assigned for the first time, a [voucherCode.assigned](/docs/assets/events/event-reference/loyalty#vouchercodeassigned) event is produced.
public getOrAssignVoucher(poolUuid: string, onSuccess: (assignVoucherRespone: AssignVoucherResponse) => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/promotions#get-or-assign-voucher-from-pool) --- This method assigns a voucher from a pool identified by UUID to the profile. A [voucherCode.assigned](/docs/assets/events/event-reference/loyalty#vouchercodeassigned) event is produced.
public assignVoucherCode(poolUuid: string, onSuccess: (assignVoucherRespone: AssignVoucherResponse) => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/promotions#assign-voucher-code-from-pool) --- This method retrieves voucher codes for a customer.
public getAssignedVoucherCodes(onSuccess: (voucherCodesResponse: VoucherCodesResponse) => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/promotions#get-voucher-codes-assigned-to-customer) --- --- ### Content The module for handling content from Synerise backend such as documents, recommendations, and so on. **Declared In:** lib/main/modules/ContentModule.js **Related To:** [RecommendationResponse](/developers/mobile-sdk/class-reference/react-native/recommendations-and-documents#recommendationresponse) [Recommendation](/developers/mobile-sdk/class-reference/react-native/recommendations-and-documents#recommendation) [DocumentApiQuery](/developers/mobile-sdk/class-reference/react-native/recommendations-and-documents#documentapiquery) [ScreenViewApiQuery](/developers/mobile-sdk/class-reference/react-native/miscellaneous#screenviewapiquery) [BrickworksApiQuery](/developers/mobile-sdk/class-reference/react-native/miscellaneous#brickworksapiquery) **Inherits From:** [Module](/developers/mobile-sdk/class-reference/react-native/modules#basemodule) **Declaration:**
class ContentModule extends Module
**Methods:** --- This method generates the document assigned to a slug.
public getDocument(slug: string, onSuccess: (document: object) => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/content#get-document) - **REMOVED in version 1.0.0** --- This method generates the document that is defined for the provided slug.
public generateDocument(slug: string, onSuccess: (document: Document) => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/content#generate-document) --- This method generates the document that is defined for the provided slug.
public generateDocumentWithApiQuery(slug: string, onSuccess: (document: Document) => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/content#generate-document-with-query-parameters) --- This method generates documents that are defined for parameters provided in the query object.
public getDocuments(apiQuery: DocumentsApiQuery, onSuccess: (documents: Array<object>) => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/content#get-documents) - **REMOVED in version 1.0.0** --- This method generates recommendations that are defined for the options provided. The recommendations are generated by using a document with an insert. For instructions, see ["Displaying AI recommendations > With documents and screen views"](/developers/mobile-sdk/displaying-recommendations/documents).
public getRecommendations(options: RecommendationOptions, onSuccess: (recommendationResponse: RecommendationResponse) => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/content#get-recommendations) - **REMOVED in version 1.0.0** --- This method generates recommendations that are defined for the options provided. The recommendations are generated by using a document with an insert. For instructions, see ["Displaying AI recommendations > With documents and screen views"](/developers/mobile-sdk/displaying-recommendations/documents).
public getRecommendationsV2(options: RecommendationOptions, onSuccess: (recommendationResponse: RecommendationResponse) => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/content#get-recommendations-v2) --- This method generates the customer's highest-priority screen view campaign.
public getScreenView(onSuccess: (screenViewResponse: ScreenViewResponse) => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/content#get-screen-view) - **REMOVED in version 1.0.0** --- This method generates a customer's highest-priority screen view campaign from the feed with the provided feed slug.
public generateScreenView(slug: String, onSuccess: (screenView: ScreenView) => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/content#generate-screen-view) --- This method generates a customer's highest-priority screen view campaign from the feed with the provided feed slug.
public generateScreenViewWithApiQuery(apiQuery: ScreenViewApiQuery, onSuccess: (screenView: ScreenView) => void, onError: (error: Error) => void)
[(Click for more details)](/developers/mobile-sdk/method-reference/react-native/content#generate-screen-view-with-query-parameters) --- # Synerise Authentication
**Upcoming breaking change (effective July 6, 2026):** Synerise is introducing changes to how user identifiers and UUIDs are handled. These changes may affect profiles with accented or diacritical characters in identifiers, profiles with leading or trailing whitespace in identifiers, and profiles with duplicate UUIDs. For details and recommended actions, see [Upcoming changes to handling identifiers](/docs/settings/configuration/identifier-standardization).
Synerise Authentication (also known as Registration as a Service) provides customer identity and account management features native to Synerise without any need for third party systems. To use RaaS, implement a set of methods listed below in your application.
For a full list of available methods, see the [method reference section](/developers/mobile-sdk/method-reference).
Additionally, in the Synerise platform (`app.synerise.com`) you can define the following settings: - [Registration mode](/docs/settings/tool/iam-for-apps/synerise#registration-mode) - [Assignment of loyalty card](/docs/settings/tool/iam-for-apps/general#loyalty-card-assignment) - [JWT longevity](/docs/settings/tool/iam-for-apps/general#jwt-lifetime) - [Custom ID overwriting](/docs/settings/tool/iam-for-apps/general#custom-id-overwriting) - [External ID overwriting](/docs/settings/tool/iam-for-apps/general#external-id-overwriting) - [Enabling email address change through a link in the email](/docs/settings/tool/iam-for-apps/general#email-address-change) - [Templates of email notifications](/docs/settings/tool/iam-for-apps/general#templates) such as account confirmation, email change request, PIN confirmation, and so on. - [Password policy](/docs/settings/tool/iam-for-apps/synerise#password-policy) ## Registration methods --- ### Register new customers This method lets you pass all customer information along with any agreements and attributes at once. The primary unique identifier used by Synerise is the email address. However, you may also define a `customId` as a unique identifier. You can read more [here](/docs/settings/configuration/non-unique-emails). | OS | Method | |--------------|-------------------------------------------------------------------------------------------------------------------------------------------| | Android | [Client.registerAccount(registerClient)](/developers/mobile-sdk/method-reference/android/client-authentication#register-customer-account) | | iOS | [Client.registerAccount(context:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-authentication#register-customer-account) | | React Native | [Synerise.Client.registerAccount(context, onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/client-authentication#register-customer-account) | | Flutter | [Synerise.client.registerAccount(context)](/developers/mobile-sdk/method-reference/flutter/client-authentication#register-customer-account) | Depending on backend configuration at Synerise, the registration may or may not require email confirmations/ The following registration behaviors are supported: | Name | Description | |-----------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Automatic | The account is ready to use right after registration, no confirmations are required. Customer has the attribute `snrs_email_confirmed` set to `false`. | | Email Confirmation Required | The account is ready to use right after registration, but the email confirmation is required. The confirmation sets `snrs_email_confirmed` to `true`. | | Email Activation Required | An activation email is sent and the account cannot be used until the address is confirmed. Activation also means that `snrs_email_confirmed` is set to `true`. | | PIN Activation Required | An activation email is sent and the account cannot be used until the PIN sent in the email is provided ([Android](/developers/mobile-sdk/method-reference/android/client-authentication#request-customer-account-activation-by-pin), [iOS](/developers/mobile-sdk/method-reference/ios/client-authentication#request-customer-account-activation-by-pin), [React Native](/developers/mobile-sdk/method-reference/react-native/client-authentication#request-customer-account-activation-by-pin)). | ### Request customer account activation by email This method requests sending an email with a URL that confirms the registration and activates the account. | OS | Method | |--------------|-----------------------------------------------------------------------------------------------------------------------| | Android | [Client.requestAccountActivation(email)](/developers/mobile-sdk/method-reference/android/client-authentication#request-customer-account-activation) | | iOS | [Client.requestAccountActivation(email:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-authentication#request-customer-account-activation) | | React Native | [Synerise.Client.requestAccountActivation(email, onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/client-authentication#request-customer-account-activation) | | Flutter | [Synerise.client.requestAccountActivation(email)](/developers/mobile-sdk/method-reference/flutter/client-authentication#request-customer-account-activation) | ### Confirm customer account activation This method confirms a customer account with the confirmation token. | OS | Method | |--------------|-----------------------------------------------------------------------------------------------------------------------| | Android | [Client.confirmAccountActivation(token)](/developers/mobile-sdk/method-reference/android/client-authentication#confirm-customer-account-activation) | | iOS | [Client.confirmAccountActivation(token:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-authentication#confirm-customer-account-activation) | | React Native | [Synerise.Client.confirmAccountActivation(token, onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/client-authentication#confirm-customer-account-activation) | | Flutter | [Synerise.client.confirmAccountActivation(token)](/developers/mobile-sdk/method-reference/flutter/client-authentication#confirm-customer-account-activation) | ### Request customer account by pin This method requests sending an email to a customer with the PIN code needed during account registration process. | OS | Method | |--------------|-----------------------------------------------------------------------------------------------------------------------| | Android | [Client.requestAccountActivationByPin(email)](/developers/mobile-sdk/method-reference/android/client-authentication#request-customer-account-activation-by-pin) | | iOS | [Client.requestAccountActivationByPin(email:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-authentication#request-customer-account-activation-by-pin) | | React Native | [Synerise.Client.requestAccountActivationByPin(email, onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/client-authentication#request-customer-account-activation-by-pin) | | Flutter | n/a | ### Confirm customer account activation by pin This method requires a customer to enter a PIN code during account registration process sent through an email. | OS | Method | |--------------|-----------------------------------------------------------------------------------------------------------------------| | Android | [Client.confirmAccountActivationByPin(pinCode, email)](/developers/mobile-sdk/method-reference/android/client-authentication#confirm-customer-account-activation-by-pin) | | iOS | [Client.confirmAccountActivationByPin(pinCode:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-authentication#confirm-customer-account-activation-by-pin) | | React Native | [Synerise.Client.confirmAccountActivationByPin(pinCode, onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/client-authentication#confirm-customer-account-activation-by-pin) | | Flutter | n/a | ## Authentication methods --- Once a customer is registered, you can let users log in by implementing this method. After a successful log-in, the application receives a JWT token. The SDK refreshes that token while a customer is using the application and events are being sent (auto-refresh occurs only when the token is still valid).
Token longevity can be changed in the Synerise application. You can learn how to do it in [this article](/docs/settings/tool/iam-for-apps/general#jwt-lifetime).
| OS | Method | |--------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Android | - [Client.signIn()](/developers/mobile-sdk/method-reference/android/client-authentication#sign-in-a-customer)
- [Client.signInConditionally](/developers/mobile-sdk/method-reference/android/client-authentication#sign-in-a-customer-conditionally) | | iOS | - [Client.signIn(email:password:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-authentication#sign-in-a-customer)
- [Client.signInConditionally(email:password:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-authentication#sign-in-a-customer-conditionally) | | React Native | [Synerise.Client.signIn()](/developers/mobile-sdk/method-reference/react-native/client-authentication#sign-in-a-customer)
[Synerise.Client.signInConditionally](/developers/mobile-sdk/method-reference/react-native/client-authentication#sign-in-a-customer-conditionally) | | Flutter | [Synerise.client.signIn()](/developers/mobile-sdk/method-reference/flutter/client-authentication#sign-in-a-customer) | ## Other methods --- ### Check if a customer is signed in This method checks if a customer is signed in through oAuth, Facebook, Sign in with Apple, or RaaS.
This method returns `false` if a customer is authenticated through [Simple Profile Authentication](/developers/mobile-sdk/user-identification-and-authorization/simple-authentication).
| OS | Method | |--------------|-------------------------------------------------------------------------------------------------------------------------------------------| | Android | [Client.isSignedIn()](/developers/mobile-sdk/method-reference/android/client-authentication#check-if-a-customer-is-signed-in-via-raas-oauth-facebook-apple) | | iOS | [Client.isSignedIn()](/developers/mobile-sdk/method-reference/ios/client-authentication#check-if-a-customer-is-signed-in-via-raas-oauth-facebook-apple) | | React Native | [Synerise.Client.isSignedIn()](/developers/mobile-sdk/method-reference/react-native/client-authentication#check-if-a-customer-is-signed-in-via-raas-oauth-facebook-apple) | | Flutter | [Synerise.client.isSignedIn()](/developers/mobile-sdk/method-reference/flutter/client-authentication#check-if-a-customer-is-signed-in-via-raas-oauth-facebook-apple) | ### Customer sign out This method signs out the customer. The method terminates the JWT token and ends the customer session. | OS | Method | |--------------|-----------------------------------------------------------------------------------------------------------------------| | Android | - [Client.signOut()](/developers/mobile-sdk/method-reference/android/client-authentication#sign-out-customer)
- [Client.signOut(mode, signOutFromAllDevices)](/developers/mobile-sdk/method-reference/android/client-authentication#sign-out-customer-with-mode-or-from-all-devices) | | iOS | - [Client.signOut()](/developers/mobile-sdk/method-reference/ios/client-authentication#sign-out-customer)
- [Client.signOut(mode:fromAllDevices:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-authentication#sign-out-customer-with-mode-or-from-all-devices) | | React Native | - [Synerise.Client.signOut()](/developers/mobile-sdk/method-reference/react-native/client-authentication#sign-out-a-customer)
- [Synerise.Client.signOutWithMode(mode, fromAllDevices, onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/client-authentication#sign-out-customer-with-mode-or-from-all-devices) | | Flutter | [Synerise.client.signOut()](/developers/mobile-sdk/method-reference/flutter/client-authentication#sign-out-a-customer) | ## What's next --- When the customer's account is registered and/or they are signed in, you can implement [profile management methods](/developers/mobile-sdk/user-identification-and-authorization/identification-and-user-management#profile-management-methods) and [session management methods](/developers/mobile-sdk/user-identification-and-authorization/session-management). # iOS ## Method reference - iOS # Simple push ## Overview --- Simple push is a standard push notification interacting with your operating system. If an app is not active (was closed or running in the background) in the moment of receiving simple push, it appears in the notification center. When a customer clicks the notification, they are taken to the application and a simple push is presented. If an app is active, the simple push is presented right away. Read more about creating and testing simple push [here](/docs/campaign/Mobile/creating-mobile-push).
Additionaly, iOS and React Native (iOS) simple push campaigns support two types of Rich Media extensions: - [Single Media](#single-media) - [Image Carousel](#image-carousel)
Add support for Rich Media Push Notifications in your application. See [Rich Media in Push Notifications](/developers/mobile-sdk/configuring-push-notifications/ios#rich-media-in-push-notifications) section.
## Configuration --- Simple push campaign is served by push notifications. See: - [Configuring push notifications - Android](/developers/mobile-sdk/configuring-push-notifications/android) - [Configuring push notifications - iOS](/developers/mobile-sdk/configuring-push-notifications/ios) - [Configuring push notifications - React Native](/developers/mobile-sdk/configuring-push-notifications/react-native) - [Configuring push notifications - Flutter](/developers/mobile-sdk/configuring-push-notifications/flutter) Additionally, check possible available configuration options in the [Settings](/developers/mobile-sdk/settings#notifications). ## Events generated by simple push --- For information about events generated by simple push, see the [event reference](/docs/assets/events/event-reference/mobile-push). ## Handling actions from simple push --- Handling main actions from campaigns depends on campaign type and operating system and it is described [here](/developers/mobile-sdk/campaigns/action-handling). ## Additional in-app alert when simple push is received ---
This feature is available only in iOS SDK, React Native SDK (iOS) and Flutter SDK (iOS).
The iOS SDK displays an additional alert in the application after a simple push campaign is received and it is configured with [OPEN_URL](/developers/mobile-sdk/campaigns/action-handling#types-of-actions-in-campaigns) or [DEEP_LINKING](/developers/mobile-sdk/campaigns/action-handling#types-of-actions-in-campaigns) action. This alert is displayed in the middle of the screen with content from the native notification payload. This is the default behavior. You can disable it in the SDK Settings - [Enable/disable notification alerts](/developers/mobile-sdk/settings#enabledisable-notification-in-app-alerts).
Simple Push campaign with in-app alert
Simple Push campaign with in-app alert
## Payload ---
{
  "data": {
    "issuer": "Synerise",
    "message-type": "static-content",
    "content-type": "simple-push",
    "content": {
      "notification": {
        "title": "Finish your purchase",
        "body": "You have in your basket Road Bike RS-500 with discount for \"New Users\". Comeback to the basket and complete your purchase.",
        "icon": "https://upload.snrcdn.net/f2afa4d4d7af216196047d1f7f0613f22a50a8c8/default/origin/7eba69de2d4dab3a9388b9d72abd91eb.png",
        "action": {
          "type": "OPEN_APP"
        }
      },
      "buttons": [
        {
          "identifier": "check",
          "text": "Check",
          "action": {
            "type": "OPEN_URL",
            "item": "http://www.synerise.com"
          }
        },
        {
          "identifier": "view_similar",
          "text": "View similar",
          "action": {
            "type": "OPEN_URL",
            "item": "http://www.synerise.com"
          }
        }
      ],
      "campaign": {
        "hash_id": "196211cc-af48-4064-8860-aad986449322",
        "variant_id": 3175648,
        "type": "Mobile push",
        "title": "SimplePush For Docs"
      }
    }
  }
}
The example presents a simple push campaign with a main action, image, and two clickable buttons connected to actions. All user interactions are tracked by Synerise Android SDK.
The look of your push notifications may vary depending on Android versions.
Expanded simple push notification
Simple push notification presented on Android 10
{
  "aps": {
    "alert": {
      "title": "Complete your purchase",
      "body": "Your basket contains Road Bike RS-500 with a discount for \"New Users\". Come and complete your purchase!"
    },
    "sound": "default",
    "category": "[YOUR CATEGORY]",
    "mutable-content": 1
  },
  "issuer": "Synerise",
  "message-type": "dynamic-content",
  "content-type": "simple-push",
  "content": {
    "campaign": {
      "variant_id": 3175648,
      "hash_id": "196211cc-af48-4064-8860-aad986449322",
      "type": "Simple Push",
      "title": "Simple Push campaign for docs"
    },
    "notification": {
      "action": {
        "type": "OPEN_APP"
      }
    },
    "buttons": [{
      "identifier": "check",
      "text": "Check",
      "action": {
        "type": "OPEN_URL",
        "item": "http://www.synerise.com"
      }
    },
    {
      "identifier": "view_similiar",
      "text": "View similiar",
      "action": {
        "type": "OPEN_URL",
        "item": "http://www.synerise.com"
      }
    }]
  }
}
The example presents a simple push campaign with a main action and two clickable buttons connected to actions. All user interactions are tracked by Synerise iOS SDK.
Simple Push campaign
Simple push campaign presented on iOS 14
The look of your push notifications may vary depending on iOS versions.
## Single Media ---
This feature is available only in iOS SDK.
It is a simple push campaign with an image that can be seen after expanding the notification. ### Payload {id=single-media-payload}
{
  "aps": {
    "alert": {
      "title": "Complete your purchase",
      "body": "Your basket contains Road Bike RS-500 with a discount for \"New Users\". Come and complete your purchase!"
    },
    "sound": "default",
    "category": "synerise.notifications.category.single-media",
    "mutable-content": 1
  },
  "issuer": "Synerise",
  "message-type": "dynamic-content",
  "content-type": "simple-push",
  "content": {
    "campaign": {
      "variant_id": 3175648,
      "hash_id": "196211cc-af48-4064-8860-aad986449322",
      "type": "Simple Push",
      "title": "Simple Push campaign for docs"
    },
    "notification": {
      "action": {
        "type": "OPEN_APP"
      }
    },
    "buttons": [{
      "identifier": "check",
      "text": "Check",
      "action": {
        "type": "OPEN_URL",
        "item": "http://www.synerise.com"
      }
    },
    {
      "identifier": "view_similiar",
      "text": "View similiar",
      "action": {
        "type": "OPEN_URL",
        "item": "http://www.synerise.com"
      }
    }],
    "rich-media": {
      "type": "single-image",
      "single-image": {
        "image": "https://upload.snrcdn.net/f2afa4d4d7af216196047d1f7f0613f22a50a8c8/default/origin/7eba69de2d4dab3a9388b9d72abd91eb.png"
      }
    }
  }
}
The example presents a simple push campaign with a main action, single image, and two clickable buttons connected to actions. All user interactions are tracked by Synerise iOS SDK.
Simple Push campaign
Simple push campaign presented on iOS 14
The look of your push notifications may vary depending on iOS versions.
## Image Carousel ---
This feature is available only in iOS SDK.
It is a simple push campaign with images that can be seen and swiped after expanding the notification. ### Payload {id=image-carousel-payload}
{
    "aps":
    {
        "alert":
        {
            "title": "Complete your purchase",
            "body": "Your basket contains Road Bike RS-500 with a discount for \"New Users\". Come and complete your purchase!"
        },
        "sound": "default",
        "badge": "5",
        "category": "synerise.notifications.category.carousel"
    },
    "issuer": "Synerise",
    "message-type": "dynamic-content",
    "content-type": "simple-push",
    "content":
    {
        "campaign":
        {
            "variant_id": 3175648,
            "hash_id": "196211cc-af48-4064-8860-aad986449322",
            "type": "Simple Push",
            "title": "Simple Push campaign for docs"
        },
        "notification":
        {
            "action":
            {
                "type": "OPEN_URL",
                "item": "https://www.synerise.com"
            }
        },
        "rich-media":
        {
            "type": "carousel",
            "carousel":
            {
                "orientation": "PORTRAIT",
                "items":
                [
                    {
                        "caption": "Check!",
                        "subcaption": "Road Bike RS-500",
                        "image": "https://upload.snrcdn.net/f2afa4d4d7af216196047d1f7f0613f22a50a8c8/default/origin/7eba69de2d4dab3a9388b9d72abd91eb.png",
                        "url": "https://www.synerise.com"
                    },
                    {
                        "caption": "Check!",
                        "subcaption": "Road Bike RS-500",
                        "image": "https://upload.snrcdn.net/f2afa4d4d7af216196047d1f7f0613f22a50a8c8/default/origin/7eba69de2d4dab3a9388b9d72abd91eb.png",
                        "url": "https://www.synerise.com"
                    }
                ]
            }
        }
    }
}
Click to see an example push with image carousel

The example presents a simple push campaign with a main action and carousel of images with connected actions. All user interactions are tracked by Synerise iOS SDK.

The look of your push notifications may vary depending on iOS versions.

Simple Push campaign
Simple Push campaign presented on iOS 14
# iOS ## Installation and configuration (iOS) In this article, you will find out how to install and initialize the Synerise SDK in an iOS application. While performing the actions from this guide, keep the presented order.
The [Settings](/developers/mobile-sdk/settings#pre-initialization-settings) article contains additional information about SDK behaviors you may need prior to configuration.
If you want to find out what kind of benefits you can get from integrating with mobile SDK, go [here](/developers/mobile-sdk/overview). ### Requirements --- You need: * Access to a [workspace](/docs/settings/workspace) * A Profile [API Key](/docs/settings/tool/api#adding-api-keys) When creating the API key, use allowlisting or denylisting to only allow the events you intend to use. * One of the following dependency managers: - [CocoaPods](https://guides.cocoapods.org/using/getting-started.html) - CocoaPods is a dependency manager for iOS projects. - [Carthage](https://github.com/Carthage/Carthage) - Carthage is a simple, decentralized dependency manager for iOS projects. - [Swift Package Manager](https://www.swift.org/package-manager/) - Swift Package Manager (SPM) is a dependency manager built into Xcode. * Recommended environment: - Xcode 16 - iOS SDK 18 * Target deployment: - **iOS 13.0+** for SDK versions 5.0.0 and higher - **iOS 9.0+** for SDK versions lower than 5.0.0
Bitcode is not supported in SDK version 5.0.0 and higher. Xcode ignores bitcode.
#### Apple Frameworks The Synerise SDK references the following Apple frameworks: - `Foundation.framework` - `UIKit.framework` - `CoreGraphics.framework` - `SystemConfiguration.framework` - `MobileCoreServices.framework` - `CoreTelephony.framework` - `Security.framework` - `CommonCrypto.framework` - `WebKit.framework` - `UserNotifications.framework` #### 3rd Party Frameworks - [AFNetworking (fork)](https://github.com/AFNetworking/AFNetworking) - [TrustKit](https://github.com/datatheorem/TrustKit) - [Aspects](https://github.com/steipete/Aspects) ### Installation --- #### CocoaPods 1. Add CocoaPods dependency to **Synerise SDK** into your `Podfile`:
use_frameworks!

       target YOUR_PROJECT_TARGET do
         pod 'SyneriseSDK'
       end
2. Execute the following shell command in the directory depending on your project configuration:
pod repo update  
       pod install
#### Swift Package Manager (SPM) 1. Go to Xcode project’s settings and navigate to the Package Dependencies tab. 2. Below the packages list, click the Add button. 3. Enter the URL of Synerise SDK repository **(https://github.com/Synerise/synerise-ios-sdk)** in the search text field. 4. Under the Dependency Rule section, select the SDK version. Finally, click **Add Package**. 5. Select the package that best suits your needs and click **Add Package**. #### Carthage 1. Add the Carthage dependency to **Synerise SDK** into your `Cartfile`:
github "synerise/ios-sdk"
2. Execute the shell command in directory depending on your project configuration:
carthage update
3. Go to Xcode project target's **General** section. 4. In Finder, open `/Carthage/Build/iOS` 5. Drag `SyneriseSDK.framework` to **Embedded Binaries**. 6. Make sure the **Copy items if needed** option is selected. 7. Click **Finish**. ### Initialization --- #### Setting up 1. Go to Xcode project target's **General** section. 2. Find the **Other Linker Flags** property and add the ***-ObjC*** flag. 2. If you are going to use push notifications: 1. Go to `Info.plist` 2. Add a row for **Required background mode** with the following array type value: `App downloads content in response to push notifications` or add the code below directly:
<key>UIBackgroundModes</key>
           <array>
               <string>remote-notification</string>
           </array>
3. If you are going to use HTTP addresses (instead of only HTTPS), change the allowlist domains in your app by adding configuration to `Info.plist` in one of the following ways: - Add configured domain/domains that you need.
<key>NSAppTransportSecurity</key>
          <dict>
              <key>NSExceptionDomains</key>
              <dict>
                  <key>yourdomain.com</key>
                  <dict>
                  <!--Include to allow subdomains-->
                  <key>NSIncludesSubdomains</key>
                  <true/>
                  <!--Include to allow HTTP requests-->
                  <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
                  <true/>
                  <!--Include to specify minimum TLS version-->
                  <key>NSTemporaryExceptionMinimumTLSVersion</key>
                  <string>TLSv1.1</string>
                  </dict>
              </dict>
          </dict>
- Give permission for all domains.
<key>NSAppTransportSecurity</key>
          <dict>
              <key>NSAllowsArbitraryLoads</key><true/>
          </dict>
#### Importing Synerise SDK Import the **Synerise SDK** header into the files that contain code relating to SDK.
```Swift import SyneriseSDK ```
```Objective-C #import ```
In Objective-C, you can include it in your Prefix Header (PCH) and Synerise SDK will be imported to all files automatically.
#### Basic initialization Initialize Synerise SDK and provide the [Profile API Key](/docs/settings/tool/api). You may initialize it wherever you want and when you need.
```Swift Synerise.initialize(apiKey: "YOUR_PROFILE_API_KEY") // 1 Synerise.setDebugModeEnabled(false) // 2 Synerise.setCrashHandlingEnabled(true) // 3 Synerise.setDelegate(self) // 4 ```
```Objective-C [SNRSynerise initializeWithApiKey:@"YOUR_PROFILE_API_KEY"]; // 1 [SNRSynerise setDebugModeEnabled:NO]; // 2 [SNRSynerise setCrashHandlingEnabled:YES]; // 3 [SNRSynerise setDelegate:self]; // 4 ```
Basic methods you need: 1. [`Synerise.initialize(apiKey:)`](/developers/mobile-sdk/method-reference/ios/lifecycle#initialization) - Initializes Synerise SDK. 2. [`Synerise.setDebugModeEnabled(_:)`](/developers/mobile-sdk/method-reference/ios/lifecycle#enable-debug-mode) - Enables debug mode for Synerise SDK. See [Debug mode](/developers/mobile-sdk/installation-and-configuration/ios#debug-mode) section for more information. 3. [`Synerise.setCrashHandlingEnabled(_:)`](/developers/mobile-sdk/method-reference/ios/lifecycle#enable-crash-handling) - Enables crash handling. Synerise SDK sends a crash event automatically when an uncaught exception occurs. 4. [`Synerise.setDelegate(_:)`](/developers/mobile-sdk/method-reference/ios/lifecycle#set-synerise-delegate)- Sets delegate to handle main actions from Synerise SDK. See [`SyneriseDelegate`](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#synerise-delegate) section for more information. #### Initialization with custom API environment To change API base URL for on-premise installations, use the following initialization method:
```Swift Synerise.initialize(apiKey: "YOUR_PROFILE_API_KEY", baseUrl: "YOUR_API_BASE_URL") ```
```Objective-C [SNRSynerise initializeWithClientApiKey:@"YOUR_PROFILE_API_KEY" andBaseUrl:@"YOUR_API_BASE_URL"]; ```
#### Advanced initialization This is an example of advanced initialization with: - custom API base URL for on-premise installations - request validation salt configured - debug mode enabled - crash handling enabled - most of the settings options available - main delegate [`SyneriseDelegate`](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#synerise-delegate) - client's state delegate [`ClientStateDelegate`](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#client-state-delegate)
We highly recommend to configure settings when Synerise SDK is initialized, before invoking the [`Synerise.initialize(apiKey:)`](/developers/mobile-sdk/method-reference/ios/lifecycle#initialization) method. See [Settings](/developers/mobile-sdk/settings) section for more details about settings options.
Secure sensitive keys (for example, `apiKey` and `requestValidationSalt`) with mechanisms like string obfuscation or encryption.
You can find more information about all [Synerise iOS SDK delegates here](/developers/mobile-sdk/listeners-and-delegates/ios-delegates).
```Swift Synerise.settings.sdk.enabled = true Synerise.settings.sdk.appGroupIdentifier = "YOUR_APP_GROUP_IDENTIFIER" Synerise.settings.sdk.keychainGroupIdentifier = "YOUR_KEYCHAIN_GROUP_IDENTIFIER" Synerise.settings.sdk.minTokenRefreshInterval = 1800 Synerise.settings.sdk.shouldDestroySessionOnApiKeyChange = false Synerise.settings.notifications.enabled = true Synerise.settings.notifications.disableInAppAlerts = true Synerise.settings.notifications.encryption = false Synerise.settings.tracker.autotracking.enabled = true Synerise.settings.tracker.autotracking.mode = AutoTrackMode.Fine Synerise.settings.tracker.autotracking.excludedClasses = [SampleViewController.self] Synerise.settings.tracker.autotracking.excludedViewTags = [0, 1, 2] Synerise.settings.tracker.tracking.enabled = true Synerise.settings.tracker.minBatchSize = 10 Synerise.settings.tracker.maxBatchSize = 100 Synerise.settings.tracker.autoFlushTimeout = 5.0 Synerise.settings.tracker.autoTracking.mode = .fine Synerise.settings.tracker.locationAutomatic = true Synerise.settings.injector.automatic = true Synerise.initialize(apiKey: "YOUR_PROFILE_API_KEY", baseUrl: "YOUR_API_BASE_URL") Synerise.setRequestValidationSalt("YOUR_REQUEST_VALIDATION_SALT") Synerise.setDebugModeEnabled(false) Synerise.setCrashHandlingEnabled(true) Synerise.setDelegate(self) Client.setClientStateDelegate(self) ```
```Objective-C SNRSynerise.settings.sdk.enabled = @YES; SNRSynerise.settings.sdk.appGroupIdentifier = @"YOUR_APP_GROUP_IDENTIFIER"; SNRSynerise.settings.sdk.keychainGroupIdentifier = @"YOUR_KEYCHAIN_GROUP_IDENTIFIER"; SNRSynerise.settings.sdk.minTokenRefreshInterval = 1800; SNRSynerise.settings.sdk.shouldDestroySessionOnApiKeyChange = NO; SNRSynerise.settings.notifications.enabled = YES; SNRSynerise.settings.notifications.disableInAppAlerts = YES; SNRSynerise.settings.notifications.encryption = NO; SNRSynerise.settings.tracker.autotracking.enabled = YES; SNRSynerise.settings.tracker.autotracking.mode = SNRTrackerAutoTrackModeFine; SNRSynerise.settings.tracker.autotracking.excludedClasses = [SampleViewController.class]; SNRSynerise.settings.tracker.autotracking.excludedViewTags = [@0, @2, @3]; SNRSynerise.settings.tracker.tracking.enabled = YES; SNRSynerise.settings.tracker.minBatchSize = 10; SNRSynerise.settings.tracker.maxBatchSize = 100; SNRSynerise.settings.tracker.autoFlushTimeout = 5.0; SNRSynerise.settings.tracker.autoTracking.mode = SNRTrackerAutoTrackModeFine; SNRSynerise.settings.tracker.locationAutomatic = YES; SNRSynerise.settings.injector.automatic = YES; [SNRSynerise initializeWithApiKey:@"YOUR_PROFILE_API_KEY" andBaseUrl:@"YOUR_API_BASE_URL"]; [SNRSynerise setRequestValidationSalt:@"YOUR_REQUEST_VALIDATION_SALT"]; [SNRSynerise setDebugModeEnabled:NO]; [SNRSynerise setCrashHandlingEnabled:YES]; [SNRSynerise setDelegate:self]; [SNRClient setClientStateDelegate:self]; ```
#### Initialization process During initialization, the library starts and when it is ready or an error occurs, the SDK notifies you. When the delegate method is called, Synerise is ready to use.
```Swift // MARK: - SyneriseDelegate // This method is called when the Synerise SDK is initialized. func snr_initialized() { //... } // This method is called when an error occurs while initializing the Synerise SDK. func snr_initializationError(error: Error) { //... } ```
```Objective-C #pragma mark - SNRSyneriseDelegate // This method is called when the Synerise SDK is initialized. - (void)SNR_initialized { //... } // This method is called when an error occurs while initializing the Synerise SDK. - (void)SNR_initializationError:(NSError *)error { //... } ```
### Debug Mode --- You can enable debug logs for Synerise SDK by method [`Synerise.setDebugModeEnabled(_:)`](/developers/mobile-sdk/method-reference/ios/lifecycle#enable-debug-mode).
Do not use Debug Mode in a release version of your application.
```Swift Synerise.setDebugModeEnabled(true) // Enables logging for all modules ```
```Objective-C [SNRSynerise setDebugModeEnabled:YES]; // Enables logging for all modules ```
You can receive some logs about: - **Core**: push notifications - **Tracker**: auto-tracked events, declarative events, sending process - **Client**: customer state, authorization - **Injector**: campaigns, UI - **Promotions**: promotions, vouchers - **Content**: content widget, documents, recommendations ### Background Tasks --- [Background Tasks](https://developer.apple.com/documentation/backgroundtasks) is a mechanism to schedule and run code in the background to keep your app up to date. Synerise supports using Background Tasks since SDK version **4.23.0**. You can pass configured identifiers for Synerise SDK by using the [`Synerise.setBackgroundTaskIdentifiers(_:)`](/developers/mobile-sdk/method-reference/ios/lifecycle#set-background-task-identifiers) method. The identifiers that you are going to pass have to be configured properly in the host app. ##### Benefits Currently, the SDK uses Background Tasks only to refresh the registration token for Push Notifications every 20 days. In these situations, the SDK invokes the [snr_registerForPushNotificationsIsNeeded(origin:)](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#synerise-delegate-register-for-push-notifications-is-needed-by-origin) method or [snr_registerForPushNotificationsIsNeeded()](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#synerise-delegate-register-for-push-notifications-is-needed) method. ##### Setting up To configure Background Tasks in your app: 1. Go to Xcode project's target's **Signing & Capabilities** section. 2. In the **Background Modes** capability (you may need to add it), enable **Background fetch** and **Background processing**. 3. Go to `Info.plist`. 4. Add a row with the following array type value: `Permitted background task scheduler identifiers`. 5. Add string identifiers, each as a separate item to declare possible Background Tasks identifiers in your app. 6. Pass these Background Tasks identifiers to SDK by using the [`Synerise.setBackgroundTaskIdentifiers(_:)`](/developers/mobile-sdk/method-reference/ios/lifecycle#set-background-task-identifiers) method. You must invoke the method **BEFORE** your app is launched (before the `application(_ application:didFinishLaunchingWithOptions launchOptions:)` method finishes). Sample `\*.plist` configuration for Background Tasks:
Sample *.plist configuration for Background Tasks
Sample *.plist configuration for Background Tasks
Example code for passing Background Tasks identifiers to the SDK:
```Swift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // ... Synerise.setBackgroundTaskIdentifiers(["YOUR_BACKGROUND_TASK_IDENTIFIER"]) return true } ```
```Objective-C - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // ... [SNRSynerise setBackgroundTaskIdentifiers:@[@"YOUR_BACKGROUND_TASK_IDENTIFIER"]]; return YES; } ```
The method's parameter is an array because of possible future purposes.
Do not use those identifiers for other Background Tasks in your app.
Documentation is available at [Apple Developer - Using background tasks to update your app](https://developer.apple.com/documentation/uikit/app_and_environment/scenes/preparing_your_ui_to_run_in_the_background/using_background_tasks_to_update_your_app). **IMPORTANT: To configure Background Tasks properly, you must set `SyneriseDelegate` before the SDK initialization.**
```Swift Synerise.setDelegate(self) Synerise.initialize(apiKey: "YOUR_PROFILE_API_KEY") // ... ```
```Objective-C [SNRSynerise setDelegate:self]; [SNRSynerise initializeWithApiKey:@"YOUR_PROFILE_API_KEY"]; // ... ```
### Privacy manifest --- From **1 May 2024**, Apple requires you to add a privacy manifest. It's a file in your project that describes your reason and method for collecting data. Third-party frameworks that track data should have a privacy manifest. When you create the application privacy report, these privacy manifest files are automatically aggregated into a single file. Synerise supports privacy manifests since SDK version **4.17.0**. When you use an SDK version older than **4.17.0**, refer to the Synerise API usage requirements defined below when creating an Apple privacy manifest. ##### APIs usage | API | Reason | Description | | --- | --- | --- | | User defaults APIs | **CA92.1**
**1C8F.1** | Synerise uses User Defaults to persist the SDK data and share them between the application and extensions | ##### Tracking Synerise does not track any data that is protected by the [App Tracking Transparency](https://developer.apple.com/documentation/apptrackingtransparency) framework. ##### Collected Data | Data type | Value | Purpose | | --- | --- | --- | | User ID | **NSPrivacyCollectedDataTypeUserID** | Analytics, Product Personalization | | Other usage data | **NSPrivacyCollectedDataTypeOtherUsageData** | Analytics, Product Personalization, App Functionality | | Product interaction | **NSPrivacyCollectedDataTypeProductInteraction** | Analytics | | Advertising data | **NSPrivacyCollectedDataTypeAdvertisingData** | Other Purposes, App Functionality | | Crash data | **NSPrivacyCollectedDataTypeOtherUserContent** | Analytics | ### Warnings and limitations --- Be careful with keychain deletion operations due to the possibility of deleting Synerise data. All the SDK library data keys are named `snr.[KEY_NAME]`. # iOS ## Class reference - iOS # iOS ## Configuring push notifications (iOS) ### Prerequisites --- - Configure handling push notifications in your application. See [Apple Developer - Notifications](https://developer.apple.com/notifications/). - Google Firebase Cloud Messaging is necessary to handle [Mobile Campaigns](/docs/campaign/Mobile) sent from Synerise. 1. Follow the instructions in [Firebase - Get Started on iOS](https://firebase.google.com/docs/storage/ios/start). 2. Integrate the Firebase with Synerise. See [Integration](/docs/settings/tool/firebase) section. ### Set up Firebase Cloud Messaging for Synerise SDK --- Extend the Firebase Messaging Delegate so our SDK can receive the Firebase token that is required to deliver push notifications from Synerise:
```Swift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { FirebaseApp.configure() Messaging.messaging().delegate = self if #available(iOS 10, *) { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in if granted { DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } guard let fcmToken = Messaging.messaging().fcmToken else { return } let mobilePushAgreement = true // true or false, should depend on device permissions and customer's agreement in the application Client.registerForPush(registrationToken:fcmToken, mobilePushAgreement:mobilePushAgreement, success: { (success) in // success }) { (error) in // failure } } } else { let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) } } // MARK: - MessagingDelegate func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) { if let registrationToken = fcmToken { let mobilePushAgreement = true // true or false, should depend on device permissions and customer's agreement in the application Client.registerForPush(registrationToken:registrationToken, mobilePushAgreement:mobilePushAgreement, success: { (success) in // success }) { (error) in // failure } } } ```
```Objective-C - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [FIRApp configure]; [FIRMessaging messaging].delegate = self; if (@available(iOS 10, *)) { [UNUserNotificationCenter currentNotificationCenter].delegate = self; UNAuthorizationOptions authOptions = (UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge); [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError *error) { if (granted == YES) { [[UIApplication sharedApplication] registerForRemoteNotifications]; } NSString *fcmToken = [FIRMessaging messaging].FCMToken; if (fcmToken == nil) { return; } BOOL mobilePushAgreement = YES; // YES or NO, should depend on device permissions and customer's agreement in the application [SNRClient registerForPush:fcmToken mobilePushAgreement:mobilePushAgreement success:^(BOOL isSuccess) { // success } failure:^(NSError *error) { // failure }]; }]; } else { UIUserNotificationType allNotificationTypes = (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge); UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil]; [[UIApplication sharedApplication] registerUserNotificationSettings:settings]; } #pragma mark - FIRMessagingDelegate - (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken { if (fcmToken != nil) { BOOL mobilePushAgreement = YES; // YES or NO, should depend on device permissions and customer's agreement in the application [SNRClient registerForPush:fcmToken mobilePushAgreement:mobilePushAgreement success:^(BOOL isSuccess) { // success } failure:^(NSError *error) { // failure }]; } } ```
The second parameter of the registration method is the agreement for mobile push campaigns. In the Profile's card in Synerise, you can find it in the **Subscriptions** section (if you have the required access permission). Learn more about the [Client.registerForPush(registrationToken:mobilePushAgreement:success:failure:) method in the method reference](/developers/mobile-sdk/method-reference/ios/campaigns#register-for-push-notifications).
### Keep Firebase token always up-to-date --- You must always keep the Firebase token updated. In many cases in the application lifecycle, such as authorization, destroyed sessions, user context change, periodic jobs ([Background Tasks](/developers/mobile-sdk/installation-and-configuration/ios#background-tasks)), and so on, the registration needs to be updated. In these situations, the SDK invokes the [snr_registerForPushNotificationsIsNeeded(origin:)](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#synerise-delegate-register-for-push-notifications-is-needed-by-origin) method or [snr_registerForPushNotificationsIsNeeded()](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#synerise-delegate-register-for-push-notifications-is-needed) method.
[Background Tasks](/developers/mobile-sdk/installation-and-configuration/ios#background-tasks)) allows you to keep the Firebase token updated even if the host application is not launched for a long time. It launches your app in the background approximately every 20 days and refreshes the token so it stays up to date.
```Swift // MARK: - SyneriseDelegate func snr_registerForPushNotificationsIsNeeded(origin: PushNotificationsRegistrationOrigin) -> Void { guard let fcmToken = Messaging.messaging().fcmToken else { return } let mobilePushAgreement = true // true or false, depending to customer's agreement in the application Client.registerForPush(registrationToken:fcmToken, mobilePushAgreement:mobilePushAgreement, success: { (success) in // success }) { (error) in // failure } } ```
```Objective-C #pragma mark - SNRSyneriseDelegate - (void)SNR_registerForPushNotificationsIsNeededByOrigin:(SNRPushNotificationsRegistrationOrigin)origin { NSString *fcmToken = [FIRMessaging messaging].FCMToken; if (fcmToken == nil) { return; } BOOL mobilePushAgreement = YES; // YES or NO, depending to customer's agreement in the application [SNRClient registerForPush:fcmToken mobilePushAgreement:mobilePushAgreement success:^(BOOL isSuccess) { // success } failure:^(NSError *error) { // failure }]; } ```
### Configure Notification Encryption --- To enable encrypted push notifications, you must change the configuration of your workspace in the Synerise portal. See [Google Firebase](/docs/settings/tool/firebase).
iOS 10 or higher version is required for this feature.
Set your Keychain Group Identifier (see [this section](/developers/mobile-sdk/settings#set-up-keychain-group-identifier)) and enable `Synerise.settings.notifications.encryption` in SDK settings:
```Swift Synerise.settings.sdk.keychainGroupIdentifier = "YOUR_KEYCHAIN_GROUP_IDENTIFIER" Synerise.settings.notifications.encryption = true ```
```Objective-C SNRSynerise.settings.sdk.keychainGroupIdentifier = @"YOUR_KEYCHAIN_GROUP_IDENTIFIER"; SNRSynerise.settings.notifications.encryption = YES; ```
**Next:** Configure [Synerise Notification Service Extension](/developers/mobile-sdk/configuring-push-notifications/ios#synerise-notification-service-extension). ### Synerise Notification Service Extension {id=synerise-notification-service-extension} --- **Synerise Notification Service Extension** is an object that adds the notification functionality to the SDK. It works by implementing the [`UNNotificationServiceExtension`](https://developer.apple.com/documentation/usernotifications/unnotificationserviceextension) that cooperates with the host application. The Synerise Notification Service Extension facilitates some operations by automating them. This means a one-time implementation provides new functionalities, changes, and fixes, along with new versions of the SDK. It implements the following operations: - Decrypting **Simple Push** communication data (if encryption is enabled). - Tracking events from **Simple Push** communication (e.g. `push.view`). - Tracking `push.dismiss` when the notification is cleared from the notification center. - Adding action buttons to **Simple Push** communication (if the communication contains any). - Improving the appearance of **Simple Push** communication (Rich Media - Single Image) with an image thumbnail.
From version 4.24.0, the SDK started tracking `push.dismiss` events when clearing from the notification center. You can enable tracking this event by setting **kSNRNotificationServiceExtensionOptionsPushDismissProcessing** to true ([see implementation below](/developers/mobile-sdk/configuring-push-notifications/ios#synerise-notification-service-extension-implementation)). If you enable this option, it can cause a noticeable amount of generated events.
#### Configuration {id=synerise-notification-service-extension-configuration} 1. Configure **App Group Identifier** (see [this section](/developers/mobile-sdk/settings#set-up-app-group-identifier)). 2. Configure **Keychain Group Identifier** (see [this section](/developers/mobile-sdk/settings#set-up-keychain-group-identifier)). 3. Add the **Notification Service Extension** to your iOS project ([Apple Developer - UNNotificationServiceExtension](https://developer.apple.com/documentation/usernotifications/unnotificationserviceextension)). 4. Configure the SDK both in the host application and in the notification service extension.
- Configuring **App Group Identifier** and **Keychain Group Identifier** both in the host application and in the notification service extension is required for proper functioning of all **Notification Service Extension** features. - Your host application and the **Notification Service Extension** must have the same **iOS Deployment Target** version (newer than iOS 10). - If you want to enable processing the campaign by **Notification Service Extension**, select the [Mutable-Content](/developers/mobile-sdk/configuring-push-notifications/ios#mutable-content-parameter) option.
#### Implementation {id=synerise-notification-service-extension-implementation}
```Swift import UserNotifications import SyneriseSDK class NotificationService: 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) if let bestAttemptContent = self.bestAttemptContent { Synerise.settings.sdk.appGroupIdentifier = "YOUR_APP_GROUP_IDENTIFIER" Synerise.settings.sdk.keychainGroupIdentifier = "YOUR_KEYCHAIN_GROUP_IDENTIFIER" NotificationServiceExtension.setDelegate(self) NotificationServiceExtension.setNotificationDelegate(self) #if DEBUG NotificationServiceExtension.setDebugModeEnabled(true) #endif NotificationServiceExtension.setDecryptionFallbackNotificationTitleAndBody(title: "(Encrypted))", body: "(Encrypted)") NotificationServiceExtension.didReceiveNotificationExtensionRequest(request, withMutableNotificationContent: bestAttemptContent, options: [ kSNRNotificationServiceExtensionOptionsPushDismissProcessing: true ]) contentHandler(bestAttemptContent) } } override func 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. if let contentHandler = self.contentHandler, let bestAttemptContent = self.bestAttemptContent { contentHandler(bestAttemptContent) } } } extension NotificationService: NotificationServiceExtensionDelegate { func notificationServiceExtensionDidFailProcessingWithError(_ error: Error) { #if DEBUG self.bestAttemptContent?.title = error.localizedDescription #endif } func notificationServiceExtensionDidFailDecryptionWithError(_ error: Error) { #if DEBUG self.bestAttemptContent?.title = error.localizedDescription #endif } } extension NotificationService: NotificationDelegate { // This method is called when a Synerise notification is received. func snr_notificationDidReceive(notificationInfo: NotificationInfo) { //... } } ```
```Objective-C #import "NotificationService.h" #import #import @interface NotificationService () @property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver); @property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent; @end @implementation NotificationService - (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler { self.contentHandler = contentHandler; self.bestAttemptContent = [request.content mutableCopy]; SNRSynerise.settings.sdk.appGroupIdentifier = @"YOUR_APP_GROUP_IDENTIFIER"; SNRSynerise.settings.sdk.keychainGroupIdentifier = @"YOUR_KEYCHAIN_GROUP_IDENTIFIER"; [SNRNotificationServiceExtension setDelegate:self]; [SNRNotificationServiceExtension setNotificationDelegate:self]; #ifdef DEBUG [SNRNotificationServiceExtension setDebugModeEnabled:YES]; #endif [SNRNotificationServiceExtension setDecryptionFallbackNotificationTitle:@"(Encrypted)" andBody:@"(Encrypted)"]; [SNRNotificationServiceExtension didReceiveNotificationExtensionRequest:request withMutableNotificationContent:self.bestAttemptContent options:@{ kSNRNotificationServiceExtensionOptionsPushDismissProcessing: @(YES) // if true, tracking `push.dismiss` by clearing from the notification center is enabled }]; self.contentHandler(self.bestAttemptContent); } - (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. self.contentHandler(self.bestAttemptContent); } #pragma mark - SNRNotificationServiceExtensionDelegate - (void)notificationServiceExtensionDidFailProcessingWithError:(NSError *)error { #ifdef DEBUG self.bestAttemptContent.body = error.localizedDescription; #endif } - (void)notificationServiceExtensionDidFailDecryptionWithError:(NSError *)error { #ifdef DEBUG self.bestAttemptContent.body = error.localizedDescription; #endif } #pragma mark - SNRNotificationDelegate // This method is called when a Synerise notification is received. - (void)SNR_notificationDidReceive:(SNRNotificationInfo *)notificationInfo { //... } @end ```
Examples of Notification Service Extensions: - [Notification Service Extension in Swift](https://github.com/Synerise/synerise-ios-sdk/tree/master/SampleAppSwift/4.10.0/SyneriseNotificationServiceExtension) - [Notification Service Extension in Objective-C](https://github.com/Synerise/synerise-ios-sdk/tree/master/SampleAppSwift/4.10.0/SyneriseNotificationServiceExtensionObjC) #### Debug Mode {id=synerise-notification-service-extension-debug-mode} You can enable the debug mode for Notification Service Extension logging and testing purposes.
Do not use the debug mode in a release version of your application.
```Swift override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.contentHandler = contentHandler self.bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) //... NotificationServiceExtension.setDebugModeEnabled(true) //... } ```
```Objective-C - (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler { self.contentHandler = contentHandler; self.bestAttemptContent = [request.content mutableCopy]; //... [SNRNotificationServiceExtension setDebugModeEnabled:YES]; //... } ```
In the debug mode, decryption process is considered successful even if it fails. Your best attempt content (`UNNotificationContent` object) is modified - the notification displays the title and body with the problem that occurred during decryption. It may help you debug and find problems with the configuration.
### Handling incoming push notifications ---
You may disable handling push notifications in the SDK at any time. See [Enable/disable notifications](/developers/mobile-sdk/settings#enabledisable-notifications).
Documentation on how to prepare push notifications in [app.synerise.com](https://app.synerise.com) is available in our [user guide](/docs/campaign/Mobile). In order to handle Synerise push notifications, you must pass the incoming push payload to the Synerise SDK. #### Synerise payload The following code shows how to handle push notifications in the `AppDelegate`:
```Swift // Support for Push Notifications on iOS 9 // Support for Silent Notifications func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { let isSyneriseNotification: Bool = Synerise.isSyneriseNotification(userInfo) if isSyneriseNotification { Synerise.handleNotification(userInfo) completionHandler(.noData) } } func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [AnyHashable : Any], completionHandler: @escaping () -> Void) { let isSyneriseNotification: Bool = Synerise.isSyneriseNotification(userInfo) if isSyneriseNotification { Synerise.handleNotification(userInfo, actionIdentifier: identifier) completionHandler() } } // Support for Push Notifications on iOS 10 and above // MARK: - UNUserNotificationCenterDelegate @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo let isSyneriseNotification: Bool = Synerise.isSyneriseNotification(userInfo) if isSyneriseNotification { Synerise.handleNotification(userInfo, actionIdentifier: response.actionIdentifier) completionHandler() } } @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { let userInfo = notification.request.content.userInfo let isSyneriseNotification: Bool = Synerise.isSyneriseNotification(userInfo) if isSyneriseNotification { Synerise.handleNotification(userInfo) completionHandler(UNNotificationPresentationOptions.init(rawValue: 0)) } } ```
```Objective-C // Support for Push Notifications on iOS 9 // Support for Silent Notifications - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { BOOL isSyneriseNotification = [SNRSynerise isSyneriseNotification:userInfo]; if (isSyneriseNotification) { [SNRSynerise handleNotification:userInfo]; completionHandler(UIBackgroundFetchResultNoData); } } - (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)())completionHandler { BOOL isSyneriseNotification = [SNRSynerise isSyneriseNotification:userInfo]; if (isSyneriseNotification) { [SNRSynerise handleNotification:userInfo actionIdentifier:identifier]; completionHandler(); } } // Support for Push Notifications on iOS 10 and above // pragma mark - UNUserNotificationCenterDelegate - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler NS_AVAILABLE_IOS(10) { NSDictionary *userInfo = response.notification.request.content.userInfo; BOOL isSyneriseNotification = [SNRSynerise isSyneriseNotification:userInfo]; if (isSyneriseNotification) { [SNRSynerise handleNotification:userInfo actionIdentifier:response.actionIdentifier]; completionHandler(); } } - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler NS_AVAILABLE_IOS(10) { NSDictionary *userInfo = notification.request.content.userInfo; BOOL isSyneriseNotification = [SNRSynerise isSyneriseNotification:userInfo]; if (isSyneriseNotification) { [SNRSynerise handleNotification:userInfo]; completionHandler(UNNotificationPresentationOptionNone); } } ```
All of these methods must be implemented to ensure proper handling of push notifications.
Displaying the notification banner on top of the screen in foreground state depends on values passed in `completionHandler` in the [UNUserNotificationCenterDelegate.userNotificationCenter(_:willPresent:completionHandler:)](https://developer.apple.com/documentation/usernotifications/unusernotificationcenterdelegate/1649518-usernotificationcenter) method.
#### Custom payload You may send both custom push notifications and custom campaigns in [Synerise](https://app.synerise.com). The code below of one sample delegate method checks if the notification origin and then handles it.
```Swift @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { let userInfo = notification.request.content.userInfo let isSyneriseNotification: Bool = Synerise.isSyneriseNotification(userInfo) if isSyneriseNotification { Synerise.handleNotification(userInfo) completionHandler(UNNotificationPresentationOptions.init(rawValue: 0)) } else { // Handle other notification in your own way } } ```
```Objective-C - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler NS_AVAILABLE_IOS(10) { NSDictionary *userInfo = notification.request.content.userInfo; BOOL isSyneriseNotification = [SNRSynerise isSyneriseNotification:userInfo]; if (isSyneriseNotification) { [SNRSynerise handleNotification:userInfo]; completionHandler(UNNotificationPresentationOptionNone); } else { // Handle other notification in your own way } } ```
#### Encrypted payloads If you handle the Synerise push notification, you do not have to do anything. The SDK decrypts Synerise push notification's payload: - In [Notification Service Extension](#synerise-notification-service-extension) for push notifications - In the SDK, after invoking [`Synerise.handleNotification(_:)`](/developers/mobile-sdk/method-reference/ios/campaigns#handle-synerise-push-notification) for silent push notifications Otherwise, if it is a custom encrypted push notification sent by Synerise, or you need decrypt data from the push notification, there are two methods for dealing with them: - [`Synerise.isNotificationEncrypted(_:)`](/developers/mobile-sdk/method-reference/ios/campaigns#check-if-push-notification-is-encrypted) - checks if the notification payload is encrypted by Synerise. - [`Synerise.decryptNotification(_:)`](/developers/mobile-sdk/method-reference/ios/campaigns#decrypt-push-notification) - decrypts a notification payload.
```Swift @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { let userInfo = notification.request.content.userInfo let isSyneriseNotification: Bool = Synerise.isSyneriseNotification(userInfo) if isSyneriseNotification { let isNotificationEncrypted: Bool = Synerise.isNotificationEncrypted(userInfo) if isNotificationEncrypted == true { if let userInfoDecrypted = Synerise.decryptNotification(userInfo) { // Handle decrypted payload in your own way } Synerise.handleNotification(userInfo) completionHandler(UNNotificationPresentationOptions.init(rawValue: 0)) } } ```
```Objective-C - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler NS_AVAILABLE_IOS(10) { NSDictionary *userInfo = notification.request.content.userInfo; BOOL isSyneriseNotification = [SNRSynerise isSyneriseNotification:userInfo]; if (isSyneriseNotification) { BOOL isNotificationEncrypted = [SNRSynerise isNotificationEncrypted:userInfo]; if (isNotificationEncrypted == YES) { NSDictionary *userInfoDecrypted = [SNRSynerise decryptNotification:userInfo]; if (userInfoDecrypted != nil) { // Handle decrypted payload in your own way } [SNRSynerise handleNotification:userInfo]; completionHandler(UNNotificationPresentationOptionNone); } } ```
Remember, if you want to send custom push notifications by Synerise (and it is not a silent push notification), you must implement the code in your [Notification Service Extension](/developers/mobile-sdk/configuring-push-notifications/ios#synerise-notification-service-extension):
```Swift import UserNotifications import SyneriseSDK class NotificationService: 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) if let bestAttemptContent = self.bestAttemptContent { var userInfo = notification.request.content.userInfo let isSyneriseNotification: Bool = Synerise.isSyneriseNotification(userInfo) if isSyneriseNotification == true { //... } else { let isNotificationEncrypted: Bool = Synerise.isNotificationEncrypted(userInfo) if isNotificationEncrypted == true { if let userInfoDecrypted = Synerise.decryptNotification(userInfo) { bestAttemptContent.title = userInfoDecrypted["aps"]?["alert"]?["title"] bestAttemptContent.body = userInfoDecrypted["aps"]?["alert"]?["body"] bestAttemptContent.userInfo = userInfoDecrypted; } else { bestAttemptContent.title = "YOUR_FALLBACK_TITLE" bestAttemptContent.body = "YOUR_FALLBACK_BODY" } } } contentHandler(bestAttemptContent) } } } ```
```Objective-C #import "NotificationService.h" #import #import @interface NotificationService () @property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver); @property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent; @end @implementation NotificationService - (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler { self.contentHandler = contentHandler; self.bestAttemptContent = [request.content mutableCopy]; NSDictionary *userInfo = notification.request.content.userInfo; BOOL isSyneriseNotification = [SNRSynerise isSyneriseNotification:userInfo]; if (isSyneriseNotification == YES) { //... } else { BOOL isNotificationEncrypted = [SNRSynerise isNotificationEncrypted:userInfo]; if (isNotificationEncrypted == YES) { NSDictionary *userInfoDecrypted = [SNRSynerise decryptNotification:userInfo]; if (userInfoDecrypted != nil) { bestAttemptContent.title = userInfoDecrypted[@"aps"][@"alert"][@"title"]; bestAttemptContent.body = userInfoDecrypted[@"aps"][@"alert"][@"body"]; bestAttemptContent.userInfo = userInfoDecrypted; } else { bestAttemptContent.title = "YOUR_FALLBACK_TITLE" bestAttemptContent.body = "YOUR_FALLBACK_BODY" } } } self.contentHandler(self.bestAttemptContent); } @end ```
#### 'Content-Available' parameter If you want to receive push notification in the background and foreground states, enable the `Content-Available` option while creating a push notification in Synerise ([Creating mobile push templates](/docs/campaign/Mobile/creating-mobile-push-templates/mobile-push-visual-builder)).
`Content-Available` option in visual builder
Enabled `Content-Available` option in a visual builder
When you want support this option, you must add the capability to your application. In the **Signing and Capability** tab, in the **Background Modes** capability, select the **Remote notifications** checkbox:
Remote notifications capability in the Xcode
Remote notifications capability in the Xcode
Your application will be notified of the notification delivery when it's in the foreground or background (the app will be woken up). This ensures that the necessary method and code responsible for receiving background notifications are executed. On iOS, it calls your app delegate’s [application(_:didReceiveRemoteNotification:fetchCompletionHandler:)](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623013-application) method. On watchOS, it calls your extension delegate’s [didReceiveRemoteNotification(_:fetchCompletionHandler:)](https://developer.apple.com/documentation/watchkit/wkextensiondelegate/3152235-didreceiveremotenotification) method. For more details, see [Apple Developer - Pushing Background Updates to Your App](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/pushing_background_updates_to_your_app). #### 'Mutable-Content' parameter If you want your notification to be processed by the Notification Service Extension, enable the `Mutable-Content` option while creating a push notification in Synerise ([Creating mobile push templates](/docs/campaign/Mobile/creating-mobile-push-templates/mobile-push-visual-builder)).
`Mutable-Content` option in visual builder
Enabled `Mutable-Content` option in a visual builder
If you want to have full support for **Simple Push** communication, and to make `Mutable-Content` relevant and functional, you must configure [Synerise Notification Service Extension](/developers/mobile-sdk/configuring-push-notifications/ios#synerise-notification-service-extension). This extension is required to fully support Simple Push communication for iOS, such as gathering the view events. For more details, see [Apple Developer - Modifying content in newly delivered notifications](https://developer.apple.com/documentation/usernotifications/modifying-content-in-newly-delivered-notifications). #### Delegate methods
[NotificationDelegate](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#notification-delegate) is available from SDK version 4.10.0.
A [NotificationDelegate](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#notification-delegate) handles events from Synerise notifications. - To handle "receive" events when an application is disabled or in background state: set the delegate in the notification service extension by using the `NotificationServiceExtension.setNotificationDelegate(_:)` method. See [this section](/developers/mobile-sdk/configuring-push-notifications/ios#synerise-notification-service-extension-implementation) to get a sample code for the notification service extension. - **SDK version 4.14.3 or newer:** To handle "receive" events when an application is launched by the notification or in foreground state: set the delegate in the application by using the `Synerise.setNotificationDelegate(_:)` method. - To handle "dismiss" and "click" events: set the delegate in the application by using the `Synerise.setNotificationDelegate(_:)` method. See a sample code from the application below:
```Swift extension SyneriseManager: NotificationDelegate { // This method is called when a Synerise notification is received. func snr_notificationDidReceive(notificationInfo: NotificationInfo) { //... } // This method is called when a Synerise notification is dismissed. func snr_notificationDidDissmis(notificationInfo: NotificationInfo) { //... } // This method is called when a Synerise notification is clicked. func snr_notificationClicked(notificationInfo: NotificationInfo) { //... } // This method is called when an action button is clicked in a Synerise notification. func snr_notificationClicked(notificationInfo: NotificationInfo, actionButton: String) { //... } } ```
```Objective-C #pragma mark - SNRNotificationDelegate // This method is called when a Synerise notification is received. - (void)SNR_notificationDidReceive:(SNRNotificationInfo *)notificationInfo { //... } // This method is called when a Synerise notification is dismissed. - (void)SNR_notificationDidDissmis:(SNRNotificationInfo *)notificationInfo { //... } // This method is called when a Synerise notification is clicked. - (void)SNR_notificationClicked:(SNRNotificationInfo *)notificationInfo { //... } // This method is called when an action button is clicked in a Synerise notification. - (void)SNR_notificationActionButtonClicked:(SNRNotificationInfo *)notificationInfo actionButton:(NSString *)actionButton { //... } ```
### Handling actions from push notifications --- - [Read more about types of actions in campaigns](/developers/mobile-sdk/campaigns/action-handling#types-of-actions-in-campaigns) - [Read more about handling actions from push notifications](/developers/mobile-sdk/campaigns/action-handling#handling-actions-from-campaigns-in-ios) ### Additional in-app alert from push notifications --- The iOS SDK can display an additional alert in the application after a push notification is received. See [this article](/developers/mobile-sdk/campaigns/simple-push#additional-in-app-alert-when-simple-push-is-received) to read more about this feature.
Simple Push campaign with in-app alert
Simple Push campaign with in-app alert
### Rich Media in push notifications --- **Notification Content Extension** is an object that allows rendering your own appearance of a push notification when the notification is expanded (by tapping the notification). It works by implementing the UNNotificationContentExtension that cooperates with the host application. Synerise SDK does most of the work needed and provides classes for the Notification Content Extensions. When you create an extension, you only need to make it inherit from a suitable Synerise SDK class. #### Prerequisites {id=rich-media-in-push-notifications-prerequisites} 1. Configure **App Group Identifier** (see [this section](/developers/mobile-sdk/settings#set-up-app-group-identifier)). 2. Configure **Keychain Group Identifier** (see [this section](/developers/mobile-sdk/settings#set-up-keychain-group-identifier)). #### Configuration {id=rich-media-in-push-notifications-configuration} To add this feature in your [Simple Push Campaigns](/developers/mobile-sdk/campaigns/simple-push), you must: 1. Add the **Notification Content Extensions** in your iOS project - separately for each type of our Rich Media extensions. 2. Configure the host application and the notification content extensions with the SDK.
- Configuring **App Group Identifier** and **Keychain Group Identifier** both in the host application and in the notification service extension is required for proper functioning of all **Notification Content Extensions** features. - Your host application and all the **Notification Content Extensions** must have the same **iOS Deployment Target** version (higher than iOS 10).
#### Application implementation {id=rich-media-in-push-notifications-application-implementation} You must create push notification categories with the right identifiers, correlating with **Content Extensions** that you added before. The identifiers must be taken from the Synerise SDK constants (they are used in the code sample below). This does not affect button names.
```Swift Synerise.settings.sdk.appGroupIdentifier = "YOUR_APP_GROUP_IDENTIFIER" Synerise.settings.sdk.keychainGroupIdentifier = "YOUR_KEYCHAIN_GROUP_IDENTIFIER" let singleMediaCategory = UNNotificationCategory(identifier: SNRSingleMediaContentExtensionViewControllerCategoryIdentifier, actions: [], intentIdentifiers: [], options: []) let carouselPrevious = UNNotificationAction(identifier: SNRCarouselContentExtensionViewControllerPreviousItemIdentifier, title: "Previous", options: []) let carouselAction = UNNotificationAction(identifier: SNRCarouselContentExtensionViewControllerChooseItemIdentifier, title: "Go!", options: UNNotificationActionOptions.foreground) let carouselNext = UNNotificationAction(identifier: SNRCarouselContentExtensionViewControllerNextItemIdentifier, title: "Next", options: []) let carouselCategory = UNNotificationCategory(identifier: SNRCarouselContentExtensionViewControllerCategoryIdentifier, actions: [carouselPrevious, carouselAction, carouselNext], intentIdentifiers: [], options: []) // Use this method when you use SDK 4.21.0 or higher Synerise.setNotificationCategories([singleMediaCategory, carouselCategory]) // or // Use this method when you use SDK lower than 4.21.0 UNUserNotificationCenter.current().setNotificationCategories([singleMediaCategory, carouselCategory]) ```
```Objective-C SNRSynerise.settings.notifications.appGroupIdentifier = @"YOUR_APP_GROUP_IDENTIFIER"; SNRSynerise.settings.sdk.keychainGroupIdentifier = @"YOUR_KEYCHAIN_GROUP_IDENTIFIER"; UNNotificationCategory *singleMediaCategory = [UNNotificationCategory categoryWithIdentifier:SNRSingleMediaContentExtensionViewControllerCategoryIdentifier actions:@[] intentIdentifiers:@[] options:0]; UNNotificationAction *carouselPreviousAction = [UNNotificationAction actionWithIdentifier:SNRCarouselContentExtensionViewControllerPreviousItemIdentifier title:@"Previous" options:0]; UNNotificationAction *carouselGoAction = [UNNotificationAction actionWithIdentifier:SNRCarouselContentExtensionViewControllerChooseItemIdentifier title:@"Go" options:0]; UNNotificationAction *carouselNextAction = [UNNotificationAction actionWithIdentifier:SNRCarouselContentExtensionViewControllerNextItemIdentifier title:@"Next" options:0]; UNNotificationCategory *carouselCategory = [UNNotificationCategory categoryWithIdentifier:SNRCarouselContentExtensionViewControllerCategoryIdentifier actions:@[carouselPreviousAction, carouselGoAction, carouselNextAction] intentIdentifiers:@[] options:0]; [[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObjects:singleMediaCategory, carouselCategory, nil]]; ```
| Method | Description | | --- | --- | | [`Synerise.setNotificationCategories(_:)`](/developers/mobile-sdk/method-reference/ios/campaigns#set-notification-categories) | Sets the notification categories (including Synerise categories) that your app supports. Use this method when you use SDK 4.21.0 or higher. | | [`UNUserNotificationCenter.current().setNotificationCategories(_:)`](https://developer.apple.com/documentation/usernotifications/unusernotificationcenter/setnotificationcategories(_:)) | Sets the notification categories by using the standard iOS SDK method. Use this method when you use SDK lower than 4.21.0. | #### Single Media implementation {id=rich-media-in-push-notifications-single-media-implementation}
```Swift import UIKit import UserNotifications import UserNotificationsUI import SyneriseSDK class NotificationViewController: SingleMediaContentExtensionViewController, UNNotificationContentExtension { func didReceive(_ notification: UNNotification) { Synerise.settings.sdk.appGroupIdentifier = "YOUR_APP_GROUP_IDENTIFIER" Synerise.settings.sdk.keychainGroupIdentifier = "YOUR_KEYCHAIN_GROUP_IDENTIFIER" self.contentViewIsScrollable = false self.imageContentMode = .scaleAspectFit setSyneriseNotification(notification) } func didReceive(_ response: UNNotificationResponse, completionHandler completion: @escaping (UNNotificationContentExtensionResponseOption) -> Void) { setSyneriseNotificationResponse(response, completionHandler: completion) } } ```
```Objective-C #import #import #import #import @interface SingleMediaNotificationViewController : SNRSingleMediaContentExtensionViewController @end #import "SingleMediaNotificationViewController.h" @implementation SingleMediaNotificationViewController - (void)didReceiveNotification:(UNNotification *)notification { SNRSynerise.settings.notifications.appGroupIdentifier = @"YOUR_APP_GROUP_IDENTIFIER"; SNRSynerise.settings.sdk.keychainGroupIdentifier = @"YOUR_KEYCHAIN_GROUP_IDENTIFIER"; self.contentViewIsScrollable = NO; self.imageContentMode = UIViewContentModeScaleAspectFit; [self setSyneriseNotification:notification]; } - (void)didReceiveNotificationResponse:(UNNotificationResponse *)response completionHandler:(void (^)(UNNotificationContentExtensionResponseOption))completion { [self setSyneriseNotificationResponse:response completionHandler:completion]; } @end ```
##### Properties {id=rich-media-in-push-notifications-single-media-properties} | Parameter | Type | Default | Description | | --- | --- | --- | --- | | contentViewIsScrollable | `Bool` | true | This parameter specifies if vertical scroll is enabled. If false, content is adjusted to the screen height. | | imageContentMode | `UIViewContentMode` | `UIViewContentModeScaleAspectFill` | This parameter sets the rendering mode of an image | ##### Info.plist {id=rich-media-in-push-notifications-single-media-info-plist} The configuration for your **Content Extension** in `\*.plist` file must be: - correlated with Synerise SDK constants for notification category *NSExtension->NSExtensionAttributes->UNNotificationExtensionCategory->0* must be **synerise.notifications.category.single-media**. - configured without a storyboard (by, default a storyboard is set). *NSExtensionMainStoryboard* key and its values must be removed from `\*.plist` file. - correlated with the principal class *NSextensionPrincipalClass* key must have value with the name of the main class for the notification extension you have created. For **Content Extension** written in Swift, the prefix `$(PRODUCT_MODULE_NAME).` is required. For Objective-C, it is not. Example `\*.plist` file for single media:
Sample *.plist configuration in Single Image Notification Content Extension
Sample *.plist configuration in Single Image Notification Content Extension
##### Example {id=rich-media-in-push-notifications-single-media-example} Examples of Single Media Notification Content Extension: - [Single Media Notification Content Extension in Swift](https://github.com/Synerise/synerise-ios-sdk/tree/master/SampleAppSwift/4.10.0/SyneriseSingleMediaNotificationContentExtension) - [Single Media Notification Content Extension in Objective-C](https://github.com/Synerise/synerise-ios-sdk/tree/master/SampleAppSwift/4.10.0/SyneriseSingleMediaNotificationContentExtensionObjC) #### Carousel implementation {id=rich-media-in-push-notifications-carousel-implementation}
```Swift import UIKit import UserNotifications import UserNotificationsUI import SyneriseSDK class NotificationViewController: CarouselContentExtensionViewController, UNNotificationContentExtension { func didReceive(_ notification: UNNotification) { Synerise.settings.sdk.appGroupIdentifier = "YOUR_APP_GROUP_IDENTIFIER" Synerise.settings.sdk.keychainGroupIdentifier = "YOUR_KEYCHAIN_GROUP_IDENTIFIER" self.imageContentMode = .scaleAspectFit setSyneriseNotification(notification) } func didReceive(_ response: UNNotificationResponse, completionHandler completion: @escaping (UNNotificationContentExtensionResponseOption) -> Void) { setSyneriseNotificationResponse(response, completionHandler: completion) } } ```
```Objective-C #import #import #import #import @interface CarouselNotificationViewController : SNRCarouselContentExtensionViewController @end #import "CarouselNotificationViewController.h" @implementation CarouselNotificationViewController - (void)didReceiveNotification:(UNNotification *)notification { SNRSynerise.settings.notifications.appGroupIdentifier = @"YOUR_APP_GROUP_IDENTIFIER"; SNRSynerise.settings.sdk.keychainGroupIdentifier = @"YOUR_KEYCHAIN_GROUP_IDENTIFIER"; [self setSyneriseNotification:notification]; } - (void)didReceiveNotificationResponse:(UNNotificationResponse *)response completionHandler:(void (^)(UNNotificationContentExtensionResponseOption))completion { [self setSyneriseNotificationResponse:response completionHandler:completion]; } @end ```
##### Properties {id=rich-media-in-push-notifications-carousel-properties} | Parameter | Type | Default | Description | | --- | --- | --- | --- | | imageContentMode | `UIViewContentMode` | `UIViewContentModeScaleAspectFill` | This parameter sets the rendering mode of images | ##### Info.plist {id=rich-media-in-push-notifications-carousel-info-plist} The configuration for your **Content Extension** in `\*.plist` file must be: - correlated with Synerise SDK constants for notification category. *NSExtension->NSExtensionAttributes->UNNotificationExtensionCategory->0* must be **synerise.notifications.category.carousel**.

- configured without storyboard (it is set by default). *NSExtensionMainStoryboard* key and its values must be removed from `\*.plist` file.

- correlated with the principal class. *NSextensionPrincipalClass* key must have value with name of your main class for the notification extension you have created. For **Content Extension** written in Swift, the prefix `$(PRODUCT_MODULE_NAME).` is required. For Objective-C, it is not. See proper `\*.plist` file example for single media below:
Sample *.plist configuration in Carousel Notification Content Extension
Sample *.plist configuration in Carousel Notification Content Extension
##### Example {id=rich-media-in-push-notifications-carousel-example} Examples of Carousel Notification Content Extension: - [Carousel Notification Content Extension in Swift](https://github.com/Synerise/synerise-ios-sdk/tree/master/SampleAppSwift/4.10.0/SyneriseCarouselNotificationContentExtension) - [Carousel Notification Content Extension in Objective-C](https://github.com/Synerise/synerise-ios-sdk/tree/master/SampleAppSwift/4.10.0/SyneriseCarouselNotificationContentExtensionObjC) # Modules ### BaseModule **Declared In:** lib/modules/base/base_module.dart **Declaration:**
class BaseModule
--- --- ### Settings **Declared In:** lib/modules/notifications/settings_impl.dart **Declaration:**
class SettingsImpl
**Properties:** | Property | Type | Description | | --- | --- | --- | | **sdk** | GeneralSettings | [General settings](/developers/mobile-sdk/settings#general) - This group contains options related to the general functioning of mobile SDK | | **notifications** | NotificationsSettings | [Notifications settings](/developers/mobile-sdk/settings#notifications) - This group contains options related to push notifications | | **tracker** | TrackerSettings | [Tracker](/developers/mobile-sdk/settings#tracker) - This group contains options related to tracking the customer activities in a mobile application | | **inAppMessaging** | InAppMessagingSettings | [In-app messaging](/developers/mobile-sdk/settings#in-app-messaging) - This group contains options related to the [in-app messages](/docs/campaign/in-app-messages) feature | | **injector** | InjectorSettings | [Injector](/developers/mobile-sdk/settings#injector) - This group contains options related to displaying [campaigns](/docs/campaign/Mobile) | **Note:** Learn more about settings [here](/developers/mobile-sdk/settings) --- --- ### Notifications **Declared In:** lib/modules/notifications/notifications_impl.dart **Declaration:**
class NotificationsImpl
**Listeners:** [NotificationsListener](/developers/mobile-sdk/listeners-and-delegates/flutter-listeners#notifications-listener) **Methods:** This method passes the Firebase Token to Synerise for notifications.
Future<void> registerForNotifications(String registrationToken, {bool? mobileAgreement, required void Function() onSuccess, required void Function(SyneriseError error) onError})
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/campaigns#register-for-push-notifications) --- This method handles a notification payload and starts activity.
Future<bool> handleNotification(Map notification) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/campaigns#handle-synerise-push-notification) --- This method handles a notification payload with a user interaction and starts activity.
Future<bool> handleNotificationClick(Map notification) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/campaigns#handle-synerise-push-notification-click) --- This method verifies if a notification was sent by Synerise.
Future<bool> isSyneriseNotification(Map notification) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/campaigns#check-if-push-notification-is-from-synerise) --- This method verifies if a notification’s sender is Synerise and if the notification is a Simple Push campaign
Future<bool> isSyneriseSimplePush(Map notification) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/campaigns#check-if-push-notification-is-a-simple-push-campaign) --- This method verifies if a notification’s sender is Synerise and if the notification is a Banner campaign.
Future<bool> isSyneriseBanner(Map notification) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/campaigns#check-if-push-notification-is-a-banner-campaign) - **REMOVED in version 2.0.0** --- This method verifies if a notification's sender is Synerise and if the notification is a Silent Command.
Future<bool> isSilentCommand(Map notification) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/campaigns#check-if-push-notification-is-a-silent-command) --- This method verifies if a notification's sender is Synerise and if the notification is a Silent SDK Command.
Future<bool> isSilentSDKCommand(Map notification) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/campaigns#check-if-push-notification-is-a-silent-sdk-command) --- --- ### Client **Declared In:** lib/modules/client/client_impl.dart **Related To:** [ClientAccountRegisterContext](/developers/mobile-sdk/class-reference/flutter/client#clientaccountregistercontext) [ClientIdentityProvider](/developers/mobile-sdk/class-reference/flutter/client#clientidentityprovider) [ClientAuthContext](/developers/mobile-sdk/class-reference/flutter/client#clientauthcontext) [ClientConditionalAuthContext](/developers/mobile-sdk/class-reference/flutter/client#clientconditionalauthcontext) [ClientAccountInformation](/developers/mobile-sdk/class-reference/flutter/client#clientaccountinformation) [ClientAccountUpdateContext](/developers/mobile-sdk/class-reference/flutter/client#clientaccountupdatecontext) [ClientConditionalAuthResult](/developers/mobile-sdk/class-reference/flutter/client#clientconditionalauthresult) [ClientPasswordResetRequestContext](/developers/mobile-sdk/method-reference/flutter/client-account#request-password-reset-for-customer-account) [ClientPasswordResetConfirmationContext](/developers/mobile-sdk/method-reference/flutter/client-account#confirm-password-reset-for-customer-account) [Token](/developers/mobile-sdk/class-reference/flutter/client#token) **Inherits From:** [BaseModule](/developers/mobile-sdk/class-reference/flutter/modules#basemodule) **Declaration:**
class ClientImpl extends BaseModule
**Methods:** This method registers a new customer with an email, password, and optional data.
Future<void> registerAccount(ClientAccountRegisterContext context, {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-authentication#register-customer-account) --- This method confirms a customer account with the confirmation token.
Future<void> confirmAccountActivation(String token, {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-authentication#confirm-customer-account-activation) --- This method activates a customer with email.
Future<void> requestAccountActivation(String email, {required void Function() onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-authentication#request-customer-account-activation) --- This method requests a customer's account registration process with the PIN code.
Future<void> requestAccountActivationByPin(String email, {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-authentication#request-customer-account-activation-by-pin) --- This method confirms a customer's account registration process with the PIN code.
Future<void> confirmAccountActivationByPin(String email, String pinCode, {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-authentication#confirm-customer-account-activation-by-pin) --- This method signs a customer in to obtain a JSON Web Token (JWT) which can be used in subsequent requests.
Future<void> signIn(String email, String password, {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-authentication#sign-in-a-customer) --- This method signs a customer in to obtain a JSON Web Token (JWT) which can be used in subsequent requests.
Future<void> signInConditionally(String email, String password, {required void Function(ClientConditionalAuthResult) onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-authentication#sign-in-a-customer-conditionally) --- This method authenticates a customer with OAuth, Facebook, Google, Apple, or Synerise.
Future<void> authenticate(ClientAuthContext clientAuthContext, IdentityProvider identityProvider, String tokenString, {required void Function(bool) onSuccess, required void Function(SyneriseError) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-authentication#authenticate-customer-by-identityprovider) --- This method authenticates a customer with OAuth, Facebook, Google, Apple, or Synerise.
Future<void> authenticateConditionally(ClientConditionalAuthContext clientAuthContext, IdentityProvider identityProvider, String tokenString, {String? authID, required void Function(ClientConditionalAuthResult) onSuccess, required void Function(SyneriseError) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-authentication#authenticate-customer-conditionally-by-identityprovider) --- This method authenticates a customer with Simple Profile Authentication.
Future<void> simpleAuthentication(ClientSimpleAuthenticationData data, String authID, {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-authentication#authenticate-customer-via-simple-profile-authentication) --- This method checks if a customer is signed in (via Synerise Authentication - RaaS, OAuth, Facebook, Apple).
Future<bool> isSignedIn() async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-authentication#check-if-a-customer-is-signed-in-via-raas-oauth-facebook-apple) --- This method checks if a customer is signed in (via Simple Profile Authentication).
Future<bool> isSignedInViaSimpleAuthentication() async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-authentication#check-if-a-customer-is-signed-in-via-simple-profile-authentication) --- This method signs out a customer out.
Future<void> signOut() async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-authentication#sign-out-a-customer) --- This method signs out a customer out with a chosen mode and Determines if the method should sign out all devices
Future<void> signOutWithMode(ClientSignOutMode mode, bool fromAllDevices, {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-authentication#sign-out-customer-with-mode-or-from-all-devices) --- This method refreshes the customer’s current token.
Future<void> refreshToken({required void Function() onSuccess, required void Function(SyneriseError) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-session#refresh-customer-token) --- This method retrieves the customer’s current, active token.
Future<void> retrieveToken({required void Function(Token) onSuccess, required void Function(SyneriseError) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-session#retrieve-customer-token) --- This method retrieves the customer’s current UUID.
Future<String> getUUID() async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-session#get-current-customer-uuid) --- This method regenerates the UUID and clears the authentication token, login session, custom email, and custom identifier.
Future<void> regenerateUUID() async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-session#regenerate-customer) --- This method regenerates the UUID and clears the authentication token, login session, custom email, and custom identifier.
Future<void> regenerateUUIDWithClientIdentifier(String clientIdentifier) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-session#regenerate-customer-with-identifier) --- This method destroys the session completely.
Future<void> destroySession({required void Function() onSuccess, required void Function(SyneriseError) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-session#destroy-current-session) --- This method gets a customer’s account information.
Future<void> getAccount({required void Function(ClientAccountInformation) onSuccess, required void Function(SyneriseError) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-account#get-customer-account-information) --- This method updates a customer’s account’s basic information (without identification data: uuid, customId, email).
Future<void> updateAccountBasicInformation(ClientAccountUpdateBasicInformationContext context, {required void Function() onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-account#update-customer-account-basic-information) --- This method updates a customer’s account information.
Future<void> updateAccount(ClientAccountUpdateContext context, {required void Function() onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-account#update-customer-account-information) --- This method requests a customer’s password reset with email.
Future<void> requestPasswordReset(String email, {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-account#request-password-reset-for-customer-account) --- This method confirm a customer’s password reset with the new password and token provided by password reset request.
Future<void> confirmPasswordReset(String password, String token, {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-account#confirm-password-reset-for-customer-account) --- This method changes a customer’s password.
Future<void> changePassword(String oldPassword, String newPassword, {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-account#change-customers-account-password) --- This method requests a customer's email change.
Future<void> requestEmailChange(String email, String password, {String? externalToken, String? authID, required void Function() onSuccess, required void Function(SyneriseError) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-account#request-email-change-for-customer-account) --- This method confirms an email change.
Future<void> confirmEmailChange(String token, bool newsletterAgreement, {required void Function() onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-account#confirm-email-change-for-customer-account) --- Requests a customer's phone update. A confirmation code is sent to the phone number.
Future<void> requestPhoneUpdate(String phone, {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-account#request-phone-update-on-customer-account) --- This method confirms a phone number update. This action requires the new phone number and confirmation code as parameters.
Future<void> confirmPhoneUpdate(String phone, String confirmationCode, bool smsAgreement, {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-account#confirm-phone-update-on-customer-account) --- This method deletes a customer's account.
Future<void> deleteAccount(String clientAuthFactor, IdentityProvider identityProvider, {String? authId, required void Function() onSuccess, required void Function(SyneriseError) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/client-account#delete-customer-account) --- --- --- ### Tracker **Declared In:** lib/modules/tracker/tracker_impl.dart **Related To:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/flutter/events#customevent) **Inherits From:** [BaseModule](/developers/mobile-sdk/class-reference/flutter/modules#basemodule) **Declaration:**
class TrackerImpl extends BaseModule
**Methods:** This method sets a custom identifier in the parameters of every event.
Future<void> setCustomIdentifier(String customIdentifier) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/tracking#set-custom-identifier-for-events) --- This method sets a custom email in the parameters of every event.
Future<void> setCustomEmail(String customEmail) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/tracking#set-custom-email-for-events) --- This method sends an event.
Future<void> send(Event event) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/tracking#send-event) --- This method forces sending the events from the queue to the server.
Future<void> flush() async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/tracking#flush-events-from-tracker) --- --- ### Injector **Declared In:** lib/modules/injector/injector_impl.dart **Inherits From:** [BaseModule](/developers/mobile-sdk/class-reference/flutter/modules#basemodule) **Declaration:**
class InjectorImpl extends BaseModule
**Listeners:** [InjectorListener](/developers/mobile-sdk/listeners-and-delegates/flutter-listeners#injector-listener) [InjectorInAppMessageListener](/developers/mobile-sdk/listeners-and-delegates/flutter-listeners#injector-in-app-message-listener) **Methods:** Closes an in-app message and sends an `inApp.discard` event. Usage examples: - Closing a top bar or bottom bar when the user taps outside the in-app area. - Automatically dismissing messages when navigating away from a screen. - Controlling in-app visibility based on app logic for a smoother user experience.
void closeInAppMessage(String campaignHash)
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/campaigns#close-in-app-message) --- This method fetches a walkthrough.
void getWalkthrough() async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/campaigns#get-walkthrough) - **REMOVED in version 2.0.0** --- This method shows a walkthrough when it is loaded.
void showWalkthrough() async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/campaigns#show-walkthrough)- **REMOVED in version 2.0.0** --- This method checks if a walkthrough is loaded.
Future<bool> isWalkthroughLoaded() async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/campaigns#check-if-walkthrough-is-loaded)- **REMOVED in version 2.0.0** --- This method checks if the walkthrough is unique compared to the previous one.
Future<bool> isLoadedWalkthroughUnique() async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/campaigns#check-if-is-loaded-walkthrough-unique)- **REMOVED in version 2.0.0** --- --- ### Promotions The module for handling promotions and vouchers from Synerise SDK. **Declared In:** lib/modules/promotions/promotions_impl.dart **Related To:** [PromotionResponse](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotionresponse) [Promotion](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotion) [AssignVoucherResponse](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#assignvoucherresponse) [VoucherCodesResponse](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#vouchercodesresponse) **Inherits From:** [Module](/developers/mobile-sdk/class-reference/flutter/modules#basemodule) **Declaration:**
class PromotionsImpl extends BaseModule
**Methods:** This method retrieves all available promotions that are defined for a customer.
Future<void> getAllPromotions({required void Function(PromotionResponse promotionResponse) onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/promotions#get-all-promotions-of-a-customer) --- This method retrieves promotions that match the parameters defined in an API query.
Future<void> getPromotions(PromotionsApiQuery apiQuery, {required void Function(PromotionResponse promotionResponse) onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/promotions#get-promotions-with-query-parameters) --- This method retrieves the promotion with the specified UUID.
Future<void> getPromotionByUUID(String uuid, {required void Function(Promotion promotion) onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/promotions#get-promotion-by-uuid) --- This method retrieves the promotion with the specified code.
Future<void> getPromotionByCode(String code, {required void Function(Promotion promotion) onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/promotions#get-promotion-by-code) --- This method activates the promotion with the specified UUID.
Future<void> activatePromotionByUUID(String uuid, {required void Function() onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/promotions#activate-promotion-by-uuid) --- This method activates the promotion with the specified code.
Future<void> activatePromotionByCode(String code, {required void Function() onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/promotions#activate-promotion-by-code) --- This method activates promotions with a code or with UUID in a batch.
Future<void> activatePromotionsBatch(List<PromotionIdentifier> promotionsToActivate, {required void Function() onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/promotions#activate-promotions-in-a-batch) --- This method deactivates the promotion with the specified UUID.
Future<void> deactivatePromotionByUUID(String uuid, {required void Function() onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/promotions#deactivate-promotion-by-uuid) --- This method deactivates the promotion with the specified code.
Future<void> deactivatePromotionByCode(String code, {required void Function() onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/promotions#deactivate-promotion-by-code) --- This method deactivates promotions with a code or with UUID in a batch.
Future<void> deactivatePromotionsBatch(List<PromotionIdentifier> promotionsToDeactivate, {required void Function() onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/promotions#deactivate-promotions-in-a-batch) --- This method retrieves an assigned voucher code or assigns a voucher from a pool identified by UUID to the profile. When the voucher is assigned for the first time, a [voucherCode.assigned](/docs/assets/events/event-reference/loyalty#vouchercodeassigned) event is produced.
Future<void> getOrAssignVoucher(String poolUuid, {required void Function(AssignVoucherResponse assignVoucherResponse) onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/promotions#get-or-assign-voucher-from-pool) --- This method assigns a voucher from a pool identified by UUID to the profile. A [voucherCode.assigned](/docs/assets/events/event-reference/loyalty#vouchercodeassigned) event is produced.
Future<void> assignVoucherCode(String poolUuid, {required void Function(AssignVoucherResponse response) onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/promotions#assign-voucher-code-from-pool) --- This method retrieves voucher codes for a customer.
Future<void> getAssignedVoucherCodes({required void Function(VoucherCodesResponse voucherCodesResponse) onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/promotions#get-voucher-codes-assigned-to-customer) --- --- ### Content The module for handling content from Synerise backend such as documents, recommendations, and so on. **Declared In:** lib/modules/content/content_impl.dart **Related To:** [DocumentsApiQuery](/developers/mobile-sdk/class-reference/flutter/recommendations-and-documents#documentsapiquery) [Document](/developers/mobile-sdk/class-reference/flutter/recommendations-and-documents#document) [RecommendationResponse](/developers/mobile-sdk/class-reference/flutter/recommendations-and-documents#recommendationresponse) [RecommendationOptions](/developers/mobile-sdk/class-reference/flutter/recommendations-and-documents#recommendationoptions) [Recommendation](/developers/mobile-sdk/class-reference/flutter/recommendations-and-documents#recommendation) [ScreenView](/developers/mobile-sdk/class-reference/flutter/miscellaneous#screenview) [ScreenViewAudienceInfo](/developers/mobile-sdk/class-reference/flutter/miscellaneous#screenviewaudienceinfo) [ScreenViewApiQuery](/developers/mobile-sdk/class-reference/flutter/miscellaneous#screenviewapiquery) [BrickworksApiQuery](/developers/mobile-sdk/class-reference/flutter/miscellaneous#brickworksapiquery) **Inherits From:** [BaseModule](/developers/mobile-sdk/class-reference/flutter/modules#basemodule) **Declaration:**
class ContentImpl extends BaseModule
**Methods:** This method generates the document assigned to a slug.
Future<void> getDocuments(DocumentsApiQuery documentsApiQuery, {required void Function(List<Map<String, Object>> documentsList) onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/content#get-document) - **REMOVED in version 2.0.0 ** --- This method generates the document that is defined for the provided slug.
Future<void> generateDocument(String slug, {required void Function(Document document) onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/content#generate-document) --- This method generates the document that is defined for parameters provided in the query object.
Future<void> generateDocumentWithApiQuery(DocumentApiQuery apiQuery, {required void Function(Document document) onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/content#generate-document-with-query-parameters) --- This method generates documents that are defined for parameters provided in the query object.
Future<List<Map<String, Object>>> getDocuments(DocumentsApiQuery documentsApiQueryModel) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/content#get-documents) - **REMOVED in version 2.0.0 ** --- This method generates recommendations that are defined for the options provided. The recommendations are generated by using a document with an insert. For instructions, see ["Displaying AI recommendations > With documents and screen views"](/developers/mobile-sdk/displaying-recommendations/documents).
Future<void> getRecommendations(RecommendationOptions recommendationOptions, {required void Function(RecommendationResponse recommendationResponse) onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/content#get-recommendations) - **REMOVED in version 2.0.0 ** --- This method generates recommendations that are defined for the options provided. The recommendations are generated by using a document with an insert. For instructions, see ["Displaying AI recommendations > With documents and screen views"](/developers/mobile-sdk/displaying-recommendations/documents).
Future<void> getRecommendationsV2(RecommendationOptions recommendationOptions, {required void Function(RecommendationResponse recommendationResponse) onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/content#get-recommendations-v2) --- This method generates the customer's highest-priority screen view campaign.
Future<void> getScreenView({required void Function(ScreenViewResponse screenViewResponse) onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/content#get-screen-view) - **REMOVED in version 2.0.0 ** --- This method generates a customer's highest-priority screen view campaign from the feed with the provided feed slug.
Future<void> generateScreenView(String feedSlug, {required void Function(ScreenView screenView) onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/content#generate-screen-view) --- This method generates customer's highest-priority screen view campaign that is defined for parameters provided in the query object.
Future<void> generateScreenViewWithApiQuery(ScreenViewApiQuery apiQuery, {required void Function(ScreenView screenView) onSuccess, required void Function(SyneriseError error) onError}) async
[(Click for more details)](/developers/mobile-sdk/method-reference/flutter/content#generate-screen-view-with-query-parameters) --- # Public interfaces ## IDataApiCall --- IDataApiCall is a public interface used to execute requests with parameterized objects. **Java**:
public interface IDataApiCall<T> {
/**
     * It is recommended to call the {@link #cancel()} method before next execution.
     *
     * @param onSuccessListener callback with response
     * @param onFailureListener callback with Throwable instance
     */
    void execute(@NonNull DataActionListener<T> onSuccessListener, @NonNull DataActionListener<ApiError> onFailureListener);
    /**
     * Cancels the API request, therefore no response will be provided nor callback fired. <br>
     * It is recommended to call this method when an activity/fragment is being stopped.
     */
    void cancel();
    /**
     * Specify a reactive Scheduler for your request. <br>
     * By default, all internal methods use the {@link Schedulers#io()} scheduler.
     * See {@link io.reactivex.schedulers.Schedulers} factory for more info.
     *
     * @param scheduler reactive scheduler.
     */
    BasicDataApiCall<T> subscribeOn(Scheduler scheduler);
    /**
     * Specify your action when the request is being subscribed. This action will be fired just before calling the API.
     *
     * @param onSubscribeListener callback
     */
    BasicDataApiCall<T> onSubscribe(ActionListener onSubscribeListener);
    /**
     * Specify your action when the request succeeds, fails, or is cancelled.
     *
     * @param doFinallyListener callback
     */
    BasicDataApiCall<T> doFinally(ActionListener doFinallyListener);
    /**
     * Get the original reactive observable to chain your requests.<br>
     * Note that some of the SDK methods not only wrap observables in IDataApiCall,
     * but also add some extra logic, which shouldn't be skipped.<br>
     *
     * @return original reactive observable.
     */
    Observable<T> getObservable();
}
## IApiCall --- IApiCall is a public interface used to execute requests. **Java**:
public interface IApiCall<T> {
    /**
     * It is recommended to call the {@link #cancel()} method before next execution.
     *
     * @param onSuccessListener successful callback with no response
     * @param onFailureListener callback with Throwable instance
     */
    void execute(@NonNull ActionListener onSuccessListener, @NonNull DataActionListener<ApiError> onFailureListener);
    /**
     * Cancels the API request, therefore no response will be provided nor callback fired. <br>
     * It is recommended to call this method when an activity/fragment is being stopped.
     */
    void cancel();
    /**
     * Specify a reactive Scheduler for your request. <br>
     * By default, all internal methods use the {@link Schedulers#io()} scheduler.
     * See {@link io.reactivex.schedulers.Schedulers} factory for more info.
     *
     * @param scheduler reactive scheduler.
     */
    BasicApiCall<T> subscribeOn(Scheduler scheduler);
    /**
     * Specify your action when the request is being subscribed. This action will be fired just before calling API.
     *
     * @param onSubscribeListener callback.
     */
    BasicApiCall<T> onSubscribe(ActionListener onSubscribeListener);
    /**
     * Specify your action when the request succeeds, fails, or is cancelled.
     *
     * @param doFinallyListener callback.
     */
    BasicApiCall<T> doFinally(ActionListener doFinallyListener);
    /**
     * Get the original reactive observable to chain your requests.<br>
     * Note that some of SDK methods not only wrap observables in IApiCall,
     * but also add some extra logic, which shouldn't be skipped.<br>
     *
     * @return original reactive observable.
     */
    Observable<T> getObservable();
}
# iOS ## Content Widget (iOS) Content widget is a feature in the Software Development Kit that allows you to embed an easily customizable view with [recommendations](/docs/ai-hub/recommendations-v2) in your application. Two view layouts are available: - Horizontal slider - a single row view that slides horizontally on the screen. - Grid view - can be displayed as full- or half-screen grid layout within your app. Both views offer a number of configuration options that allow you to style the view consistently in the app. Additionally, the Content widget automatically tracks 4 events: - `recommendation.seen` or `recommendation.view` (depending on configuration) sent when a recommended item is visible to the customer.
Recommendation.seen event
Recommendation.seen event
- `recommendation.click` sent when a customer clicks the recommended item.
Recommendation.click event
Recommendation.click event
- `product.like` sent when a customer clicks a selectable button in the recommendation. (The button must be added)
Event sent when a user clicks the
Event sent when a user clicks the "like" button on an item
- `product.dislike` sent when a customer clicks a selectable button in the recommendation a second time. (The button must be added)
Product.dislike event
Product.dislike event
Currently, the widget can only be used for displaying AI recommendations.
### Prerequisites --- To use the content widget feature, you must: - Obtain a customer token from [Customer Authentication](/developers/mobile-sdk/user-identification-and-authorization/overview#authenticated-customers). - [Create an AI Recommendation](/docs/ai-hub/recommendations-v2). - [Create a document](/docs/assets/documents). Such a document should contain the following content:
{
      "name": "Similar Products",
      "recommendations": "{% recommendations_json3 campaignId=COhsCCOdu8Cg %} {% endrecommendations_json3 %}"
  }
- In the notepad, save the document's slug and the ID of the recommendation for later use.
It's a good practice to name slugs based on the area of the app that you want to place the content in, for example `product-details`, `menu`, and so on.
### Basic implementation --- Configure the [`ContentWidgetOptions`](/developers/mobile-sdk/class-reference/ios/content-widget#contentwidgetoptions) and [`ContentWidgetAppearance`](/developers/mobile-sdk/class-reference/ios/content-widget#contentwidgetappearance) settings first. | Class | Description | | --- | --- | | [`ContentWidgetOptions`](/developers/mobile-sdk/class-reference/ios/content-widget#contentwidgetoptions) | [`ContentWidgetOptions`](/developers/mobile-sdk/class-reference/ios/content-widget#contentwidgetoptions) contains options for business logic, such as the slug, product identifier, and so on. [Read more](#options). | | [`ContentWidgetAppearance`](/developers/mobile-sdk/class-reference/ios/content-widget#contentwidgetappearance) | [`ContentWidgetAppearance`](/developers/mobile-sdk/class-reference/ios/content-widget#contentwidgetappearance) contains the UI configuration. [Read more](#options). | The example below is the most basic implementation.
```swift let options = ContentWidgetOptions() options.slug = "similar" options.mapping = { model in guard let imageURLString = model.attributes["imageLink"] as? String, let imageURL = URL(string: imageURLString), let title = model.attributes["title"] as? String, let priceDictionary = model.attributes["price"] as? [AnyHashable: Any], let priceValue = priceDictionary["value"] as? Double else { return nil } let dataModel = ContentWidgetRecommendationDataModel(imageURL: imageURL, title: title, priceCurrency: "PLN", price: NSNumber(value: priceValue), salePrice: nil) if let salePriceDictionary = model.attributes["salePrice"] as? [AnyHashable: Any], let salePriceValue = salePriceDictionary["value"] as? Double { dataModel.salePriceValue = NSNumber(floatLiteral: salePriceValue) } let badgeDataModel = ContentWidgetBadgeDataModel(backgroundColor: UIColor.black, textColor: UIColor.white, text: "Black Week") dataModel.badge = badgeDataModel return dataModel } let gridLayout = ContentWidgetGridLayout() let itemLayout = ContentWidgetBasicProductItemLayout() let appearance = ContentWidgetAppearance(widgetLayout: gridLayout, itemLayout: itemLayout) let widget = ContentWidget(options: options, appearance: appearance) let widgetView = widget.getView() widgetView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height) view.addSubview(widgetView) ```
```objective-c SNRContentWidgetOptions *options = [SNRContentWidgetOptions new]; options.slug = @"similar"; options.mapping = ^(SNRContentWidgetRecommendationModel *model) { NSString *imageURLString = model.attributes[@"imageLink"]; NSString *imageURL = [[NSURL alloc] initWithString:imageURLString]; NSString *title = model.attributes[@"title"]; NSDictionary *priceDictionary = model.attributes[@"price"]; NSNumber *priceValue = priceDictionary[@"value"]; if (imageURL == nil || title == nil || priceValue == nil) { return nil; } SNRContentWidgetRecommendationDataModel *dataModel = [[SNRContentWidgetRecommendationDataModel alloc] initWithimageURL:imageURL title:title priceCurrency:@"PLN" price:priceValue salePrice:nil]; NSDictionary *salePriceDictionary = model.attributes[@"salePrice"]; NSNumber *salePriceValue = salePriceDictionary[@"value"]; if (salePrice != nil) { dataModel.salePriceValue = salePriceValue; } SNRContentWidgetBadgeDataModel *badgeDataModel = [[SNRContentWidgetBadgeDataModel alloc] initWithBackgroundColor:backgroundColor textColor:textColor text:text]; dataModel.badge = badgeDataModel; return dataModel; } SNRContentWidgetGridLayout *gridLayout = [SNRContentWidgetGridLayout new]; SNRContentWidgetBasicProductItemLayout *itemLayout = [SNRContentWidgetBasicProductItemLayout new]; SNRContentWidgetAppearance *appearance = [[SNRContentWidgetAppearance alloc] initWithLayout:gridLayout andItemLayout:itemLayout]; SNRContentWidget *widget = [[SNRContentWidget alloc] initWithOptions:options andAppearance:appearance]; UIView *widgetView = [widget getView]; widgetView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height); [self.view addSubview:widgetView]; ```
### Options --- The [`ContentWidgetRecommendationsOptions`](/developers/mobile-sdk/class-reference/ios/content-widget#contentwidgetoptions) class is responsible for defining the business logic options of the widget, for example: - slug of the document - product identifier - recommendation data model mapper The table explains the parameters that can be configured in [`ContentWidgetRecommendationsOptions`](/developers/mobile-sdk/class-reference/ios/content-widget#contentwidgetoptions). | Parameter | Type | Default | Description | | --- | --- | --- | --- | | slug | `String` | nil | Slug of a document | | productID | `String` | nil | Product identifier for generating data | | mapping | `((ContentWidgetRecommendationModel) -> (ContentWidgetRecommendationDataModel?))` | nil | Mapping block responsible for mapping data from the feed to a `ContentWidgetRecommendationDataModel` | | recommendationEventType | `ContentWidgetRecommendationEventType` | - | Recommendation event type.
  • **.view** sends all products in one event. We highly recommend using this type of event in content widget.
  • **.seen** sends each event as a separate event.
|
```swift let widgetOptions = ContentWidgetRecommendationsOptions() widgetOptions.slug = "similar" widgetOptions.productID = "12345" widgetOptions.mapping = { model in guard let imageURLString = model.attributes["imageLink"] as? String, let imageURL = URL(string: imageURLString), let title = model.attributes["title"] as? String, let priceDictionary = model.attributes["price"] as? [AnyHashable: Any], let priceValue = priceDictionary["value"] as? Double else { return nil } let dataModel = ContentWidgetRecommendationDataModel(imageURL: imageURL, title: title, priceCurrency: "PLN", price: NSNumber(value: priceValue), salePrice: nil) if let salePriceDictionary = model.attributes["salePrice"] as? [AnyHashable: Any], let salePriceValue = salePriceDictionary["value"] as? Double { dataModel.salePriceValue = NSNumber(floatLiteral: salePriceValue) } let badgeDataModel = ContentWidgetBadgeDataModel(backgroundColor: UIColor.black, textColor: UIColor.white, text: "Black Week") dataModel.badge = badgeDataModel return dataModel } ```
```objective-c SNRContentWidgetRecommendationsOptions *widgetOptions = [SNRContentWidgetRecommendationsOptions new]; widgetOptions.slug = @"similar"; widgetOptions.productID = @"12345"; widgetOptions.mapping = ^(SNRContentWidgetRecommendationModel *model) { NSString *imageURLString = model.attributes[@"imageLink"]; NSString *imageURL = [[NSURL alloc] initWithString:imageURLString]; NSString *title = model.attributes[@"title"]; NSDictionary *priceDictionary = model.attributes[@"price"]; NSNumber *priceValue = priceDictionary[@"value"]; if (imageURL == nil || title == nil || priceValue == nil) { return nil; } SNRContentWidgetRecommendationDataModel *dataModel = [[SNRContentWidgetRecommendationDataModel alloc] initWithimageURL:imageURL title:title priceCurrency:@"PLN" price:priceValue salePrice:nil]; NSDictionary *salePriceDictionary = model.attributes[@"salePrice"]; NSNumber *salePriceValue = salePriceDictionary[@"value"]; if (salePrice != nil) { dataModel.salePriceValue = salePriceValue; } SNRContentWidgetBadgeDataModel *badgeDataModel = [[SNRContentWidgetBadgeDataModel alloc] initWithBackgroundColor:backgroundColor textColor:textColor text:text]; dataModel.badge = badgeDataModel; return dataModel; } ```
### Appearance --- The [`ContentWidgetAppearance`](/developers/mobile-sdk/class-reference/ios/content-widget#contentwidgetappearance) class is responsible for defining the appearance of the widget. The class consists of parameters that define the widget's appearance, however, two of them are the most important: - **Main layout class**: defines the way of distributing elements in the widget. Currently, two layouts are provided: [`ContentWidgetHorizontalSliderLayout`](/developers/mobile-sdk/class-reference/ios/content-widget#contentwidgethorizontalsliderlayout) and [`ContentWidgetGridLayout`](/developers/mobile-sdk/class-reference/ios/content-widget#contentwidgetgridlayout). - **Item layout class**: defines appearance and parameters for the item in the widget. Currently, there is only one layout provided: [`ContentWidgetBasicProductItemLayout`](/developers/mobile-sdk/class-reference/ios/content-widget#contentwidgetbasicproductitemlayout). The table explains the parameters that can be configured in [`ContentWidgetAppearance`](/developers/mobile-sdk/class-reference/ios/content-widget#contentwidgetappearance). | Parameter | Type | Default | Description | | --- | --- | --- | --- | | layout | [`ContentWidgetLayout`](/developers/mobile-sdk/class-reference/ios/content-widget#contentwidgetlayout) | - | Class that inherits from [`ContentWidgetLayout`](/developers/mobile-sdk/class-reference/ios/content-widget#contentwidgetlayout) contains the UI details of `widgetLayout` | | itemLayout | [`ContentWidgetItemLayout`](/developers/mobile-sdk/class-reference/ios/content-widget#contentwidgetitemlayout) | - | Class that inherits from [`ContentWidgetItemLayout`](/developers/mobile-sdk/class-reference/ios/content-widget#contentwidgetitemlayout) contains the UI details of a single item in a widget | ### Widget layouts --- #### Horizontal Slider This layout is intended to present recommendations in a fixed-hight horizontal scrollable slider. **Example widget configuration with horizontal slider:** Content Widget - Horizontal Slider ##### Parameters The table explains the parameters of `SNRContentWidgetHorizontalLayout`. | Property | Type | Default | Description | | --- | --- | --- | --- | | backgroundColor | `UIColor` | UIColor.clearColor | Background color of a widget | | insets | `UIEdgeInsets` | (8.0, 8.0, 8.0, 8.0) | Inner widget margins in pt | | itemSize | `CGSize` | (150.0, 200.0) | Size of a single item in pt | | itemSpacing | `CGFloat` | 16.0 | Horizontal spacing between items in pt | | numberOfItems | `Int` | - | A **read-only** property. It returns the number of items after a widget is loaded | ##### Example
```swift let horizontalSliderLayout = ContentWidgetHorizontalSliderLayout() horizontalSliderLayout.insets = UIEdgeInsets(top: 16.0, left: 16.0, bottom: 16.0, right: 16.0) horizontalSliderLayout.itemSize = CGSize(width: 150, height: 350) horizontalSliderLayout.itemSpacing = 8.0 ```
```objective-c SNRContentWidgetHorizontalSliderLayout *horizontalSliderLayout = [SNRContentWidgetHorizontalSliderLayout new]; horizontalSliderLayout.insets = UIEdgeInsetsMake(16.0f, 16.0f, 16.0f, 16.0f); horizontalSliderLayout.itemSize = CGSizeMake(150.0f, 350.0f); horizontalSliderLayout.itemSpacing = 8.0f; ```
#### Grid View This layout presents recommendations in a vertical scrollable grid, with elements organized into columns and rows. You can create a full- or half-screen widget. **Example widget configuration with grid layout:** Content Widget - Grid View ##### Parameters The table explains the parameters of the grid layout. | Property | Type | Default | Description | | --- | --- | --- | --- | | backgroundColor | `UIColor` | UIColor.clearColor | Background color of a widget | | insets | `UIEdgeInsets` | (8.0, 8.0, 8.0, 8.0) | Inner widget margins in pt | | itemSize | `CGSize` | (150.0, 200.0) | Size of a single item in pt| | itemHorizontalSpacing | `CGFloat` | 16.0 | Horizontal spacing between items in pt | | itemVerticalSpacing | `CGFloat` | 16.0 | Vertical spacing between items in pt | | numberOfItems | `Int` | - | A **read-only** property. It returns the number of items after the widget is loaded | ##### Example
```swift let gridLayout = ContentWidgetGridLayout() gridLayout.insets = UIEdgeInsets(top: 16.0, left: 16.0, bottom: 16.0, right: 16.0) gridLayout.itemSize = CGSize(width: 150, height: 350) gridLayout.horizontalItemSpacing = 8.0 gridLayout.verticalItemSpacing = 8.0 ```
```objective-c SNRContentWidgetGridLayout *gridLayout = [SNRContentWidgetGridLayout new]; gridLayout.insets = UIEdgeInsetsMake(16.0f, 16.0f, 16.0f, 16.0f); gridLayout.itemSize = CGSizeMake(150.0f, 350.0f); gridLayout.horizontalItemSpacing = 8.0f; gridLayout.verticalItemSpacing = 8.0f; ```
### Widget Item layouts --- #### Basic Product Item Layout This is the basic layout for items. It contains: the image, the title, and the price from the uploaded data. ##### Parameters The table below contains all parameters you can configure in the basic item layout. | Property | Type | Default | Description | | --- | --- | --- | --- | | backgroundColor | `UIColor` | UIColor.whiteColor | Background color of an item | | cornerRadius | `CGFloat` | 0.0 | Radius of the item corners | | borderWidth | `CGFloat` | 0.0 | Width of the item's border | | borderColor | `CGFloat` | nil | Color of the item's border | | shadowColor | `UIColor` | nil | Color of the item's shadow | | imageWidthRatio | `CGFloat` | 1.0 | Image width. A ratio of `1.0` means that the image width equals to 100% of the entire height of the item | | imageHeightRatio | `CGFloat` | 0.35 | Image height. A ratio of `0.35` means that image height equals to 35% of the entire height of the item | | imageBackground | `UIColor` | UIColor.clearColor | Background color of the image | | imageContentMode | `UIViewContentMode` | UIViewContentMode.scaleToFill | Display content mode of the image | | topTextInsets | `UIEdgeInsets` | (8.0, 8.0, 8.0, 8.0) | Inner margins of the top text label | | topTextFont | `UIFont` | UIFont.systemFont(ofSize: 16.0) | Font of the top text label | | topTextFontColor | `UIColor` | UIColor.blackColor | Color of the top text label | | topTextAlignment | `NSTextAlignment` | NSTextAlignment.center | Alignment of the top text label | | titleInsets | `UIEdgeInsets` | (8.0, 8.0, 8.0, 8.0) | Inner margins of the title label | | titleFont | `UIFont` | UIFont.systemFont(ofSize: 16.0) | Font of the title label | | titleFontColor | `UIColor` | UIColor.blackColor | Color of the title label | | titleAlignment | `NSTextAlignment` | NSTextAlignment.center | Alignment of the title label | | subtitleInsets | `UIEdgeInsets` | (8.0, 8.0, 8.0, 8.0) | Inner margins of the subtitle label | | subtitleFont | `UIFont` | UIFont.systemFont(ofSize: 16.0) | Font of the subtitle label | | subtitleFontColor | `UIColor` | UIColor.blackColor | Color of the subtitle label | | subtitleAlignment | `NSTextAlignment` | NSTextAlignment.center | Alignment of the subtitle label | | identifierInsets | `UIEdgeInsets` | (8.0, 8.0, 8.0, 8.0) | Inner margins of the identifier label | | identifierFont | `UIFont` | UIFont.systemFont(ofSize: 16.0) | Font of the identifier label | | identifierFontColor | `UIColor` | UIColor.blackColor | Color of the identifier label | | identifierAlignment | `NSTextAlignment` | NSTextAlignment.center | Alignment of the identifier label | | priceInsets | `UIEdgeInsets` | (8.0, 8.0, 8.0, 8.0) | Inner margins of the price label | | priceFont | `UIFont` | UIFont.systemFont(ofSize: 14.0) | Font of the price label | | priceFontColor | `UIColor` | UIColor.blackColor | Color of the price label | | priceAlignment | `NSTextAlignment` | NSTextAlignment.center | Alignment of the price label | | priceGroupSeparator | `String` | nil | Separator of price group | | priceDecimalSeparator | `String` | nil | Separator of price decimal | | priceCurrencyPosition | `ContentWidgetPriceCurrencyPosition` | .right | Determines the side on which the price currency is | | isSalePriceVisible | `Bool` | true | Flag determining whether to show the sale price label or not | | salePriceOrientation | `UILayoutConstraintAxis` | UILayoutConstraintAxis.Horizontal | Orientation of the sale price label | | isDiscountPercentageVisible | `Bool` | true | Flag determining whether to show the discount percentage label or not | | discountPercentageFont | `UIFont` | UIFont.systemFont(ofSize: 10.0) | Font of the discount percentage label | | discountPercentageFontColor | `UIColor` | UIColor.blackColor | Font of the discount percentage label | | regularPriceFont | `UIFont` | nil | Font of the regular price label | | regularPriceFontColor | `UIColor` | nil | Color of the sale regular label | | salePriceFont | `UIFont` | nil | Font of the sale price label | | salePriceFontColor | `UIColor` | nil | Color of the sale price label | | loyaltyPointsInsets | `UIEdgeInsets` | (8.0, 8.0, 8.0, 8.0) | Inner margins of the loyalty points label | | loyaltyPointsAlignment | `NSTextAlignment` | NSTextAlignment.left | Alignment of the loyalty points label | | loyaltyPointsNumberFont | `UIFont` | UIFont.systemFont(ofSize: 16.0) | Font of the loyalty points number label | | loyaltyPointsNumberFontColor | `UIColor` | UIColor.blackColor | Color of the loyalty points number label | | loyaltyPointsTextFont | `UIFont` | UIFont.systemFont(ofSize: 16.0) | Font of the loyalty points text label | | loyaltyPointsTextFontColor | `UIColor` | UIColor.blackColor | Color of the loyalty points text label | | loyaltyPointsText | `UIFont` | 'Loyalty points' | Text after the number of loyalty points | | badge | `SNRContentWidgetBadgeItemLayoutPartial` | nil | Optional badge view | | actionButton | `SNRContentWidgetImageButtonCustomAction` | nil | Optional button for your own custom action | ##### Example
```swift let itemLayout = ContentWidgetBasicProductItemLayout() itemLayout.imageWidthRatio = 1.0 itemLayout.imageHeightRatio = 0.4 itemLayout.borderWidth = 2.0 itemLayout.borderColor = UIColor.black itemLayout.shadowColor = UIColor.black itemLayout.cornerRadius = 12.0 ```
```objective-c SNRContentWidgetBasicProductItemLayout *itemLayout = [SNRContentWidgetBasicProductItemLayout new]; itemLayout.imageWidthRatio = 1.0f; itemLayout.imageHeightRatio = 0.4f; itemLayout.borderWidth = 2.0f; itemLayout.borderColor = [UIColor blackColor]; itemLayout.shadowColor = [UIColor blackColor]; itemLayout.cornerRadius = 12.0f; ```
### Interaction with the Widget --- #### Public Interface `load()` - Starts fetching data and creates a view structure of the widget. `isLoaded()` - Checks whether the widget is successfully loaded. `getView()` - Gets the root view of the whole widget view structure. #### Delegation [`ContentWidgetDelegate`](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#content-widget-delegate) is used to inform developers about the state of a widget. - `snr_widgetIsLoading(widget:isLoading:)` - Called when the widget’s loading state changes. It's an **optional** method. - `snr_widgetDidLoad(widget:)` - Called after the widget is loaded. It's a **required** method. - `snr_widgetDidNotLoad(widget:error:)` - Called when an error occurs while loading. It's a **required** method. - `snr_widgetDidChangeSize(widget:size:)` - Called when the widget size changes. It's an **optional** method. - `snr_widgetDidReceiveClickAction(widget:model:)` - Called when the customer clicks a widget item. It's a **required** method.
Check the [`ContentWidgetDelegate`](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#content-widget-delegate) section for more details.
#### Image Button Custom Action [`ContentWidgetImageButtonCustomAction`](/developers/mobile-sdk/class-reference/ios/content-widget#contentwidgetbasecustomaction) is used to add an image button to your widget (only if the item layout allows). You can add a button with a single state or make it selectable. ##### Parameters | Property | Type | Default | Description | | --- | --- | --- | --- | | predefinedActionType | [`ContentWidgetBaseCustomActionPredefiniedActionType`](/developers/mobile-sdk/class-reference/ios/content-widget#contentwidgetbasecustomactionpredefiniedactiontype) | .none | It determines which event is sent on click | | size | `CGSize` | CGSize.Zero | Button size | | position | `CGPoint` | CGPoint.Zero | Position | | backgroundColor | `UIColor` | UIColor.clearColor | Background color of the button | | tintColor | `UIColor` | UIColor.blackColor | Fill color of the button's image, if an asset supports it | | image | `UIImage` | nil | Button image | | isSelectable | `Bool` | nil | Flag determining whether the button is selectable | | selectedImage | `UIImage` | nil | Image of the button when the button is selected | | isSelected | `SNRContentWidgetImageButtonCustomActionIsSelectedBlock` | nil | Block/closure to be executed when the widget needs to determine the state of a button in the cell | | onReceiveClickAction | `SNRContentWidgetImageButtonCustomActionReceiveClickActionBlock` | nil | Block/closure to be executed when the button is clicked | ##### Block/Closures - `isSelected` - Called when the widget tries to determine button's state. The only one parameter is model of data for the cell (for example [`Recommendation`](/developers/mobile-sdk/class-reference/ios/recommendations-and-documents#recommendation)). It's an **optional** property. - `onReceiveClickAction` - Called when the button was clicked. Parameters are model of data for the cell (for example [`Recommendation`](/developers/mobile-sdk/class-reference/ios/recommendations-and-documents#recommendation)) and current state of button. It's an **optional** property. ### Sample Implementations --- #### Horizontal Slider This is an example with [`ContentWidgetHorizontalSliderLayout`](/developers/mobile-sdk/class-reference/ios/content-widget#contentwidgethorizontalsliderlayout). It always has fixed height, so after the widget is loaded, its content height can be calculated. That is why it is done in the `snr_widgetDidLoad(widget:)` method. The widget content size in a horizontal slider layout can be calculated by the `getSize()` method.
```swift class ContentWidgetHorizontalSliderSampleViewController: UIViewController, ContentWidgetDelegate { var widget: ContentWidget! @IBOutlet weak var widgetContainerView: UIView! // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() setupWidget() } // MARK: - Private func setupWidget() -> Void { let options = ContentWidgetRecommendationsOptions() options.slug = "similar" options.productID = "12345" options.mapping = { model in guard let imageURLString = model.attributes["imageLink"] as? String, let imageURL = URL(string: imageURLString), let title = model.attributes["title"] as? String, let priceDictionary = model.attributes["price"] as? [AnyHashable: Any], let priceValue = priceDictionary["value"] as? Double else { return nil } let dataModel = ContentWidgetRecommendationDataModel(imageURL: imageURL, title: title, priceCurrency: "PLN", price: NSNumber(value: priceValue), salePrice: nil) if let salePriceDictionary = model.attributes["salePrice"] as? [AnyHashable: Any], let salePriceValue = salePriceDictionary["value"] as? Double { dataModel.salePriceValue = NSNumber(floatLiteral: salePriceValue) } let badgeDataModel = ContentWidgetBadgeDataModel(backgroundColor: UIColor.black, textColor: UIColor.white, text: "Black Week") dataModel.badge = badgeDataModel return dataModel } let horizontalSliderLayout = ContentWidgetHorizontalSliderLayout() horizontalSliderLayout.insets = UIEdgeInsets(top: 16.0, left: 16.0, bottom: 16.0, right: 16.0) horizontalSliderLayout.itemSize = CGSize(width: 150, height: 350) horizontalSliderLayout.itemSpacing = 8.0 let itemLayout = ContentWidgetBasicProductItemLayout() itemLayout.imageWidthRatio = 1.0 itemLayout.imageHeightRatio = 0.4 itemLayout.borderWidth = 2.0 itemLayout.borderColor = UIColor.black itemLayout.shadowColor = UIColor.black itemLayout.cornerRadius = 12.0 let actionButton = ContentWidgetImageButtonCustomAction() actionButton.backgroundColor = UIColor.clear actionButton.tintColor = UIColor.black actionButton.image = UIImage(imageLiteralResourceName: "Shop Flow/icon_favorite_add") actionButton.isSelectable = true actionButton.selectedImage = UIImage(imageLiteralResourceName: "Shop Flow/icon_favorite_remove") actionButton.size = CGSize(width: 40, height: 40) actionButton.predefinedActionType = .sendLikeEvent actionButton.onReceiveClickAction = { model, isSelected in if let recommendationModel = model as? Recommendation { print("Content Widget did receive click action for action button \(recommendationModel.title)") } } actionButton.isSelected = { model in return false } itemLayout.actionButton = actionButton itemLayout.actionButtonPosition = CGPoint(x: (150.0 - 40 - 8), y: 8) let appearance = ContentWidgetAppearance(widgetLayout: horizontalSliderLayout, itemLayout: itemLayout) widget = ContentWidget(options: options, appearance: appearance) widget.delegate = self widget.load() } // MARK: - ContentWidgetDelegate func snr_widgetIsLoading(widget: ContentWidget, isLoading: Bool) { print("Content Widget is loading: \(isLoading)") } func snr_widgetDidLoad(widget: ContentWidget) { print("Content Widget did load") let widgetView: UIView = widget.getView() let widgetSize: CGSize = (widget.layout as! ContentWidgetHorizontalSliderLayout).getSize() widgetContainerView.addSubview(widgetView) widgetView.translatesAutoresizingMaskIntoConstraints = false widgetView.topAnchor.constraint(equalTo: widgetContainerView.topAnchor).isActive = true widgetView.bottomAnchor.constraint(equalTo: widgetContainerView.bottomAnchor).isActive = true widgetView.leftAnchor.constraint(equalTo: widgetContainerView.leftAnchor).isActive = true widgetView.rightAnchor.constraint(equalTo: widgetContainerView.rightAnchor).isActive = true widgetContainerView.heightAnchor.constraint(equalToConstant: widgetSize.height).isActive = true } func snr_widgetDidNotLoad(widget: ContentWidget, error: Error) { print("Content Widget did not load. Error: \(error.localizedDescription)") } func snr_widgetDidChangeSize(widget: ContentWidget, size: CGSize) { print("Content Widget did change size to: \(size)") } func snr_widgetDidReceiveClickAction(widget: ContentWidget, model: BaseModel) { if let recommendationModel = model as? Recommendation { print("Content Widget did receive click action for \(recommendationModel.title)") } } } ```
```objective-c @interface ContentWidgetHorizontalSliderSampleViewController : UIViewController @property (weak, nonatomic, nonnull, readwrite) IBOutlet UIView *widgetContainerView; @end @@implementation ContentWidgetHorizontalSliderSampleViewController () @property (strong, nonatomic, nullable, readwrite) SNRContentWidget *widget; @end @@implementation ContentWidgetHorizontalSliderSampleViewController #pragma mark - Lifecycle - (void)viewDidLoad { [super viewDidLoad]; [self setupWidget]; } #pragma mark - Private - (void)setupWidget { SNRContentWidgetOptions *options = [SNRContentWidgetOptions new]; options.slug = @"similar"; options.productID = @"12345"; options.mapping = ^(SNRContentWidgetRecommendationModel *model) { NSString *imageURLString = model.attributes[@"imageLink"]; NSString *imageURL = [[NSURL alloc] initWithString:imageURLString]; NSString *title = model.attributes[@"title"]; NSDictionary *priceDictionary = model.attributes[@"price"]; NSNumber *priceValue = priceDictionary[@"value"]; if (imageURL == nil || title == nil || priceValue == nil) { return nil; } SNRContentWidgetRecommendationDataModel *dataModel = [[SNRContentWidgetRecommendationDataModel alloc] initWithimageURL:imageURL title:title priceCurrency:@"PLN" price:priceValue salePrice:nil]; NSDictionary *salePriceDictionary = model.attributes[@"salePrice"]; NSNumber *salePriceValue = salePriceDictionary[@"value"]; if (salePrice != nil) { dataModel.salePriceValue = salePriceValue; } SNRContentWidgetBadgeDataModel *badgeDataModel = [[SNRContentWidgetBadgeDataModel alloc] initWithBackgroundColor:backgroundColor textColor:textColor text:text]; dataModel.badge = badgeDataModel; return dataModel; } SNRContentWidgetHorizontalSliderLayout *horizontalSliderLayout = [SNRContentWidgetHorizontalSliderLayout new]; horizontalSliderLayout.insets = UIEdgeInsetsMake(16.0f, 16.0f, 16.0f, 16.0f); horizontalSliderLayout.itemSize = CGSizeMake(150.0f, 350.0f); horizontalSliderLayout.itemSpacing = 8.0f; SNRContentWidgetBasicProductItemLayout *itemLayout = [SNRContentWidgetBasicProductItemLayout new]; itemLayout.imageWidthRatio = 1.0f; itemLayout.imageHeightRatio = 0.4f; itemLayout.borderWidth = 2.0f; itemLayout.borderColor = [UIColor blackColor]; itemLayout.shadowColor = [UIColor blackColor]; itemLayout.cornerRadius = 12.0f; SNRContentWidgetImageButtonCustomAction *actionButton = [SNRContentWidgetImageButtonCustomAction new]; actionButton.backgroundColor = [UIColor clearColor]; actionButton.tintColor = [UIColor blackColor]; actionButton.image = [UIImage imageNamed:@"Shop Flow/icon_favorite_add"]; actionButton.isSelectable = YES actionButton.selectedImage = [UIImage imageNamed:@"Shop Flow/icon_favorite_remove"]; actionButton.size = CGSizeMake(40.0f, 40.0f); actionButton.predefinedActionType = SNRContentWidgetBaseCustomActionPredefiniedActionTypeSendLikeEvent; actionButton.onReceiveClickAction = ^(SNRBaseModel *model, BOOL isSelected) { NSLog(@"Content Widget did receive click action for action button %@", ((SNRRecommednation *)recommendationModel.title)); }; actionButton.isSelected = ^(SNRBaseModel *model) { return NO; }; itemLayout.actionButton = actionButton itemLayout.actionButtonPosition = CGPointMake((150.0f - 40.0f - 8), 8.0f) SNRContentWidgetAppearance *appearance = [[SNRContentWidgetAppearance alloc] initWithLayout:horizontalSliderLayout andItemLayout:itemLayout]; SNRContentWidget *widget = [[SNRContentWidget alloc] initWithOptions:options andAppearance:appearance]; widget.delegate = self [widget load]; self.widget = widget; } #pragma mark - SNRContentWidgetDelegate - (void)SNR_widget:(SNRContentWidget *)widget isLoading:(BOOL)isLoading { NSLog(@"Content Widget is loading: %@", isLoading ?? @"true" : @"false"); } - (void)SNR_widgetDidLoad:(SNRContentWidget *)widget { NSLog(@"Content Widget did load"); UIView *widgetView = [widget getView]; CGSize widgetSize = [((SNRContentWidgetHorizontalSliderLayout *)widget.layout getSize]; [self.widgetContainerView addSubview:widgetView]; widgetView.translatesAutoresizingMaskIntoConstraints = NO; [widgetView.topAnchor constraintEqualTo:widgetContainerView.topAnchor].active = YES; [widgetView.bottomAnchor constraintEqualTo:widgetContainerView.bottomAnchor].active = YES; [widgetView.leftAnchor constraintEqualTo:widgetContainerView.leftAnchor].active = YES; [widgetView.rightAnchor constraintEqualTo:widgetContainerView.rightAnchor].active = YES; [widgetContainerView.heightAnchor constraintEqualToConstant:widgetSize.height].active = YES; } - (void)SNR_widget:(SNRContentWidget *)widget didNotLoadWithError:(NSError *)error { NSLog(@"Content Widget did not load. Error: %@", error.localizedDescription); } - (void)SNR_widget:(SNRContentWidget *)widget didChangeToSize:(CGSize)size { NSLog(@"Content Widget did change size to %@", NSStringFromCGSize(size)); } - (void)SNR_widget:(SNRContentWidget *)widget didReceiveClickActionForModel:(SNRBaseModel *)model { if ([model isKindOfClass:[SNRRecommendation class]] == YES) { SNRRecommendation *recommendationModel = ((SNRRecommendation *)model); NSLog(@"Content Widget did receive click action for %@", recommendationModel.title); } } @end ```
#### Grid View A basic example with [`ContentWidgetGridLayout`](/developers/mobile-sdk/class-reference/ios/content-widget#contentwidgetgridlayout) and `UITableViewController`. Remember that cells are prototyped. Initially, the height of the tenth row equals zero, because there is no possibility of getting the correct height of the widget. Before the widget is loaded, we don't know how many items it's going to contain. The widget view is flexible, so it fits the dimensions that you set up. If the height of the widget that you set is smaller than the total height of the generated grid, the content can be scrolled vertically. The grid's content height depends on: - The widget width that you set up - The number of items that have been loaded That is why the code below reloads the tenth row after the widget is loaded. Earlier, it was impossible to calculate the height correctly. In addition, the widget row is reloaded when the `snr_widgetDidChangeSize(widget:size:)` method is called. In this case, it's a required action, because the widget has pinned constraints to superview in a prototyped cell. The widget's content size changes with the tableview size, for example when the screen orientation changes, the widget's height needs to be re-calculated. Otherwise, the cell height may be larger that necessary. The total widget content size in a grid layout can be calculated by the `getSize(preferredWidth:)` method.
```swift class ContentWidgetGridViewSampleViewController: UITableViewController, ContentWidgetDelegate { var widget: ContentWidget! @IBOutlet weak var widgetContainerView: UIView! // MARK: - Lifecycle override func viewDidLoad() { super.viewDidLoad() setupWidget() } func setupWidget() -> Void { let options = ContentWidgetRecommendationsOptions() options.slug = "similar" options.productID = "12345" options.mapping = { model in guard let imageURLString = model.attributes["imageLink"] as? String, let imageURL = URL(string: imageURLString), let title = model.attributes["title"] as? String, let priceDictionary = model.attributes["price"] as? [AnyHashable: Any], let priceValue = priceDictionary["value"] as? Double else { return nil } let dataModel = ContentWidgetRecommendationDataModel(imageURL: imageURL, title: title, priceCurrency: "PLN", price: NSNumber(value: priceValue), salePrice: nil) if let salePriceDictionary = model.attributes["salePrice"] as? [AnyHashable: Any], let salePriceValue = salePriceDictionary["value"] as? Double { dataModel.salePriceValue = NSNumber(floatLiteral: salePriceValue) } let badgeDataModel = ContentWidgetBadgeDataModel(backgroundColor: UIColor.black, textColor: UIColor.white, text: "Black Week") dataModel.badge = badgeDataModel return dataModel } let gridLayout = ContentWidgetGridLayout() gridLayout.insets = UIEdgeInsets(top: 16.0, left: 16.0, bottom: 16.0, right: 16.0) gridLayout.itemSize = CGSize(width: 150.0, height: 350.0) gridLayout.horizontalItemSpacing = 8.0 gridLayout.verticalItemSpacing = 8.0 let itemLayout = ContentWidgetBasicProductItemLayout() itemLayout.imageWidthRatio = 1.0 itemLayout.imageHeightRatio = 0.4 itemLayout.borderWidth = 2.0 itemLayout.borderColor = UIColor.black itemLayout.shadowColor = UIColor.black itemLayout.cornerRadius = 12.0 actionButton.onReceiveClickAction = { model, isSelected in if let recommendationModel = model as? Recommendation { print("Content Widget did receive click action for action button \(recommendationModel.title)") } } actionButton.isSelected = { model in return false } itemLayout.actionButton = actionButton itemLayout.actionButtonPosition = CGPoint(x: (150.0 - 40.0 - 8.0), y: 8.0) let appearance = ContentWidgetAppearance(widgetLayout: gridLayout, itemLayout: itemLayout) widget = ContentWidget(options: options, appearance: appearance) widget.delegate = self widget.load() } // MARK: - UITableViewDataSource, UITableViewDelegate override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if indexPath.row == 10 { if widget != nil && widget.isLoaded() { return (widget.layout as! ContentWidgetGridLayout).getSize(preferredWidth: tableView.bounds.size.width).height } else { return 0 } } return 100.0 } // MARK: - ContentWidgetDelegate func snr_widgetIsLoading(widget: ContentWidget, isLoading: Bool) { print("Content Widget is loading: \(isLoading)") } func snr_widgetDidLoad(widget: ContentWidget) { print("Content Widget did load") view.addSubview(widgetView) widgetView = widget.getView() widgetContainerView.addSubview(widgetView) widgetView.translatesAutoresizingMaskIntoConstraints = false widgetView.topAnchor.constraint(equalTo: widgetContainerView.topAnchor).isActive = true widgetView.bottomAnchor.constraint(equalTo: widgetContainerView.bottomAnchor).isActive = true widgetView.leftAnchor.constraint(equalTo: widgetContainerView.leftAnchor).isActive = true widgetView.rightAnchor.constraint(equalTo: widgetContainerView.rightAnchor).isActive = true tableView.reloadData() } func snr_widgetDidNotLoad(widget: ContentWidget, error: Error) { print("Content Widget did not load. Error: \(error.localizedDescription)") } func snr_widgetDidChangeSize(widget: ContentWidget, size: CGSize) { print("Content Widget did change size to: \(size)") tableView.reloadData() } func snr_widgetDidReceiveClickAction(widget: ContentWidget, model: BaseModel) { if let recommendationModel = model as? Recommendation { print("Content Widget did receive click action for \(recommendationModel.title)") } } } ```
```objective-c @interface ContentWidgetGridViewSampleViewController : UITableViewController @property (weak, nonatomic, nonnull, readwrite) IBOutlet UIView *widgetContainerView; @end @@implementation ContentWidgetGridViewSampleViewController () @property (strong, nonatomic, nullable, readwrite) SNRContentWidget *widget; @end @@implementation ContentWidgetGridViewSampleViewController #pragma mark - Lifecycle - (void)viewDidLoad { [super viewDidLoad]; [self setupWidget]; } #pragma mark - Private - (void)setupWidget { SNRContentWidgetOptions *options = [SNRContentWidgetOptions new]; options.slug = @"similar"; options.productID = @"12345"; options.mapping = ^(SNRContentWidgetRecommendationModel *model) { NSString *imageURLString = model.attributes[@"imageLink"]; NSString *imageURL = [[NSURL alloc] initWithString:imageURLString]; NSString *title = model.attributes[@"title"]; NSDictionary *priceDictionary = model.attributes[@"price"]; NSNumber *priceValue = priceDictionary[@"value"]; if (imageURL == nil || title == nil || priceValue == nil) { return nil; } SNRContentWidgetRecommendationDataModel *dataModel = [[SNRContentWidgetRecommendationDataModel alloc] initWithimageURL:imageURL title:title priceCurrency:@"PLN" price:priceValue salePrice:nil]; NSDictionary *salePriceDictionary = model.attributes[@"salePrice"]; NSNumber *salePriceValue = salePriceDictionary[@"value"]; if (salePrice != nil) { dataModel.salePriceValue = salePriceValue; } SNRContentWidgetBadgeDataModel *badgeDataModel = [[SNRContentWidgetBadgeDataModel alloc] initWithBackgroundColor:backgroundColor textColor:textColor text:text]; dataModel.badge = badgeDataModel; return dataModel; } SNRContentWidgetGridLayout *gridLayout = [SNRContentWidgetGridLayout new]; gridLayout.insets = UIEdgeInsetsMake(16.0f, 16.0f, 16.0f, 16.0f); gridLayout.itemSize = CGSizeMake(150.0f, 350.0f); gridLayout.horizontalItemSpacing = 8.0f; gridLayout.verticalItemSpacing = 8.0f; SNRContentWidgetImageButtonCustomAction *actionButton = [SNRContentWidgetImageButtonCustomAction new]; actionButton.backgroundColor = [UIColor clearColor]; actionButton.tintColor = [UIColor blackColor]; actionButton.image = [UIImage imageNamed:@"Shop Flow/icon_favorite_add"]; actionButton.isSelectable = YES actionButton.selectedImage = [UIImage imageNamed:@"Shop Flow/icon_favorite_remove"]; actionButton.size = CGSizeMake(40.0f, 40.0f); actionButton.predefinedActionType = SNRContentWidgetBaseCustomActionPredefiniedActionTypeSendLikeEvent; actionButton.onReceiveClickAction = ^(SNRBaseModel *model, BOOL isSelected) { NSLog(@"Content Widget did receive click action for action button %@", ((SNRRecommednation *)recommendationModel.title)); }; actionButton.isSelected = ^(SNRBaseModel *model) { return NO; }; itemLayout.actionButton = actionButton itemLayout.actionButtonPosition = CGPointMake((150.0f - 40.0f - 8), 8.0f) SNRContentWidgetAppearance *appearance = [[SNRContentWidgetAppearance alloc] initWithLayout:gridLayout andItemLayout:itemLayout]; SNRContentWidget *widget = [[SNRContentWidget alloc] initWithOptions:options andAppearance:appearance]; widget.delegate = self; [widget load]; } #pragma mark - UITableViewDataSource, UITableViewDelegate - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return 10; } - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { if (indexPath.row == 10) { if (self.widget != nil && [self.widget isLoaded] == YES) { return [((ContentWidgetGridLayout *)widget.layout) getSizeForPreferredWidth:tableView.bounds.size.width].height; } else { return 0; } } return 100.0f; } #pragma mark - SNRContentWidgetDelegate - (void)SNR_widget:(SNRContentWidget *)widget isLoading:(BOOL)isLoading { NSLog(@"Content Widget is loading: %@", isLoading ?? @"true" : @"false"); } - (void)SNR_widgetDidLoad:(SNRContentWidget *)widget { NSLog(@"Content Widget did load"); UIView *widgetView = [self.widget getView]; CGSize widgetSize = [((SNRContentWidgetHorizontalSliderLayout *)widget.layout getSize]; [self.widgetContainerView addSubview:widgetView]; widgetView.translatesAutoresizingMaskIntoConstraints = NO; [widgetView.topAnchor constraintEqualTo:widgetContainerView.topAnchor].active = YES; [widgetView.bottomAnchor constraintEqualTo:widgetContainerView.bottomAnchor].active = YES; [widgetView.leftAnchor constraintEqualTo:widgetContainerView.leftAnchor].active = YES; [widgetView.rightAnchor constraintEqualTo:widgetContainerView.rightAnchor].active = YES; [widgetContainerView.heightAnchor constraintEqualToConstant:widgetSize.height].active = YES; } - (void)SNR_widget:(SNRContentWidget *)widget didNotLoadWithError:(NSError *)error { NSLog(@"Content Widget did not load. Error: %@", error.localizedDescription); } - (void)SNR_widget:(SNRContentWidget *)widget didChangeToSize:(CGSize)size { NSLog(@"Content Widget did change size to %@", NSStringFromCGSize(size)); } - (void)SNR_widget:(SNRContentWidget *)widget didReceiveClickActionForModel:(SNRBaseModel *)model { if ([model isKindOfClass:[SNRRecommendation class]] == YES) { SNRRecommendation *recommendationModel = ((SNRRecommendation *)model); NSLog(@"Content Widget did receive click action for %@", recommendationModel.title); } } @end ```
### More information --- You can find more information under the following links: - [Sample App on GitHub](https://github.com/Synerise/ios-sdk/tree/master/SampleAppSwift/4.1.0) - [Horizontal Slider implementation in the Sample App on GitHub](https://github.com/Synerise/synerise-ios-sdk/blob/master/SampleAppSwift/4.1.0/SampleAppSwift/Main/Developer%20Tools%20Flow/ViewControllers/ContentAPI/RecommendationsWidgetAsSliderTableViewController.swift) - [Grid implementation in the Sample App on GitHub](https://github.com/Synerise/synerise-ios-sdk/blob/master/SampleAppSwift/4.1.0/SampleAppSwift/Main/Developer%20Tools%20Flow/ViewControllers/ContentAPI/RecommendationsWidgetAsGridTableViewController.swift) # Huawei integration in Android SDK ## Enable integration in the Synerise platform Before you start integrating Huawei services in your app, you must configure the integration in Synerise platform. For instructions, see ["Huawei integration"](/docs/settings/tool/huawei-integration). ## Configuration In order to integrate Huawei Mobile Services with Synerise, you must add `.mesaggingServiceType(MessagingServiceType)` to your `Synerise.Builder`. We recommend passing `MessagingServiceType.HMS` as an argument when you build the app for AppGallery.
More information about `Synerise.Builder` is available in ["Configuration"](/developers/mobile-sdk/installation-and-configuration/android#configuration).
## Implementing Huawei notifications in applications 1. Register your service in the AndroidManifest:
<application
           android:name=".App"
           android:allowBackup="true"
           android:icon="@mipmap/ic_launcher"
           android:label="@string/app_name"
           android:roundIcon="@mipmap/ic_launcher_round"
           android:supportsRtl="true"
           android:theme="@style/AppTheme">
           ...
           <service
           android:name=".service.MyPushService"
           android:exported="false">
           <intent-filter>
               <action android:name="com.huawei.push.action.MESSAGING_EVENT" />
           </intent-filter>
       </service>
       </application>
2. In `onRegisterForPush`, pass the huaweiToken using the [`Client.registerForPush(token, pushAgreement)` method](/developers/mobile-sdk/method-reference/android/campaigns#register-for-push-notifications). 3. Add the Huawei registration method:
```kotlin override fun onNewToken(p0: String?, p1: Bundle?) { super.onNewToken(p0, p1) val call = Client.registerForPush(p0!!, true) call.execute( { Log.i(TAG, "Register for Push succeed: $p0") } ) { apiError: Any? -> Log.i(TAG, "Register for push failed:" + apiError.toString()) } Log.i(TAG, p0!!) Log.i(TAG, "receive token: $p0") } ```
1. Pass the incoming push notification payload to the `Injector` in your `HmsMessageService` implementation:
```kotlin val scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) override fun onMessageReceived(p0: RemoteMessage?) { super.onMessageReceived(p0) val data: Map = p0!!.dataOfMap scope.launch { Injector.handlePushPayload(data) } } ```
For more information, visit [Huawei Codelab](https://developer.huawei.com/consumer/en/codelab/HMSPushKit/index.html#0).
## Links and Deep Links In order to implement links and deep links, refer to [this](/developers/mobile-sdk/campaigns/action-handling#handling-actions-from-campaigns-in-android) instruction. ## Configuring notification encryption Instructions for encrypting push notifications are available [here](/developers/mobile-sdk/configuring-push-notifications/android#configure-notification-encryption). # Customer authentication --- ## Set Client State listener --- This method sets callbacks for a customer's state changes. **Declared In:** lib/main/modules/ClientModule.js **Related To:** [ClientStateChangeListener](/developers/mobile-sdk/listeners-and-delegates/react-native-listeners#client-state-listener) **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public setClientStateChangeListener(listener: IClientStateChangeListener)
**Discussion:** Learn more about the methods and the purpose of this listener [here](/developers/mobile-sdk/listeners-and-delegates/react-native-listeners#client-state-listener). ## Register customer account --- This method registers a new customer with an email, password, and optional data. This method requires the context object with a customer’s email, password, and optional data. Omitted fields are not modified. Depending on the backend configuration, the account may require activation. For details, see [customer registration](/developers/mobile-sdk/user-identification-and-authorization/overview). Do not allow signing in again (or signing up) when a customer is already signed in. Sign the customer out first. Do not create multiple instances nor call this method multiple times before execution. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_REGISTER_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** lib/main/modules/ClientModule.js **Related To:** [ClientAccountRegisterContext](/developers/mobile-sdk/class-reference/react-native/client#clientaccountregistercontext) **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public registerAccount(context: ClientAccountRegisterContext, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **context** | [ClientAccountRegisterContext](/developers/mobile-sdk/class-reference/react-native/client#clientaccountregistercontext) | yes | - | Object with the customer's email, password, and other optional data | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript let email = "EMAIL"; let password = "PASSWORD"; let context = new ClientAccountRegisterContext(email, password); context.phone = '123456789'; context.customId = '000111'; context.firstName = 'John'; context.lastName = 'Rise'; context.sex = ClientSex.Male; context.company = 'Synerise'; context.address = 'Marszałkowska'; context.city = 'Warszawa'; context.province = 'Mazowieckie'; context.zipCode = '00-000'; context.countryCode = 'PL'; context.agreements = new ClientAgreements({ email: true, sms: false, push: true, bluetooth: false, rfid: true, wifi: false }); context.attributes = { ATTRIBUTE_1: 'ATTRIBUTE_1' } context.tags = ['TAG_1', 'TAG_2'] Synerise.Client.registerAccount(context, function() { // success }, function(error) { // failure }); ```
## Request customer account activation --- This method requests sending an email with a URL that confirms the registration and activates the account. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_CONFIRMATION_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public requestAccountActivation(email: string, onSuccess: () => void, onError: (error: Error) => void)
Before version 1.0.0, this method was called `activateAccount`.
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | string | yes | - | Customer's email | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```TypeScript Synerise.Client.requestAccountActivation("EMAIL", function() { // success }, function(error) { // failure }); ```
## Confirm customer account activation --- This method confirms a customer account with the confirmation token. This method is a global operation and doesn't require customer authentication.
Returns the HTTP 400 status code if the account is already confirmed or 404 if the account does not exist.
The API key must have the `SAUTH_CONFIRMATION_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public confirmAccountActivation(token: string, onSuccess: () => void, onError: (error: Error) => void)
Before version 1.0.0, this method was called `confirmAccount`.
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **token** | string | yes | - | Customer's token provided by email | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Client.confirmAccountActivation("TOKEN", function() { // success }, function(error) { // failure }); ```
## Request customer account activation by pin --- This method requests a customer's account registration process with the PIN code. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_PIN_CODE_RESEND_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public requestAccountActivationByPin(email: string, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | string | yes | - | Customer's email | | **onSuccess** | Function | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. ## Confirm customer account activation by pin --- This method confirms a customer's account registration process with the PIN code. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_PIN_CODE_RESEND_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public confirmAccountActivationByPin(pinCode: string, email: string, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **pinCode** | string | yes | - | Code sent to a customer's email | | **email** | string | yes | - | Customer's email | | **onSuccess** | Function | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. ## Sign in a customer --- This method signs a customer in to obtain a JSON Web Token (JWT) which can be used in subsequent requests. The SDK will refresh the token before each call if it is about to expire (but not expired). Do NOT allow signing in again (or signing up) when a customer is already signed in. First, sign the customer out. Do NOT create multiple instances nor call this method multiple times before execution. **Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public signIn(email: string, password: string, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | string | yes | - | Customer's email | | **password** | string | yes | - | Customer's password | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript let email = "EMAIL"; let password = "PASSWORD"; Synerise.Client.signIn(email, password, function() { // success }, function(error) { // failure }); ```
## Sign in a customer conditionally --- This method signs a customer in to obtain a JSON Web Token (JWT) which can be used in subsequent requests. The SDK will refresh the token before each call if it is about to expire (but not expired). Do NOT allow signing in again (or signing up) when a customer is already signed in. First, sign the customer out. Do NOT create multiple instances nor call this method multiple times before execution. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | **Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public signInConditionally(email: string, password: string, onSuccess: (authResult: ClientConditionalAuthResult) => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | string | yes | - | Customer's email | | **password** | string | yes | - | Customer's password | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript let email = "EMAIL"; let password = "PASSWORD"; Synerise.Client.signInConditionally(email, password, function(clientConditionalAuthResult) { // success }, function(error) { // failure }); ```
## Authenticate customer by IdentityProvider --- This method authenticates a customer with OAuth, Facebook, Google, Apple, or Synerise. If an account for the customer does not exist and the identity provider is different than Synerise, this request creates an account. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.7.6 | 3.8.0 | 0.9.19 | 0.3.0 | **Declared In:** lib/main/modules/ClientModule.js **Related To:** [ClientAuthContext](/developers/mobile-sdk/class-reference/react-native/client#clientauthcontext) [ClientIdentityProvider](/developers/mobile-sdk/class-reference/react-native/client#clientidentityprovider) **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public authenticate(token: string, provider: ClientIdentityProvider, context: ClientAuthContext, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **token** | string | yes | - | Token retrieved from provider | | **clientIdentityProvider** | [ClientIdentityProvider](/developers/mobile-sdk/class-reference/react-native/client#clientidentityprovider) | yes | - | Provider of your token | | **context** | [ClientAuthContext](/developers/mobile-sdk/class-reference/react-native/client#clientauthcontext) | yes | - | Object which wraps around agreements, attributes and authId | | **onSuccess** | Function | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Client.authenticate(token, ClientIdentityProvider.Oauth, context, function() { // success }, function(error) { // failure }) ```
## Authenticate customer conditionally by IdentityProvider --- This method authenticates a customer with OAuth, Facebook, Google, Apple, or Synerise. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | **Declared In:** lib/main/modules/ClientModule.js **Related To:** [ClientAuthContext](/developers/mobile-sdk/class-reference/react-native/client#clientauthcontext) [ClientIdentityProvider](/developers/mobile-sdk/class-reference/react-native/client#clientidentityprovider) **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public authenticateConditionally(token: string, provider: ClientIdentityProvider, context: ClientAuthContext, onSuccess: (authResult: ClientConditionalAuthResult) => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **token** | string | yes | - | Token retrieved from provider | | **clientIdentityProvider** | [ClientIdentityProvider](/developers/mobile-sdk/class-reference/react-native/client#clientidentityprovider) | yes | - | Provider of your token | | **context** | [ClientAuthContext](/developers/mobile-sdk/class-reference/react-native/client#clientauthcontext) | no | - | Object which contains agreements, attributes, and identifier of authorization | | **onSuccess** | Function | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Client.authenticateConditionally(token, ClientIdentityProvider.Oauth, context, function(clientConditionalAuthResult) { // success }, function(error) { // failure }) ```
## Authenticate customer via Simple Profile Authentication --- This method authenticates a customer with Simple Profile Authentication. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.14.0 | 5.7.1 | 0.15.0 | 0.7.0 |
When you use this method, you must set a request validation salt by using the `Synerise.setRequestValidationSalt(_:)` method (if salt is enabled for Simple Profile Authentication).
The API key must have the `SAUTH_SIMPLE_AUTH_CREATE` from the **Auth** group.
**Declared In:** lib/main/modules/ClientModule.js **Related To:** [ClientSimpleAuthenticationData](/developers/mobile-sdk/class-reference/react-native/client#clientsimpleauthenticationdata) **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public simpleAuthentication(data: ClientSimpleAuthenticationData, authID: string, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **data** | [ClientSimpleAuthenticationData](/developers/mobile-sdk/class-reference/react-native/client#clientsimpleauthenticationdata) | yes | - | Object which contains customer data | | **authID** | string | yes | - | Required identifier of authorization | | **onSuccess** | Function | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```TypeScript let data: ClientSimpleAuthenticationData = new ClientSimpleAuthenticationData(); context.email = "EMAIL"; context.firstName = "FIRST_NAME"; let authID: String = "AUTH_ID" Synerise.Client.simpleAuthentication(data, authID, function() { // success }, function(error) { // failure }) ```
## Check if a customer is signed in (via RaaS, OAuth, Facebook, Apple) --- This method checks if a customer is signed in (via Synerise Authentication - RaaS, OAuth, Facebook, Apple). **Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public isSignedIn(): boolean
**Return Value:** **true** if the customer is signed in, otherwise returns **false**. **Example:**
```JavaScript let isSignedIn = Synerise.Client.isSignedIn(); ```
## Check if a customer is signed in (via Simple Profile Authentication) --- This method checks if a customer is signed in (via Simple Profile Authentication). | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.14.0 | 5.7.1 | 0.15.0 | 0.7.0 | **Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public isSignedInViaSimpleAuthentication(): boolean
**Return Value:** **true** if the customer is signed in (via Simple Profile Authentication), otherwise returns **false**. **Example:**
```JavaScript let isSignedIn = Synerise.Client.isSignedInViaSimpleAuthentication(); ```
## Sign out a customer --- This method signs out a customer out.
This method works with every authentication type (via Synerise, External Provider, OAuth or Simple Profile Authentication).
**Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public signOut()
**Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Client.signOut(); ```
## Sign out customer with mode or from all devices --- This method signs out a customer out with a chosen mode and Determines if the method should sign out all devices. Available modes: - `.signOut` mode signs out the customer. - `.signOutWithSessionDestroy` mode signs out the customer and additionally, clears the anonymous session and regenerates the customer UUID. The `fromAllDevices` parameter determines whether the method should notify the backend to sign out all devices. **IMPORTANT: It is an asynchronous method.** | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.11.0 | 5.1.0 | 0.14.0 | 1.0.0 |
This method works with every authentication type (via Synerise, External Provider, OAuth or Simple Profile Authentication).
**Declared In:** lib/main/modules/ClientModule.js **Related To:** [ClientSignOutMode](/developers/mobile-sdk/class-reference/react-native/client#clientsignoutmode) **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public signOutWithMode(mode: ClientSignOutMode, fromAllDevices: boolean, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **mode** | [ClientSignOutMode](/developers/mobile-sdk/class-reference/react-native/client#clientsignoutmode) | yes | - | Mode of signing out | | **fromAllDevices** | Bool | yes | - | Determines if the method should sign out all devices | **Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Client.signOutWithMode( ClientSignOutMode.SignOutWithSessionDestroy, true, () => { this.setState({ isLoading: false, isSignedIn: true, }) }, (error) => { this.setState({ isLoading: false, isSignedIn: false, }) console.log('ERROR: ' + error.message); } ) ```
## Deprecated methods ### Authenticate customer by OAuth with registration --- This method authenticates a customer with OAuth. If an account for the customer does not exist, this request creates an account. | Available on | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.11 | 3.6.13 | 0.9.12 | n/a | | Deprecated in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | n/a |
Returns the HTTP 401 status code if the provided access token and/or API Key is invalid.
**Declared In:** lib/main/modules/ClientModule.js **Related To:** [ClientOAuthAuthenticationContext](/developers/mobile-sdk/class-reference/react-native/client#clientoauthauthenticationcontext) **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public authenticateByOAuth(accessToken: string, context: ClientOAuthAuthenticationContext, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **accessToken** | string | yes | - | OAuth Access Token | | **clientOAuthContext** | [ClientOAuthAuthenticationContext](/developers/mobile-sdk/class-reference/react-native/client#clientoauthauthenticationcontext) | yes | - | Object which contains agreements, attributes, and identifier of authorization | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Client.authenticateByOAuth(token, context, function() { // success }, function(error) { // failure }) ```
### Authenticate customer by OAuth without registration --- This method authenticates a customer with OAuth. | Available on | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.11 | 3.6.13 | 0.9.12 | n/a | | Deprecated in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | n/a |
Returns the HTTP 401 status code if the provided access token and/or API Key is invalid.
**Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public authenticateByOAuthIfRegistered(accessToken: string, authID: string | null, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **accessToken** | string | yes | - | OAuth Access Token | | **authID** | string | no | null | Optional identifier of authorization | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error |
**authID** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Client.authenticateByOAuthIfRegistered(accessToken, authID, function() { // success }, function(error) { // failure }) ```
### Authenticate customer by Facebook with registration --- This method authenticates a customer with Facebook. If an account for the customer does not exist, this request creates an account. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.3.8 | 3.3.0 | 0.9.7 | n/a | | Deprecated in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | n/a |
Returns the HTTP 401 status code if the provided Facebook token and/or API Key is invalid.
**Declared In:** lib/main/modules/ClientModule.js **Related To:** [ClientFacebookAuthenticationContext](/developers/mobile-sdk/class-reference/react-native/client#clientfacebookauthenticationcontext) **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public authenticateByFacebook(facebookToken: string, context: ClientFacebookAuthenticationContext, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **facebookToken** | string | yes | - | Facebook Access Token | | **clientFacebookAuthenticationContext** | [ClientFacebookAuthenticationContext](/developers/mobile-sdk/class-reference/react-native/client#clientfacebookauthenticationcontext) | yes | - | Object which contains agreements, attributes, and identifier of authorization | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Client.authenticateByFacebook(token, clientFacebookAuthenticationContext, function(clientConditionalAuthResult) { // success }, function(error) { // failure }) ```
### Authenticate customer by Facebook without registration --- This method authenticates a customer with Facebook. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.3.8 | 3.3.0 | 0.9.7 | n/a | | Deprecated in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | n/a |
Returns the HTTP 401 status code if the provided Facebook token and/or API Key is invalid.
**Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public authenticateByFacebookIfRegistered(facebookToken: string, authID: string | null, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **facebookToken** | string | yes | - | Facebook Access Token | | **authID** | string | no | null | Optional identifier of authorization | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error |
**authID** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Client.authenticateByFacebookIfRegistered(facebookToken, authID, function() { // success }, function(error) { // failure }) ```
### Authenticate customer by Sign in with Apple with registration --- This method authenticates a customer with Sign In With Apple. If an account for the customer does not exist, this request creates an account. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.11 | n/a | 0.9.12 | n/a | | Deprecated in: | 3.7.6 | n/a | 0.9.19 | n/a | | Removed in: | 5.0.0 | n/a | 1.0.0 | n/a | **Declared In:** lib/main/modules/ClientModule.js **Related To:** [ClientAppleSignInAuthenticationContext](/developers/mobile-sdk/class-reference/react-native/client#clientapplesigninauthenticationcontext) **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public authenticateByAppleSignIn(identityToken: string, context: ClientAppleSignInAuthenticationContext, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **identityToken** | string | yes | - | Apple Identity Token | | **context** | [ClientAppleSignInAuthenticationContext](/developers/mobile-sdk/class-reference/react-native/client#clientapplesigninauthenticationcontext) | yes | - | Object which contains agreements, attributes, and identifier of authorization | | **success** | Function | no | - | Function to be executed when the operation is completed successfully | | **failure** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. ### Authenticate customer by Sign in with Apple without registration --- This method authenticates a customer with Sign In With Apple. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.11 | 3.6.13 | 0.9.12 | n/a | | Deprecated in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | n/a | **Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public authenticateByAppleSignInIfRegistered(identityToken: string, authID: string, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **identityToken** | string | yes | - | Apple Identity Token | | **authID** | string | no | null | Optional identifier of authorization | | **success** | Function | no | - | Function to be executed when the operation is completed successfully | | **failure** | Function | no | - | Function to be executed when the operation is completed with an error |
**authID** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** No value is returned. # Client ### ClientIdentityProvider **Declared In:** Headers/SNRClientIdentityProvider.h **Declaration:**
```Swift enum ClientIdentityProvider: Int { synerise, oauth, simpleAuth, facebook, apple, google } ```
```Objective-C typedef NS_ENUM(NSUInteger, SNRClientIdentityProvider) { SNRClientIdentityProviderSynerise, SNRClientIdentityProviderOAuth, SNRClientIdentityProviderSimpleAuth, SNRClientIdentityProviderFacebook, SNRClientIdentityProviderApple, SNRClientIdentityProviderGoogle } ```
**Functions:** Converts from **ClientIdentityProvider** to **String**.
```Swift func SNR_ClientIdentityProviderToString(_: ClientIdentityProvider) -> String ```
```Objective-C NSString * SNR_ClientIdentityProviderToString(SNRClientIdentityProvider type) ```
--- Converts from **String** to **ClientIdentityProvider**.
```Swift func SNR_StringToClientIdentityProvider(_: String) -> ClientIdentityProvider ```
```Objective-C SNRClientIdentityProvider SNR_StringToClientIdentityProvider(NSString * _Nullable string) ```
--- --- ### ClientConditionalAuthenticationContext **Declared In:** Headers/SNRClientConditionalAuthContext.h **Related To:** [ClientAgreements](/developers/mobile-sdk/class-reference/ios/client#clientagreements) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class ClientConditionalAuthContext: BaseModel ```
```Objective-C @interface SNRClientConditionalAuthContext : SNRBaseModel ```
**Properties:** Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/ios/client#clientagreements) | yes | nil | Object that stores all agreements of a customer | | **attributes** | [AnyHashable: Any] | yes | [] | Additional custom attributes of a customer | **Initializers:**
```Swift init() ```
```Objective-C - (instancetype)init ```
--- --- ### ClientAuthenticationContext **Declared In:** Headers/SNRClientAuthenticationContext.h **Related To:** [ClientAgreements](/developers/mobile-sdk/class-reference/ios/client#clientagreements) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class ClientAuthenticationContext: BaseModel ```
```Objective-C @interface SNRClientAuthenticationContext : SNRBaseModel ```
**Properties:** Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/ios/client#clientagreements) | yes | nil | Object that stores all agreements of a customer | | **attributes** | [AnyHashable: Any] | yes | [] | Additional custom attributes of a customer | **Initializers:**
```Swift init() ```
```Objective-C - (instancetype)init ```
--- --- ### ClientConditionalAuthResult **Declared In:** Headers/SNRClientConditionalAuthResult.h **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class ClientConditionalAuthResult: BaseModel ```
```Objective-C @interface SNRClientConditionalAuthResult : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **isSuccess** | Bool | no | Result of authentication operation | | **token** | String | yes | Token as a raw string | | **status** | [ClientConditionalAuthStatus](/developers/mobile-sdk/class-reference/ios/client#clientconditionalauthstatus) | no | Status of the authentication | | **conditions** | [AnyObject] | yes | Authentication conditions |
All properties are read-only.
--- --- ### ClientConditionalAuthStatus **Declared In:** Headers/SNRClientConditionalAuthStatus.h **Declaration:**
```Swift enum ClientConditionalAuthStatus: Int { success, unauthorized, activationRequired, registrationRequired, approvalRequired, termsAcceptanceRequired, mfaRequired, unknown } ```
```Objective-C typedef NS_ENUM(NSUInteger, SNRClientConditionalAuthStatus) { SNRClientConditionalAuthStatusSuccess, SNRClientConditionalAuthStatusUnauthorized, SNRClientConditionalAuthStatusActivationRequired, SNRClientConditionalAuthStatusRegistrationRequired, SNRClientConditionalAuthStatusApprovalRequired, SNRClientConditionalAuthStatusTermsAcceptanceRequired, SNRClientConditionalAuthStatusMFARequired, SNRClientConditionalAuthStatusUnknown } ```
**Functions:** Converts from **ClientConditionalAuthStatus** to **String**.
```Swift func SNR_ClientConditionalAuthStatusToString(_: ClientConditionalAuthStatus) -> String ```
```Objective-C NSString * SNR_ClientConditionalAuthStatusToString(SNRClientConditionalAuthStatus status) ```
--- Converts from **String** to **ClientConditionalAuthStatus**.
```Swift func SNR_StringToClientConditionalAuthStatus(_: String) -> ClientConditionalAuthStatus ```
```Objective-C SNRClientConditionalAuthStatus SNR_StringToClientConditionalAuthStatus(NSString * _Nullable string) ```
--- --- ### ClientSimpleAuthenticationData **Declared In:** Headers/SNRClientSimpleAuthenticationData.h **Related To:** [ClientSex](/developers/mobile-sdk/class-reference/ios/client#clientsex) [ClientAgreements](/developers/mobile-sdk/class-reference/ios/client#clientagreements) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class ClientSimpleAuthenticationData: BaseModel ```
```Objective-C @interface SNRClientSimpleAuthenticationData : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **email** | String | yes | Customer's email | | **phone** | String | yes | Customer's phone | | **customId** | String | yes | Customer's custom ID | | **uuid** | String | yes | Customer's UUID | | **firstName** | String | yes | Customer's first name | | **lastName** | String | yes | Customer's last name | | **displayName** | String | yes | Customer's display name | | **sex** | [ClientSex](/developers/mobile-sdk/class-reference/ios/client#clientsex) | yes | Customer's sex | | **company** | String | yes | Customer's company | | **address** | String | yes | Customer's address | | **city** | String | yes | Customer's city | | **province** | String | yes | Customer's province | | **zipCode** | String | yes | Customer's ZIP code | | **countryCode** | String | yes | Customer's country code | | **birthDate** | String | yes | Customer's birthdate | | **avatarUrl** | String | yes | Customer's avatar URL | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/ios/client#clientagreements) | yes | Customer's agreements | | **attributes** | [AnyHashable: Any] | yes | Customer's attributes | **Initializers:**
```Swift init() ```
```Objective-C - (instancetype)init ```
--- --- ### ClientSessionEndReason **Declared In:** Headers/SNRClientSessionEndReason.h **Declaration:**
```Swift enum ClientSessionEndReason: Int { userSignOut, systemSignOut, sessionExpiration, securityException, clientRejected, userAccountDeleted } ```
```Objective-C typedef NS_ENUM(NSUInteger, SNRClientSessionEndReason) { SNRClientSessionEndReasonUserSignOut, SNRClientSessionEndReasonSystemSignOut, SNRClientSessionEndReasonSessionExpiration, SNRClientSessionEndReasonSessionDestroyed, SNRClientSessionEndReasonSecurityException, SNRClientSessionEndReasonClientRejected, SNRClientSessionEndReasonUserAccountDeleted } ```
--- --- ### ClientSignOutMode **Declared In:** Headers/SNRClientSignOutMode.h **Declaration:**
```Swift enum ClientSignOutMode: Int { .signOut, .signOutWithSessionDestroy } ```
```Objective-C typedef NS_ENUM(NSUInteger, SNRClientSignOutMode) { SNRClientSignOutModeSignOut, SNRClientSignOutModeSignOutWithSessionDestroy } ```
--- --- ### ClientAccountInformation **Declared In:** Headers/SNRClientAccountInformation.h **Related To:** [ClientSex](/developers/mobile-sdk/class-reference/ios/client#clientsex) [ClientAgreements](/developers/mobile-sdk/class-reference/ios/client#clientagreements) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Conforms To:** [NSSecureCoding](https://developer.apple.com/documentation/foundation/nssecurecoding) **Declaration:**
```Swift class ClientAccountInformation: BaseModel ```
```Objective-C @interface SNRClientAccountInformation : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **clientId** | Int | no | Customer's ID | | **email** | String | no | Customer's email | | **phone** | String | yes | Customer's phone | | **customId** | String | yes | Customer's custom ID | | **uuid** | String | no | Customer's UUID | | **firstName** | String | yes | Customer's first name | | **lastName** | String | yes | Customer's last name | | **displayName** | String | yes | Customer's display name | | **sex** | [ClientSex](/developers/mobile-sdk/class-reference/ios/client#clientsex) | no | Customer's sex | | **company** | String | yes | Customer's company | | **address** | String | yes | Customer's address | | **city** | String | yes | Customer's city | | **province** | String | yes | Customer's province | | **zipCode** | String | yes | Customer's ZIP code | | **countryCode** | String | yes | Customer's country code | | **birthDate** | String | yes | Customer's birthdate | | **lastActivityDate** | Date | no | Customer's last activity date | | **avatarUrl** | String | yes | Customer's avatar URL | | **anonymous** | Bool | no | Customer's anonymous flag | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/ios/client#clientagreements) | no | Customer's agreements | | **attributes** | [AnyHashable: Any] | yes | Customer's attributes | | **tags** | [String] | yes | Customer's tags |
All properties are read-only.
--- --- ### ClientUpdateAccountBasicInformationContext **Declared In:** Headers/SNRClientUpdateAccountBasicInformationContext.h **Related To:** [ClientSex](/developers/mobile-sdk/class-reference/ios/client#clientsex) [ClientAgreements](/developers/mobile-sdk/class-reference/ios/client#clientagreements) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Conforms To:** [NSSecureCoding](https://developer.apple.com/documentation/foundation/nssecurecoding) **Declaration:**
```Swift class ClientUpdateAccountBasicInformationContext: BaseModel ```
```Objective-C @interface SNRClientUpdateAccountBasicInformationContext : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **firstName** | String | yes | Customer's first name | | **lastName** | String | yes | Customer's last name | | **displayName** | String | yes | Customer's display name | | **sex** | [ClientSex](/developers/mobile-sdk/class-reference/ios/client#clientsex) | yes | Customer's sex | | **phone** | String | yes | Customer's phone | | **company** | String | yes | Customer's company | | **address** | String | yes | Customer's address | | **city** | String | yes | Customer's city | | **province** | String | yes | Customer's province | | **zipCode** | String | yes | Customer's ZIP code | | **countryCode** | String | yes | Customer's country code | | **birthDate** | String | yes | Customer's birthdate | | **avatarUrl** | String | yes | Customer's avatar URL | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/ios/client#clientagreements) | no | Customer's agreements | | **attributes** | [AnyHashable: Any] | yes | Customer's attributes | **Initializers:**
```Swift init() ```
```Objective-C - (instancetype)init ```
--- --- ### ClientUpdateAccountContext **Declared In:** Headers/SNRClientUpdateAccountContext.h **Related To:** [ClientSex](/developers/mobile-sdk/class-reference/ios/client#clientsex) [ClientAgreements](/developers/mobile-sdk/class-reference/ios/client#clientagreements) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Conforms To:** [NSSecureCoding](https://developer.apple.com/documentation/foundation/nssecurecoding) **Declaration:**
```Swift class ClientUpdateAccountContext: BaseModel ```
```Objective-C @interface SNRClientUpdateAccountContext : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **email** | String | yes | Customer's email | | **phone** | String | yes | Customer's phone | | **customId** | String | yes | Customer's custom ID | | **uuid** | String | yes | Customer's UUID | | **firstName** | String | yes | Customer's first name | | **lastName** | String | yes | Customer's last name | | **displayName** | String | yes | Customer's display name | | **sex** | [ClientSex](/developers/mobile-sdk/class-reference/ios/client#clientsex) | yes | Customer's sex | | **company** | String | yes | Customer's company | | **address** | String | yes | Customer's address | | **city** | String | yes | Customer's city | | **province** | String | yes | Customer's province | | **zipCode** | String | yes | Customer's ZIP code | | **countryCode** | String | yes | Customer's country code | | **birthDate** | String | yes | Customer's birthdate | | **avatarUrl** | String | yes | Customer's avatar URL | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/ios/client#clientagreements) | no | Customer's agreements | | **attributes** | [AnyHashable: Any] | yes | Customer's attributes | **Initializers:**
```Swift init() ```
```Objective-C - (instancetype)init ```
--- --- ### ClientRegisterAccountContext **Declared In:** Headers/SNRClientRegisterAccountContext.h **Related To:** [ClientSex](/developers/mobile-sdk/class-reference/ios/client#clientsex) [ClientAgreements](/developers/mobile-sdk/class-reference/ios/client#clientagreements) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class ClientRegisterAccountContext: BaseModel ```
```Objective-C @interface SNRClientRegisterAccountContext : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **email** | String | no | Customer's email | | **password** | String | no | Customer's password | | **firstName** | String | yes | Customer's first name | | **lastName** | String | yes | Customer's last name | | **customId** | String | yes | Customer's custom ID | | **sex** | [ClientSex](/developers/mobile-sdk/class-reference/ios/client#clientsex) | yes | Customer's sex | | **phone** | String | yes | Customer's phone | | **company** | String | yes | Customer's company | | **address** | String | yes | Customer's address | | **city** | String | yes | Customer's city | | **province** | String | yes | Customer's province code | | **zipCode** | String | yes | Customer's ZIP code | | **countryCode** | String | yes | Customer's country code | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/ios/client#clientagreements) | yes | Customer's agreements | | **attributes** | [AnyHashable: Any] | yes | Customer's attributes | **Initializers:**
```Swift init(email: String, password: String) ```
```Objective-C - (instancetype)initWithEmail:(nonnull NSString *)email andPassword:(nonnull NSString *)password ```
--- --- ### ClientPasswordResetRequestContext **Declared In:** Headers/SNRClientPasswordResetRequestContext.h **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class ClientPasswordResetRequestContext: BaseModel ```
```Objective-C @interface SNRClientPasswordResetRequestContext : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **email** | Bool | no | Customer's email | **Initializers:**
```Swift init(email: String) ```
```Objective-C - (instancetype)initWithEmail:(nonnull NSString *)email ```
--- --- ### ClientPasswordResetConfirmationContext **Declared In:** Headers/SNRClientPasswordResetConfirmationContext.h **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class ClientPasswordResetConfirmationContext: BaseModel ```
```Objective-C @interface SNRClientPasswordResetConfirmationContext : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **password** | String | no | Customer's password | | **token** | String | no | Customer's token | **Initializers:**
```Swift init(password: String, token: String) ```
```Objective-C - (instancetype)initWithPassword:(nonnull NSString *)password andToken:(nonnull NSString *)token ```
--- --- ### ClientSex **Declared In:** Headers/SNRClientSex.h **Declaration:**
```Swift enum ClientSex: Int { notSpecified, male, female, other } ```
```Objective-C typedef NS_ENUM(NSUInteger, SNRClientSex) { SNRClientSexNotSpecified = 0, SNRClientSexMale, SNRClientSexFemale, SNRClientSexOther, } ```
**Functions:** Converts from **ClientSex** to **String**.
```Swift func SNR_ClientSexToString(_: ClientSex) -> String ```
```Objective-C NSString * SNR_ClientSexToString(SNRClientSex type) ```

Converts from **String** to **ClientSex**.
```Swift func SNR_StringToClientSex(_: String) -> ClientSex ```
```Objective-C SNRClientSex SNR_StringToClientSex(NSString * _Nullable string) ```
--- --- ### ClientAgreements **Declared In:** Headers/SNRClientAgreements.h **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Conforms To:** [NSSecureCoding](https://developer.apple.com/documentation/foundation/nssecurecoding) [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class ClientAgreements: BaseModel ```
```Objective-C @interface SNRClientAgreements : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **email** | Bool | no | Email agreement | | **sms** | Bool | no | SMS agreement | | **push** | Bool | no | Push notifications agreement | | **bluetooth** | Bool | no | Bluetooth agreement | | **rfid** | Bool | no | RFID agreement | | **wifi** | Bool | no | WIFI agreement | **Initializers:**
```Swift init() ```
```Objective-C - (instancetype)init ```
--- --- ### ClientEventData **Declared In:** Headers/SNRClientEventData.h **Related To:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class ClientEventData: BaseModel ```
```Objective-C @interface SNRClientEventData : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **time** | String | no | Event's time | | **label** | String | no | Event's label | | **action** | String | no | Event's action | | **client** | [AnyHashable: Any] | no | Event's customer identification | | **params** | [AnyHashable: Any] | no | Event's parameters |
All properties are read-only.
**Methods:** This method retrieves a customer ID.
```Swift func getClientID() -> Int ```
```Objective-C - (NSInteger)getClientID ```
--- This method retrieves a customer UUID.
```Swift func getClientUUIDString() -> String? ```
```Objective-C - (nullable NSString *)getClientUUIDString ```
--- This method retrieves a customer email.
```Swift func getClientEmail() -> String? ```
```Objective-C - (nullable NSString *)getClientEmail ```
--- --- ### ClientEventsApiQuery The object to set parameters easily for fetching client events from API. **Declared In:** Headers/SNRClientEventsApiQuery.h **Inherits From:** [NSObject](https://developer.apple.com/documentation/objectivec/nsobject) **Declaration:**
```Swift class ClientEventsApiQuery: NSObject ```
```Objective-C @interface SNRClientEventsApiQuery : NSObject ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **actions** | [String] | no | [] | Specifies event actions for query | | **timeFrom** | String | yes | nil | Specifies time from for query | | **timeTo** | String | yes | nil | Specifies time to for query | | **limit** | String | no | 100 | Limit of items in the response | **Initializers:**
```Swift init() ```
```Objective-C - (instancetype)init ```
--- --- ### TokenPayload **Declared In:** Headers/SNRTokenPayload.h **Related To:** [TokenOrigin](/developers/mobile-sdk/class-reference/ios/client#tokenorigin) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class TokenPayload: BaseModel ```
```Objective-C @interface SNRTokenPayload : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **tokenString** | String | no | Token as a raw string | | **expirationDate** | Date | no | Token's expiration time | | **creationDate** | Date | no | Token's creation time | | **rlm** | String | no | Token's RLM | | **origin** | [TokenOrigin](/developers/mobile-sdk/class-reference/ios/client#tokenorigin) | no | Token's origin | | **uuid** | String | no | Customer's UUID | | **clientId** | String | no | Customer's ID | | **customId** | String | yes | Customer's custom ID | **Initializers:**
```Swift init(tokenString: String, expirationDate: Date, creationDate: Date, rlm: String, origin: TokenOrigin, uuid: String, clientId: String, customId: String?) ```
```Objective-C - (instancetype)initWithTokenString:(NSString *)tokenString expirationDate:(NSDate *)expirationDate creationDate:(NSDate *)creationDate rlm:(NSString *)rlm origin:(SNRTokenOrigin)origin uuid:(NSString *)uuid clientId:(NSString *)clientId customId:(nullable NSString *)customId; ```
--- --- ### Token **Declared In:** Headers/SNRToken.h **Related To:** [TokenOrigin](/developers/mobile-sdk/class-reference/ios/client#tokenorigin) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class Token: BaseModel ```
```Objective-C @interface SNRToken : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **tokenString** | String | no | Token as a raw string | | **expirationDate** | String | no | Token's expiration time | | **rlm** | String | no | Token's RLM | | **origin** | [TokenOrigin](/developers/mobile-sdk/class-reference/ios/client#tokenorigin) | no | Token's origin | | **clientId** | String | no | Customer's ID | | **customId** | String | yes | Customer's custom ID | **Methods:** Checks if the token is near expiration.
```Swift func isNearExpiring() -> Bool ```
```Objective-C - (BOOL)isNearExpiring ```
--- --- ### TokenOrigin
The `Oauth` value was renamed in 5.0.0 version to `OAuth`.
**Declared In:** Headers/SNRTokenOrigin.h **Declaration:**
```Swift enum TokenOrigin: Int { unknown, synerise, simpleAuth, facebook, OAuth, apple } ```
```Objective-C typedef NS_ENUM(NSUInteger, SNRTokenOrigin) { SNRTokenOriginUnknown, SNRTokenOriginSynerise, SNRTokenOriginSimpleAuth, SNRTokenOriginFacebook, SNRTokenOriginOAuth, SNRTokenOriginApple } ```
**Functions:** Converts from **TokenOrigin** to **String**.
```Swift func SNR_TokenOriginToString(_: TokenOrigin) -> String ```
```Objective-C NSString * SNR_TokenOriginToString(SNRTokenOrigin type) ```
--- Converts from **String** to **TokenOrigin**.
```Swift func SNR_StringToTokenOrigin(_: String) -> TokenOrigin ```
```Objective-C SNRTokenOrigin SNR_StringToTokenOrigin(NSString *string) ```
--- --- ## Removed symbols --- ### ClientOAuthAuthenticationContext{#clientoauthauthenticationcontext} | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.11 | 3.6.13 | 0.9.12 | n/a | | Deprecated in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | n/a | **Declared In:** Headers/SNRClientOAuthAuthenticationContext.h **Related To:** [ClientAgreements](/developers/mobile-sdk/class-reference/ios/client#clientagreements) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class ClientOAuthAuthenticationContext: BaseModel ```
```Objective-C @interface SNRClientOAuthAuthenticationContext : SNRBaseModel ```
**Properties:** Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/ios/client#clientagreements) | yes | nil | Object that stores all agreements of a customer | | **attributes** | [AnyHashable: Any] | yes | [] | Additional custom attributes of a customer | **Initializers:**
```Swift init() ```
```Objective-C - (instancetype)init ```
--- --- ### ClientFacebookAuthenticationContext{#clientfacebookauthenticationcontext} | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.3.8 | 3.3.0 | 0.9.7 | n/a | | Deprecated in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | n/a | **Declared In:** Headers/SNRClientFacebookAuthenticationContext.h **Related To:** [ClientAgreements](/developers/mobile-sdk/class-reference/ios/client#clientagreements) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class ClientFacebookAuthenticationContext: BaseModel ```
```Objective-C @interface SNRClientFacebookAuthenticationContext : SNRBaseModel ```
**Properties:** Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/ios/client#clientagreements) | yes | nil | Object that stores all agreements of a customer | | **attributes** | [AnyHashable: Any] | yes | [] | Additional custom attributes of a customer | **Initializers:**
```Swift init() ```
```Objective-C - (instancetype)init ```
--- --- ### ClientAppleSignInAuthenticationContext{#clientapplesigninauthenticationcontext} | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.11 | n/a | 0.9.12 | n/a | | Deprecated in: | 3.7.6 | n/a | 0.9.19 | n/a | | Removed in: | 5.0.0 | n/a | 1.0.0 | n/a | **Declared In:** Headers/SNRClientAppleSignInAuthenticationContext.h **Related To:** [ClientAgreements](/developers/mobile-sdk/class-reference/ios/client#clientagreements) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class ClientAppleSignInAuthenticationContext: BaseModel ```
```Objective-C @interface SNRClientAppleSignInAuthenticationContext : SNRBaseModel ```
**Properties:** Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/ios/client#clientagreements) | yes | nil | Object that stores all agreements of a customer | | **attributes** | [AnyHashable: Any] | yes | [] | Additional custom attributes of a customer | **Initializers:**
```Swift init() ```
```Objective-C - (instancetype)init ```
# Customer authentication ## Set Client State delegate --- This method sets an object for a customer's state delegate methods. **Declared In:** Headers/SNRClient.h **Related To:** [ClientStateDelegate](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#client-state-delegate) **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func setClientStateDelegate(_ delegate: ClientStateDelegate) ```
```Objective-C + (void)setClientStateDelegate:(SNRClientStateDelegate *)delegate ```
**Discussion:** Learn more about the methods and the purpose of this listener [here](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#client-state-delegate). ## Register customer account --- This method registers a new customer with an email, password, and optional data. This method requires the context object with a customer’s email, password, and optional data. Omitted fields are not modified. Depending on the backend configuration, the account may require activation. For details, see [customer registration](/developers/mobile-sdk/user-identification-and-authorization/overview). Do not allow signing in again (or signing up) when a customer is already signed in. Sign the customer out first. Do not create multiple instances nor call this method multiple times before execution. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_REGISTER_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** Headers/SNRClient.h **Related To:** [ClientRegisterAccountContext](/developers/mobile-sdk/class-reference/ios/client#clientregisteraccountcontext) **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func registerAccount(context: ClientRegisterAccountContext, success: (() -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)registerAccount:(nonnull SNRClientRegisterAccountContext *)context success:(nonnull void (^)(void))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **context** | [ClientRegisterAccountContext](/developers/mobile-sdk/class-reference/ios/client#clientregisteraccountcontext) | yes | - | Object with the customer's email, password, and other optional data | | **success** | (() -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
Since version 5.0.0, the **success** closure does NOT contain the `isSuccess` parameter.
**Return Value:** No value is returned. **Example:**
```Swift let agreements: ClientAgreements = ClientAgreements() agreements.email = true agreements.sms = true agreements.push = true agreements.bluetooth = true agreements.rfid = true agreements.wifi = true let email: String = "YOUR_EMAIL" let password: String = "YOUR_PASSWORD" let context: ClientRegisterAccountContext = ClientRegisterAccountContext(email: email, password: password) context.firstName = "FIRST_NAME" context.lastName = "LAST_NAME" context.customId = "CUSTOM_ID" context.sex = .male context.phone = "123-456-789" context.company = "Synerise" context.address = "Lubostroń 1" context.city = "Kraków" context.province = "Małopolskie" context.zipCode = "30-383" context.countryCode = "+48" context.agreements = agreements context.attributes = ["attribute1": "value1", "attribute2": "value2"] context.tags = ["tag1", "tag2" "tag3"] Client.registerAccount(context: context, success: { // success }, failure: { (error) in // failure }) ```
```Objective-C SNRClientAgreements *agreements = [SNRClientAgreements new]; agreements.email = true; agreements.sms = true; agreements.push = true; agreements.bluetooth = true; agreements.rfid = true; agreements.wifi = true; NSString *email = @"EMAIL"; NSString *password = @"PASSWORD"; SNRClientRegisterAccountContext *context = [SNRClientRegisterAccountContext alloc] initWithEmail:email andPassword:password]; context.firstName = @"FIRST_NAME"; context.lastName = @"LAST_NAME"; context.customId = @"CUSTOM_ID"; context.sex = SNRClientSexMale; context.phone = @"123-456-789"; context.company = @"Synerise"; context.address = @"Lubostroń 1"; context.city = @"Kraków"; context.province = @"Małopolskie"; context.zipCode = @"30-383"; context.countryCode = @"+48"; context.agreements = agreements; context.attributes = @{@"attribute": @"value"}; context.tags = @[@"tag1", @"tag2" @"tag3"]; [SNRClient registerAccount:context success:^() { // success } failure:^(SNRApiError *error) { // failure }]; ```
## Request customer account activation --- This method requests sending an email with a URL that confirms the registration and activates the account. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_CONFIRMATION_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func requestAccountActivation(email: String, success: (() -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)requestAccountActivationWithEmail:(nonnull NSString *)email success:(nonnull void (^)(void))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | String | yes | - | Customer's email | | **success** | (() -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
Before version 5.0.0, this method was called `Synerise.activateAccount(email:success:failure:)`.
Since version 5.0.0, the **success** closure does NOT contain the `isSuccess` parameter.
**Return Value:** No value is returned. **Example:**
```Swift let email: String = "EMAIL" Client.requestAccountActivation(email: email, success: { // success }) { (error) in // failure } ```
```Objective-C NSString *email = @"EMAIL"; [SNRClient requestAccountActivationWithEmail:email success:^() { // success } failure:^(NSError * error) { // failure }]; ```
## Confirm customer account activation --- This method confirms a customer account with the confirmation token. This method is a global operation and doesn't require customer authentication.
Returns the HTTP 400 status code if the account is already confirmed or 404 if the account does not exist.
The API key must have the `SAUTH_CONFIRMATION_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func confirmAccountActivation(token: String, success: (() -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)confirmAccountActivationByToken:(nonnull NSString *)token success:(nonnull void (^)(void))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **token** | String | yes | - | Confirmation token | | **success** | (() -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
Before version 5.0.0, this method was called `Synerise.confirmAccount(token:success:failure:)`.
Since version 5.0.0, the **success** closure does NOT contain the `isSuccess` parameter.
**Return Value:** No value is returned. **Example:**
```Swift let token: String = "TOKEN" Client.confirmAccountActivation(token: token, success: { // success }, failure: { (error) in // failure }) ```
```Objective-C NSString *token = @"TOKEN"; [SNRClient confirmAccountActivationByToken:token success:^() { // success } failure:^(SNRApiError *error) { // failure }]; ```
## Request customer account activation by pin --- This method requests a customer's account registration process with the PIN code. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_PIN_CODE_RESEND_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func requestAccountActivationByPin(email: String, success: (() -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)requestAccountActivationByPinWithEmail:(nonnull NSString *)email success:(nonnull void (^)(void))success failure:(nonnull void (^)(SNRApiError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | String | yes | - | Customer's email | | **success** | (() -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
Since version 5.0.0, the **success** closure does NOT contain the `isSuccess` parameter.
**Return Value:** No value is returned. **Example:**
```Swift let email: String = "EMAIL" Client.requestAccountActivationByPin(email: email, success: { // success }) { (error) in // failure } ```
```Objective-C NSString *email = @"EMAIL"; [SNRClient requestAccountActivationByPinWithEmail:email success:^() { // success } failure:^(SNRApiError *error) { // failure }]; ```
## Confirm customer account activation by pin --- This method confirms a customer's account registration process with the PIN code. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_PIN_CODE_RESEND_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func confirmAccountActivationByPin(pinCode: String, email: String, success: (() -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)confirmAccountActivationByPin:(nonnull NSString *)pinCode email:(nonnull NSString *)email success:(nonnull void (^)(void))success failure:(nonnull void (^)(SNRApiError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **pinCode** | String | yes | - | Code sent to a customer's email | | **email** | String | yes | - | Customer's email | | **success** | (() -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
Since version 5.0.0, the **success** closure does NOT contain the `isSuccess` parameter.
**Return Value:** No value is returned. **Example:**
```Swift let pinCode: String = "PIN_CODE" let email: String = "EMAIL" Client.confirmAccountActivationByPin(pinCode: pinCode, email: email, success: { // success }) { (error) in // failure } ```
```Objective-C NSString *pinCode = @"PIN_CODE"; NSString *email = @"EMAIL"; [SNRClient confirmAccountActivationByPin:pinCode email:email success:^() { // success } failure:^(SNRApiError *error) { // failure }]; ```
## Sign in a customer --- This method signs a customer in to obtain a JSON Web Token (JWT) which can be used in subsequent requests. The SDK will refresh the token before each call if it is about to expire (but not expired). Do NOT allow signing in again (or signing up) when a customer is already signed in. First, sign the customer out. Do NOT create multiple instances nor call this method multiple times before execution. **Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func signIn(email: String, password: String, success: (() -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)signInWithEmail:(nonnull NSString *)email password:(nonnull NSString *)password success:(nonnull void (^)(void))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | String | yes | - | Customer's email | | **password** | String | yes | - | Customer's password | | **success** | (() -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
Since version 5.0.0, the **success** closure does NOT contain the `isSuccess` parameter.
**Return Value:** No value is returned. **Example:**
```Swift let email: String = "EMAIL" let password: String = "PASSWORD" Client.signIn(email: email, password: password, success: { // success }, failure: { (error) in // failure }) ```
```Objective-C NSString *email = @"EMAIL"; NSString *password = @"PASSWORD"; [SNRClient signInWithEmail:email password:password success:^() { // success } failure:^(SNRApiError *error) { // failure }]; ```
## Sign in a customer conditionally --- This method signs a customer in to obtain a JSON Web Token (JWT) which can be used in subsequent requests. The SDK will refresh the token before each call if it is about to expire (but not expired). Do NOT allow signing in again (or signing up) when a customer is already signed in. First, sign the customer out. Do NOT create multiple instances nor call this method multiple times before execution. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | **Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func signInConditionally(email: String, password: String, success: ((ClientAuthenticationResult) -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)signInConditionallyWithEmail:(nonnull NSString *)email password:(nonnull NSString *)password success:(nonnull void (^)(SNRClientAuthenticationResult *result))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | String | yes | - | Customer's email | | **password** | String | yes | - | Customer's password | | **success** | ((ClientAuthenticationResult) -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```Swift let email: String = "EMAIL" let password: String = "PASSWORD" Client.signInConditionally(email: email, password: password, success: { (result) in // success }, failure: { (error) in // failure }) ```
```Objective-C NSString *email = @"EMAIL"; NSString *password = @"PASSWORD"; [SNRClient signInConditionallyWithEmail:email password:password success:^(SNRClientAuthenticationResult *result) { // success } failure:^(SNRApiError *error) { // failure }]; ```
## Authenticate customer by IdentityProvider --- This method authenticates a customer with OAuth, Facebook, Google, Apple, or Synerise. If an account for the customer does not exist and the identity provider is different than Synerise, this request creates an account. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.7.6 | 3.8.0 | 0.9.19 | 0.3.0 | **Declared In:** Headers/SNRClient.h **Related To:** [ClientAuthenticationContext](/developers/mobile-sdk/class-reference/ios/client#clientauthenticationcontext) [ClientIdentityProivider](/developers/mobile-sdk/class-reference/ios/client#clientidentityprovider) **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func authenticate(token: AnyObject, clientIdentityProvider: ClientIdentityProvider, authID: String?, context: ClientAuthenticationContext?, success: (() -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)authenticateWithToken:(id)token clientIdentityProvider:(SNRClientIdentityProvider)clientIdentityProvider authID:(nullable NSString *)authID context:(nullable SNRClientAuthenticationContext *)context success:(void (^)(void))success failure:(void (^)(SNRApiError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **token** | AnyObject | yes | - | Token retrieved from provider | | **clientIdentityProvider** | [ClientIdentityProvider](/developers/mobile-sdk/class-reference/ios/client#clientidentityprovider) | yes | - | Provider of your token | | **authID** | String | no | nil | Optional identifier of authorization | | **context** | [ClientAuthenticationContext](/developers/mobile-sdk/class-reference/ios/client#clientauthenticationcontext) | no | nil | Object which contains agreements and attributes | | **success** | (() -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
**authID** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
Since version 5.0.0, the **success** closure does NOT contain the `isSuccess` parameter.
**Return Value:** No value is returned. **Example:**
```Swift let agreements: ClientAgreements = ClientAgreements() agreements.email = true agreements.sms = true agreements.push = true agreements.bluetooth = true agreements.rfid = true agreements.wifi = true let context: ClientAuthenticationContext = ClientAuthenticationContext() context.agreements = agreements context.attributes = ["attribute1": "value1", "attribute2": "value2"] let accessToken: String = "ACCESS_TOKEN" let authID: String = "AUTH_ID" Client.authenticate(token: token, authID: authID, context: context, success: { // success }) { (error) in // failure } ```
```Objective-C SNRClientAgreements *agreements = [SNRClientAgreements new]; agreements.email = true; agreements.sms = true; agreements.push = true; agreements.bluetooth = true; agreements.rfid = true; agreements.wifi = true; SNRClientAuthenticationContext *context = [SNRClientAuthenticationContext new]; context.agreements = agreements; context.attributes = @{"attribute1": "value1", "attribute2": "value2"}; NSString *accessToken = @"ACCESS_TOKEN"; NSString *authID = @"AUTH_ID"; [SNRClient authenticateWithToken:token authID:authID context:context success:^() { // success } failure:^(SNRApiError *error) { // failure }]; ```
## Authenticate customer conditionally by IdentityProvider --- This method authenticates a customer with OAuth, Facebook, Google, Apple, or Synerise. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | **Declared In:** Headers/SNRClient.h **Related To:** [ClientConditionalAuthResult](/developers/mobile-sdk/class-reference/ios/client#clientconditionalauthresult) [ClientIdentityProvider](/developers/mobile-sdk/class-reference/ios/client#clientidentityprovider) **Class:** [Client](/developers/mobile-sdk/class-reference/ios/client) **Declaration:**
```Swift static func authenticateConditionally(token: AnyObject, clientIdentityProvider: ClientIdentityProvider, authID: String?, context: ClientConditionalAuthenticationContext?, success: ((ClientAuthenticationResult) -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)authenticateConditionallyWithToken:(id)token clientIdentityProvider:(SNRClientIdentityProvider)clientIdentityProvider authID:(nullable NSString *)authID context:(nullable SNRClientConditionalAuthenticationContext *)context success:(void (^)(SNRClientAuthenticationResult *authenticationResult))success failure:(void (^)(SNRApiError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **token** | AnyObject | yes | - | Token retrieved from provider | | **clientIdentityProvider** | [ClientIdentityProvider](/developers/mobile-sdk/class-reference/ios/client#clientidentityprovider) | yes | - | Provider of your token | | **authID** | String | no | nil | Optional identifier of authorization | | **context** | [ClientConditionalAuthenticationContext](/developers/mobile-sdk/class-reference/ios/client#clientconditionalauthenticationcontext) | no | nil | Object which contains agreements and attributes | | **success** | (([ClientConditionalAuthResult](/developers/mobile-sdk/class-reference/ios/client#clientconditionalauthenticationcontext)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
**authID** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** No value is returned. **Example:**
```Swift let agreements: ClientAgreements = ClientAgreements() agreements.email = true agreements.sms = true agreements.push = true agreements.bluetooth = true agreements.rfid = true agreements.wifi = true let context: ClientConditionalAuthenticationContext = ClientConditionalAuthenticationContext() context.agreements = agreements context.attributes = ["attribute1": "value1", "attribute2": "value2"] let accessToken: String = "ACCESS_TOKEN" let authID: String = "AUTH_ID" Client.authenticateConditionally(token: token, authID: authID, context: context, success: { (success) in // success }) { (error) in // failure } ```
```Objective-C SNRClientAgreements *agreements = [SNRClientAgreements new]; agreements.email = true; agreements.sms = true; agreements.push = true; agreements.bluetooth = true; agreements.rfid = true; agreements.wifi = true; SNRClientConditionalAuthenticationContext *context = [SNRClientConditionalAuthenticationContext new]; context.agreements = agreements; context.attributes = @{"attribute1": "value1", "attribute2": "value2"}; NSString *accessToken = @"ACCESS_TOKEN"; NSString *authID = @"AUTH_ID"; [SNRClient authenticateConditionallyWithToken:token authID:authID context:context success:^(BOOL isSuccess) { // success } failure:^(SNRApiError *error) { // failure }]; ```
## Authenticate customer with token payload --- This method signs in a customer in with the provided token payload. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.15.0 | 5.15.0 | n/a | n/a | **Declared In:** Headers/SNRClient.h **Related To:** [TokenPayload](/developers/mobile-sdk/class-reference/ios/client#tokenpayload) **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func authenticate(tokenPayload: TokenPayload, authID: String, success: (() -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)authenticateWithTokenPayload:(SNRTokenPayload *)tokenPayload authID:(NSString *)authID success:(void (^)(void))success failure:(void (^)(SNRApiError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **tokenPayload** | [TokenPayload](/developers/mobile-sdk/class-reference/ios/client#tokenpayload) | yes | - | Object which contains a token's payload | | **authID** | String | yes | - | Required customer's identifier of authorization | | **success** | (() -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
**authID** parameter is used for decreasion the number of UUID refreshes so it must be unique for every customer.
**Return Value:** No value is returned. ## Authenticate customer via Simple Profile Authentication --- This method authenticates a customer with Simple Profile Authentication. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.14.0 | 5.7.1 | 0.15.0 | 0.7.0 |
When you use this method, you must set a request validation salt by using the `Synerise.setRequestValidationSalt(_:)` method (if salt is enabled for Simple Profile Authentication).
The API key must have the `SAUTH_SIMPLE_AUTH_CREATE` from the **Auth** group.
**Declared In:** Headers/SNRClient.h **Related To:** [ClientSimpleAuthenticationData](/developers/mobile-sdk/class-reference/ios/client#clientsimpleauthenticationdata) **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func simpleAuthentication(data: ClientSimpleAuthenticationData, authID: String, success: (() -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)simpleAuthentication:(SNRClientSimpleAuthenticationData *)data authID:(NSString *)authID success:(void (^)(void))success failure:(void (^)(SNRApiError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **data** | [ClientSimpleAuthenticationData](/developers/mobile-sdk/class-reference/ios/client#clientsimpleauthenticationdata) | yes | - | Object which contains customer data | | **authID** | String | yes | - | Required identifier of authorization | | **success** | (() -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
**authID** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** No value is returned. ## Check if a customer is signed in (via RaaS, OAuth, Facebook, Apple) --- This method checks if a customer is signed in (via Synerise Authentication - RaaS, OAuth, Facebook, Apple). **Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func isSignedIn() -> Bool ```
```Objective-C + (BOOL)isSignedIn ```
**Return Value:** **true** if the customer is signed in, otherwise returns **false**. **Example:**
```Swift let isSignedIn: Bool = Client.isSignedIn() ```
```Objective-C BOOL isSignedIn = [SNRClient isSignedIn]; ```
## Check if a customer is signed in (via Simple Profile Authentication) --- This method checks if a customer is signed in (via Simple Profile Authentication). | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.14.0 | 5.7.1 | 0.15.0 | 0.7.0 | **Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func isSignedInViaSimpleAuthentication() -> Bool ```
```Objective-C + (BOOL)isSignedInViaSimpleAuthentication ```
**Return Value:** **true** if the customer is signed in (via Simple Profile Authentication), otherwise returns **false**. ## Sign out customer --- This method signs out a customer out.
This method works with every authentication type (via Synerise, External Provider, OAuth or Simple Profile Authentication).
**Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func signOut() -> Void ```
```Objective-C + (void)signOut ```
**Return Value:** No value is returned. **Example:**
```Swift Client.signOut() ```
```Objective-C [SNRClient signOut]; ```
## Sign out customer with mode or from all devices --- This method signs out a customer out with a chosen mode and Determines if the method should sign out all devices. Available modes: - `.signOut` mode signs out the customer. - `.signOutWithSessionDestroy` mode signs out the customer and additionally, clears the anonymous session and regenerates the customer UUID. The `fromAllDevices` parameter determines whether the method should notify the backend to sign out all devices. **IMPORTANT: It is an asynchronous method.** | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.11.0 | 5.1.0 | 0.14.0 | 1.0.0 |
This method works with every authentication type (via Synerise, External Provider, OAuth or Simple Profile Authentication).
**Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func signOut(mode: ClientSignOutMode, fromAllDevices: Bool, success: ((Bool) -> Void), failure: ((ApiError) -> Void)) ```
```Objective-C + (void)signOutWithmode:(SNRClientSignOutMode)mode fromAllDevices:(BOOL)fromAllDevices success:(void (^)(void))success failure:(void (^)(SNRApiError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **mode** | [ClientSignOutMode](/developers/mobile-sdk/class-reference/ios/client#clientsignoutmode) | yes | - | Mode of signing out | | **fromAllDevices** | Bool | yes | - | Determines if the method should sign out all devices | | **success** | (() -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```Swift Client.signOut(mode: .signOutWithSessionDestroy, fromAllDevices: true, success: { // success }) { (error) in // failure } ```
```Objective-C [SNRClient signOutWithMode:SNRClientSignOutModeSignOutWithSessionDestroy fromAllDevices:YES success:^{ // success } failure:^(SNRApiError *error) { // failure }]; ```
## Removed methods ### Authenticate customer by OAuth with registration {#authenticate-customer-by-oauth-with-registration} --- This method authenticates a customer with OAuth. If an account for the customer does not exist, this request creates an account. | Available on | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.11 | 3.6.13 | 0.9.12 | n/a | | Deprecated in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | n/a |
Returns the HTTP 401 status code if the provided access token and/or API Key is invalid.
**Replaced By:** [Authenticate customer by IdentityProvider](/developers/mobile-sdk/method-reference/ios/client-authentication#authenticate-customer-by-identityprovider) **Declared In:** Headers/SNRClient.h **Related To:** [ClientOAuthAuthenticationContext](/developers/mobile-sdk/class-reference/ios/client#clientoauthauthenticationcontext) **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func authenticateByOAuth(accessToken: String, authID: String?, context: ClientOAuthAuthenticationContext?, success: ((Bool) -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)authenticateByOAuthWithAccessToken:(NSString *)accessToken authID:(nullable NSString *)authID context:(nullable SNRClientOAuthAuthenticationContext *)context success:(nullable void (^)(BOOL isSuccess))success failure:(nullable void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **accessToken** | String | yes | - | OAuth Access Token | | **authID** | String | no | nil | Optional identifier of authorization | | **context** | [ClientOAuthAuthenticationContext](/developers/mobile-sdk/class-reference/ios/client#clientoauthauthenticationcontext) | no | nil | Object which contains agreements and attributes | | **success** | ((Bool) -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
**authID** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** No value is returned. **Example:**
```Swift let agreements: ClientAgreements = ClientAgreements() agreements.email = true agreements.sms = true agreements.push = true agreements.bluetooth = true agreements.rfid = true agreements.wifi = true let context: ClientOAuthContext = ClientOAuthContext() context.agreements = agreements context.attributes = ["attribute1": "value1", "attribute2": "value2"] let accessToken: String = "ACCESS_TOKEN" let authID: String = "AUTH_ID" Client.authenticateByOAuth(accessToken: accessToken, authID: authID, context: context, success: { (success) in // success }) { (error) in // failure } ```
```Objective-C SNRClientAgreements *agreements = [SNRClientAgreements new]; agreements.email = true; agreements.sms = true; agreements.push = true; agreements.bluetooth = true; agreements.rfid = true; agreements.wifi = true; SNRClientOAuthContext *context = [SNRClientOAuthContext new]; context.agreements = agreements; context.attributes = @{"attribute1": "value1", "attribute2": "value2"}; NSString *accessToken = @"ACCESS_TOKEN"; NSString *authID = @"AUTH_ID"; [SNRClient authenticateByOAuthWithAccessToken:accessToken authID:authID context:context success:^(BOOL isSuccess) { // success } failure:^(SNRApiError *error) { // failure }]; ```
### Authenticate customer by OAuth without registration {#authenticate-customer-by-oauth-without-registration} --- This method authenticates a customer with OAuth. | Available on | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.11 | 3.6.13 | 0.9.12 | n/a | | Deprecated in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | n/a |
Returns the HTTP 401 status code if the provided access token and/or API Key is invalid.
**Replaced By:** [Authenticate customer conditionally by IdentityProvider](/developers/mobile-sdk/method-reference/ios/client-authentication#authenticate-customer-conditionally-by-identityprovider) **Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func authenticateByOAuthIfRegistered(accessToken: String, authID: String?, success: ((Bool) -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)authenticateByOAuthIfRegisteredWithAccessToken:(nonnull NSString *)accessToken authID:(nullable NSString *)authID success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **accessToken** | String | yes | - | OAuth Access Token | | **authID** | String | no | nil | Optional identifier of authorization | | **success** | ((Bool) -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
**authID** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** No value is returned. ### Authenticate customer by Facebook with registration {#authenticate-customer-by-facebook-with-registration} --- This method authenticates a customer with Facebook. If an account for the customer does not exist, this request creates an account. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.3.8 | 3.3.0 | 0.9.7 | n/a | | Deprecated in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | n/a |
Returns the HTTP 401 status code if the provided Facebook token and/or API Key is invalid.
**Replaced By:** [Authenticate customer by IdentityProvider](/developers/mobile-sdk/method-reference/ios/client-authentication#authenticate-customer-by-identityprovider) **Declared In:** Headers/SNRClient.h **Related To:** [ClientFacebookAuthenticationContext](/developers/mobile-sdk/class-reference/ios/client#clientfacebookauthenticationcontext) **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func authenticateByFacebook(facebookToken: String, authID: String?, context: ClientFacebookAuthenticationContext?, success: ((Bool) -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)authenticateByFacebookWithFacebookToken:(nonnull NSString *)facebookToken authID:(nullable NSString *)authID context:(nullable SNRClientFacebookAuthenticationContext *)context success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **facebookToken** | String | yes | - | Facebook Access Token | | **authID** | String | no | nil | Optional identifier of authorization | | **context** | [ClientFacebookAuthenticationContext](/developers/mobile-sdk/class-reference/ios/client#clientfacebookauthenticationcontext) | no | nil | Object which contains agreements and attributes | | **success** | ((Bool) -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
**authID** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** No value is returned. **Example:**
```Swift let agreements: ClientAgreements = ClientAgreements() agreements.email = true agreements.sms = true agreements.push = true agreements.bluetooth = true agreements.rfid = true agreements.wifi = true let context: ClientFacebookAuthenticationContext = ClientFacebookAuthenticationContext() context.agreements = agreements context.attributes = ["attribute1": "value1", "attribute2": "value2"] guard let facebookToken = FBSDKAccessToken.current()?.tokenString else { return } let authID: String = "AUTH_ID" Client.authenticateByFacebook(facebookToken: fa, authID: authID, context: context, success: { (success) in // success }) { (error) in // failure } ```
```Objective-C SNRClientAgreements *agreements = [SNRClientAgreements new]; agreements.email = true; agreements.sms = true; agreements.push = true; agreements.bluetooth = true; agreements.rfid = true; agreements.wifi = true; SNRClientFacebookAuthenticationContext *context = [SNRClientFacebookAuthenticationContext new]; context.agreements = agreements; context.attributes = @{"attribute1": "value1", "attribute2": "value2"}; NSString *facebookToken = [FBSDKAccessToken currentAccessToken].tokenString; NSString *authID = @"AUTH_ID"; [SNRClient authenticateByFacebookWithFacebookToken:facebookToken authID:authID context:context success:^(BOOL isSuccess) { // success } failure:^(SNRApiError *error) { // failure }]; ```
### Authenticate customer by Facebook without registration {#authenticate-customer-by-facebook-without-registration} --- This method authenticates a customer with Facebook. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.3.8 | 3.3.0 | 0.9.7 | n/a | | Deprecated in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | n/a |
Returns the HTTP 401 status code if the provided Facebook token and/or API Key is invalid.
**Replaced By:** [Authenticate customer conditionally by IdentityProvider](/developers/mobile-sdk/method-reference/ios/client-authentication#authenticate-customer-conditionally-by-identityprovider) **Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func authenticateByFacebookIfRegistered(facebookToken: String, authID: String?, success: ((Bool) -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)authenticateByFacebookIfRegisteredWithFacebookToken:(nonnull NSString *)facebookToken authID:(nullable NSString *)authID success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **facebookToken** | String | yes | - | Facebook Access Token | | **authID** | String | no | nil | Optional identifier of authorization | | **success** | ((Bool) -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
**authID** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** No value is returned. **Example:**
```Swift guard let facebookToken = FBSDKAccessToken.current()?.tokenString else { return } let authID: String = "AUTH_ID" Client.authenticateByFacebookIfRegistered(facebookToken: facebookToken, success: { (success) in // success }, failure: { (error) in // failure }) ```
```Objective-C NSString *facebookToken = [FBSDKAccessToken currentAccessToken].tokenString; NSString *authID = @"AUTH_ID"; [SNRClient authenticateByFacebookIfRegisteredWithFacebookToken:facebookToken authID:authID success:^(BOOL isSuccess) { // success } failure:^(SNRApiError *error) { // failure }]; ```
### Authenticate customer by Sign in with Apple with registration {#authenticate-customer-by-sign-in-with-apple-with-registration} --- This method authenticates a customer with Sign In With Apple. If an account for the customer does not exist, this request creates an account. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.11 | n/a | 0.9.12 | n/a | | Deprecated in: | 3.7.6 | n/a | 0.9.19 | n/a | | Removed in: | 5.0.0 | n/a | 1.0.0 | n/a | **Replaced By:** [Authenticate customer by IdentityProvider](/developers/mobile-sdk/method-reference/ios/client-authentication#authenticate-customer-by-identityprovider) **Declared In:** Headers/SNRClient.h **Related To:** [ClientAppleSignInAuthenticationContext](/developers/mobile-sdk/class-reference/ios/client#clientapplesigninauthenticationcontext) **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func authenticateByAppleSignIn(identityToken: Data, authID: String?, context: ClientAppleSignInAuthenticationContext?, success: ((Bool) -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)authenticateByAppleSignInWithIdentityToken:(nonnull NSData *)identityToken authID:(nullable NSString *)authID context:(nullable SNRClientAppleSignInAuthenticationContext *)context success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **identityToken** | Data | yes | - | Apple Identity Token | | **context** | [ClientAppleSignInAuthenticationContext](/developers/mobile-sdk/class-reference/ios/client#clientapplesigninauthenticationcontext) | no | nil | Object which contains agreements and attributes | | **authID** | String | no | nil | Optional identifier of authorization | | **success** | ((Bool) -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
**authID** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** No value is returned. **Example:**
```Swift extension LoginViewController: ASAuthorizationControllerDelegate { func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) { if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential { let agreements: ClientAgreements = ClientAgreements() agreements.email = true agreements.sms = true agreements.push = true agreements.bluetooth = true agreements.rfid = true agreements.wifi = true let context: ClientAppleSignInAuthenticationContext = ClientAppleSignInAuthenticationContext(identityToken: appleIdCredential.identityToken!) context.agreements = agreements context.attributes = ["param": "value"] Client.authenticateByAppleSignIn(context: context, authID: authID, success: { (success) in // success }) { (error) in // failure } } } } ```
```Objective-C #pragma mark - ASAuthorizationControllerDelegate - (void)authorizationController:(ASAuthorizationController *)controller didCompleteWithAuthorization:(ASAuthorization *)authorization { id credential = authorization.credential; if (credential != nil) { SNRClientAgreements *agreements = [SNRClientAgreements new]; agreements.email = true; agreements.sms = true; agreements.push = true; agreements.bluetooth = true; agreements.rfid = true; agreements.wifi = true; SNRClientAppleSignInAuthenticationContext*context = [[SNRClientAppleSignInAuthenticationContext alloc] initWithIdentityToken:credential.identityToken]; context.agreements = agreements; context.attributes = @{"attribute1": "value1", "attribute2": "value2"}; [SNRClient authenticateByAppleSignInWithContext:context authID:authID success:^(BOOL isSuccess) { // success } failure:^(SNRApiError *error) { // failure }]; } } ```
### Authenticate customer by Sign in with Apple without registration {#authenticate-customer-by-sign-in-with-apple-without-registration} --- This method authenticates a customer with Sign In With Apple. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.11 | 3.6.13 | 0.9.12 | n/a | | Deprecated in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | n/a | **Replaced By:** [Authenticate customer conditionally by IdentityProvider](/developers/mobile-sdk/method-reference/ios/client-authentication#authenticate-customer-conditionally-by-identityprovider) **Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func authenticateByAppleSignInIfRegistered(identityToken: String, authID: String?, success: ((Bool) -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)authenticateByAppleSignInIfRegisteredWithIdentityToken:(nonnull NSData *)identityToken authID:(nullable NSString *)authID success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **identityToken** | String | yes | - | Apple Identity Token | | **authID** | String | no | nil | Optional identifier of authorization | | **success** | ((Bool) -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
**authID** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** No value is returned. ### Sign out customer with mode {#sign-out-customer-with-mode} --- This method signs out a customer out with a chosen mode: - `.signOut` mode notifies the backend that the customer is signed out. - `.signOutWithSessionDestroy` mode notifies the backend that the customer is signed out and additionally, clears the anonymous session and regenerates the customer UUID. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.4.0 | 4.6.0 | 0.12.0 | 0.7.0 | | Deprecated in: | 4.11.0 | 5.1.0 | - | - | | Removed in: | 5.0.0 | 6.0.0 | 0.14.0 | 1.0.0 |
This method works with every authentication type (via Synerise, External Provider, OAuth or Simple Profile Authentication).
**Replaced By:** [Sign out with mode or from all devices](/developers/mobile-sdk/method-reference/ios/client-authentication#sign-out-customer-with-mode-or-from-all-devices) **Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func signOut(mode: ClientSignOutMode) -> Void ```
```Objective-C + (void)signOutWithmode:(SNRClientSignOutMode)mode ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **mode** | [ClientSignOutMode](/developers/mobile-sdk/class-reference/ios/client#clientsignoutmode) | yes | - | Mode of signing out | **Return Value:** No value is returned. **Example:**
```Swift Client.signOut(mode: .signOutWithSessionDestroy) ```
```Objective-C [SNRClient signOutWithMode:SNRClientSignOutModeSignOutWithSessionDestroy]; ```
# iOS ## iOS delegates ### SyneriseDelegate {id=synerise-delegate} A delegate to handle the SDK lifecycle events. To set your object as delegate, you must use [this method](/developers/mobile-sdk/method-reference/ios/lifecycle#set-synerise-delegate).
```Swift Synerise.setDelegate(YOUR_OBJECT) ```
```Objective-C [SNRSynerise setDelegate:YOUR_OBJECT]; ```
If optional methods for handling URL and deeplink are not implemented, SDK has a default behavior.
##### snr_initialized() {id=synerise-delegate-initialized} This method is called when the Synerise SDK is initialized.
```Swift func snr_initialized() -> Void ```
```Objective-C - (void)SNR_initialized ```
##### snr_initializationError(error: Error) {id=synerise-delegate-initialization-error} This method is called when an error occurs while initializing the Synerise SDK.
```Swift func snr_initializationError(error: Error) -> Void ```
```Objective-C - (void)SNR_initializationError:(NSError *)error ```
| Parameter | Type | Description | | --- | --- | --- | | **error** | NSError | The error that occurred. | ##### snr_registerForPushNotificationsIsNeeded() {id=synerise-delegate-register-for-push-notifications-is-needed} This method is called when Synerise needs registration for push notifications. See [Configuring push notifications](/developers/mobile-sdk/configuring-push-notifications/ios) for more details.
After invoking this method, you must invoke the [Client.registerForPush(registrationToken:mobilePushAgreement:success:failure:)](/developers/mobile-sdk/method-reference/ios/campaigns#register-for-push-notifications) method again.
This method is invoked when the **snr_registerForPushNotificationsIsNeeded(origin:)** method is not implemented.
```Swift func snr_registerForPushNotificationsIsNeeded() -> Void ```
```Objective-C - (void)SNR_registerForPushNotificationsIsNeeded ```
##### snr_registerForPushNotificationsIsNeeded(origin: PushNotificationsRegistrationOrigin) {id=synerise-delegate-register-for-push-notifications-is-needed-by-origin} This method is called when Synerise needs registration for push notifications. See [Configuring push notifications](/developers/mobile-sdk/configuring-push-notifications/ios) for more details.
After invoking this method, you must invoke the [Client.registerForPush(registrationToken:mobilePushAgreement:success:failure:)](/developers/mobile-sdk/method-reference/ios/campaigns#register-for-push-notifications) method again.
```Swift func snr_registerForPushNotificationsIsNeeded(origin: PushNotificationsRegistrationOrigin) -> Void ```
```Objective-C - (void)SNR_registerForPushNotificationsIsNeededByOrigin:(SNRPushNotificationsRegistrationOrigin)origin ```
| Parameter | Type | Description | | --- | --- | --- | | **origin** | [PushNotificationsRegistrationOrigin](/developers/mobile-sdk/class-reference/ios/campaigns#pushnotificationsregistrationorigin) | Origin of the push notifications registration from the SDK. | ##### snr_handledAction(url: URL) {id=snr-handled-url-action} This method is called when Synerise handles URL action from campaign activities.
This method is invoked when the **snr_handledAction(url:source:)** method is not implemented.
```Swift func snr_handledAction(url: URL) -> Void ```
```Objective-C - (void)SNR_handledActionWithURL:(NSURL *)url ```
| Parameter | Type | Description | | --- | --- | --- | | **url** | NSURL | URL value from the action of the activity. | ##### snr_handledAction(url: URL, source: SyneriseSource) {id=snr-handled-url-action-advanced-with-parameters} This method is called when Synerise handles URL action from campaign activities.
```Swift func snr_handledAction(url: URL, source: SyneriseSource) -> Void ```
```Objective-C - (void)SNR_handledActionWithURL:(NSURL *)url source:(SNRSyneriseSource)source ```
| Parameter | Type | Description | | --- | --- | --- | | **url** | NSURL | URL value from the action of the activity. | | **source** | [SyneriseSource](/developers/mobile-sdk/class-reference/ios/campaigns#synerisesource) | Identifies Synerise campaign source ([SyneriseSource](/developers/mobile-sdk/class-reference/ios/campaigns#synerisesource)). | ##### snr_handledAction(url: URL, activity: SyneriseActivity, completionHandler: SyneriseActivityCompletionHandler) {id=snr-handled-url-action-advanced-with-parameters-deprecated} This method is called when Synerise handles URL action from campaign activities.
This method was deprecated in SDK version 5.0.0.
```Swift func snr_handledAction(url: URL, activity: SyneriseActivity, completionHandler: SyneriseActivityCompletionHandler) -> Void ```
```Objective-C - (void)SNR_handledActionWithURL:(NSURL *)url activity:(SNRSyneriseActivity)activity completionHandler:(SNRSyneriseActivityCompletionHandler)completionHandler ```
| Parameter | Type | Description | | --- | --- | --- | | **url** | NSURL | URL value from the action of the activity. | | **activity** | [SyneriseActivity](/developers/mobile-sdk/class-reference/ios/campaigns#syneriseactivity) | Identifies Synerise campaign activity ([SyneriseActivity](/developers/mobile-sdk/class-reference/ios/campaigns#syneriseactivity)). | | **completionHandler** | [SyneriseActivityAction](/developers/mobile-sdk/class-reference/ios/campaigns#syneriseactivityaction) | A block/closure that should be invoked with [SyneriseActivityAction](/developers/mobile-sdk/class-reference/ios/campaigns#syneriseactivityaction) parameters and a completion block to execute. | ##### snr_handledAction(deepLink: String) {id=snr-handled-deeplink-action} This method is called when Synerise handles deeplink action from campaign activities.
This method is invoked when the **snr_handledAction(deepLink:source:)** method is not implemented.
```Swift func snr_handledAction(deepLink: String) -> Void ```
```Objective-C - (void)SNR_handledActionWithDeepLink:(NSString *)deepLink ```
| Parameter | Type | Description | | --- | --- | --- | | **deepLink** | String | Deep link value from the action of the activity. | ##### snr_handledAction(deepLink: String, source: SyneriseSource) {id=snr-handled-deeplink-action-advanced-with-parameters} This method is called when Synerise handles deeplink action from campaign activities.
```Swift func snr_handledAction(deepLink: String, source: SyneriseSource) -> Void ```
```Objective-C - (void)SNR_handledActionWithDeepLink:(NSString *)deepLink source:(SNRSyneriseSource)source ```
| Parameter | Type | Description | | --- | --- | --- | | **deeplink** | String | Deep link value from the action of the activity. | | **source** | [SyneriseSource](/developers/mobile-sdk/class-reference/ios/campaigns#synerisesource) | Identifies Synerise campaign source ([SyneriseActivity](/developers/mobile-sdk/class-reference/ios/campaigns#synerisesource)). | ##### snr_handledAction(deepLink: String, activity: SyneriseActivity, completionHandler: SyneriseActivityCompletionHandler) {id=snr-handled-deeplink-action-advanced-with-parameters-deprecated} This method is called when Synerise handles deeplink action from campaign activities.
This method was deprecated in SDK version 5.0.0.
```Swift func snr_handledAction(deepLink: String, activity: SyneriseActivity, completionHandler: SyneriseActivityCompletionHandler) -> Void ```
```Objective-C - (void)SNR_handledActionWithDeepLink:(NSString *)deepLink activity:(SNRSyneriseActivity)activity completionHandler:(SNRSyneriseActivityCompletionHandler)completionHandler ```
| Parameter | Type | Description | | --- | --- | --- | | **deeplink** | String | Deep link value from the action of the activity. | | **activity** | [SyneriseActivity](/developers/mobile-sdk/class-reference/ios/campaigns#syneriseactivity) | Identifies Synerise campaign activity ([SyneriseActivity](/developers/mobile-sdk/class-reference/ios/campaigns#syneriseactivity)). | | **completionHandler** | [SyneriseActivityAction](/developers/mobile-sdk/class-reference/ios/campaigns#syneriseactivityaction) | A block/closure that should be invoked with parameters: [SyneriseActivityAction](/developers/mobile-sdk/class-reference/ios/campaigns#syneriseactivityaction) and completion block to execute. | --- --- ### NotificationDelegate {id=notification-delegate} A delegate to handle events from Synerise notifications. See [Configuring push notifications](/developers/mobile-sdk/configuring-push-notifications/ios#delegate-methods) for more details.
**NotificationDelegate** is available from 4.10.0 SDK version. All methods are optional.
To set your object as delegate, you must use [this method](/developers/mobile-sdk/method-reference/ios/campaigns#set-notification-delegate).
```Swift Synerise.setNotificationDelegate(YOUR_OBJECT) ```
```Objective-C [SNRSynerise setNotificationDelegate:YOUR_OBJECT]; ```
##### snr_notificationDidReceive(notificationInfo: NotificationInfo) {id=notification-delegate-notification-did-receive} This method is called when a Synerise notification is received.
```Swift snr_notificationDidReceive(notificationInfo: NotificationInfo) ```
```Objective-C - (void)SNR_notificationDidReceive:(SNRNotificationInfo *)notificationInfo ```
| Parameter | Type | Description | | --- | --- | --- | | **notificationInfo** | [NotificationInfo](/developers/mobile-sdk/class-reference/ios/campaigns#notificationinfo) | Object providing information about the notification. | ##### snr_notificationDidDismiss(notificationInfo: NotificationInfo) {id=notification-delegate-notification-did-dismiss} This method is called when a Synerise notification is dismissed.
```Swift func snr_notificationDidDissmis(notificationInfo: NotificationInfo) ```
```Objective-C - (void)SNR_notificationDidDissmis:(SNRNotificationInfo *)notificationInfo ```
| Parameter | Type | Description | | --- | --- | --- | | **notificationInfo** | [NotificationInfo](/developers/mobile-sdk/class-reference/ios/campaigns#notificationinfo) | Object providing information about the notification. | ##### snr_notificationClicked(notificationInfo: NotificationInfo) {id=notification-delegate-notification-clicked} This method is called when a Synerise notification is clicked.
```Swift func snr_notificationClicked(notificationInfo: NotificationInfo) ```
```Objective-C - (void)SNR_notificationClicked:(SNRNotificationInfo *)notificationInfo ```
| Parameter | Type | Description | | --- | --- | --- | | **notificationInfo** | [NotificationInfo](/developers/mobile-sdk/class-reference/ios/campaigns#notificationinfo) | Object providing information about the notification. | ##### snr_notificationClicked(notificationInfo: NotificationInfo, actionButton: String) {id=notification-delegate-notification-clicked-with-button} This method is called when an action button is clicked in a Synerise notification.
```Swift func snr_notificationClicked(notificationInfo: NotificationInfo, actionButton: String) ```
```Objective-C - (void)SNR_notificationActionButtonClicked:(SNRNotificationInfo *)notificationInfo actionButton:(NSString *)actionButton ```
| Parameter | Type | Description | | --- | --- | --- | | **notificationInfo** | [NotificationInfo](/developers/mobile-sdk/class-reference/ios/campaigns#notificationinfo) | Object providing information about the notification. | | **actionButton** | String | Text on the clicked action button. | --- --- ### ClientStateDelegate {id=client-state-delegate} A delegate to handle customer's sign-in state changes. To set your object as delegate, you must use [this method](/developers/mobile-sdk/method-reference/ios/client-authentication#set-client-state-delegate).
```Swift Client.setClientStateDelegate(YOUR_OBJECT) ```
```Objective-C [SNRClient setClientStateDelegate:YOUR_OBJECT]; ```
##### snr_clientIsSignedIn() {id=client-state-delegate-client-is-signed-in} This method is called when a customer signs in.
```Swift func snr_clientIsSignedIn() ```
```Objective-C - (void)SNR_clientIsSignedIn ```
##### snr_clientIsSignedOut(reason: ClientSessionEndReason) {id=client-state-delegate-client-is-signed-out} This method is called when a customer signs out.
```Swift func snr_clientIsSignedOut(reason: ClientSessionEndReason) ```
```Objective-C - (void)SNR_clientIsSignedOutWithReason:(SNRClientSessionEndReason)reason ```
| Parameter | Type | Description | | --- | --- | --- | | **reason** | [ClientSessionEndReason](/developers/mobile-sdk/class-reference/ios/client#clientsessionendreason) | Specifies the reason for signing out. | --- --- ### InjectorInAppMessageDelegate {id=injector-in-app-message-delegate} A delegate to handle the states of [in-app message](/developers/mobile-sdk/campaigns/in-app-message).
**InjectorInAppMessageDelegate** is available from 4.6.0 SDK version.
To set your object as delegate, you must use [this method](/developers/mobile-sdk/method-reference/ios/campaigns#set-in-app-message-delegate).
```Swift Injector.setInAppMessageDelegate(YOUR_OBJECT) ```
```Objective-C [SNRInjector setInAppMessageDelegate:YOUR_OBJECT]; ```
##### snr_shouldInAppMessageAppear(data: InAppMessageData) -> Bool {id=injector-in-app-message-delegate-should-in-app-message-appear} This method is called after an in-app message is loaded and Synerise SDK asks for permission to show it.
```Swift func snr_shouldInAppMessageAppear(data: InAppMessageData) -> Bool ```
```Objective-C - (BOOL)SNR_shouldInAppMessageAppear:(SNRInAppMessageData *)data ```
| Parameter | Type | Description | | --- | --- | --- | | **data** | [InAppMessageData](/developers/mobile-sdk/class-reference/ios/campaigns#inappmessagedata) | Model representation of the in-app message. | ##### snr_inAppMessageDidAppear(data: InAppMessageData) {id=injector-in-app-message-delegate-in-app-message-did-appear} This method is called after an in-app message appears.
```Swift func snr_inAppMessageDidAppear(data: InAppMessageData) ```
```Objective-C - (void)SNR_inAppMessageDidAppear:(SNRInAppMessageData *)data ```
| Parameter | Type | Description | | --- | --- | --- | | **data** | [InAppMessageData](/developers/mobile-sdk/class-reference/ios/campaigns#inappmessagedata) | Model representation of the in-app message. | ##### snr_inAppMessageDidDisappear(data: InAppMessageData) {id=injector-in-app-message-delegate-in-app-message-did-disappear} This method is called after an in-app message disappears.
```Swift func snr_inAppMessageDidDisappear(data: InAppMessageData) ```
```Objective-C - (void)SNR_inAppMessageDidDisappear:(SNRInAppMessageData *)data ```
| Parameter | Type | Description | | --- | --- | --- | | **data** | [InAppMessageData](/developers/mobile-sdk/class-reference/ios/campaigns#inappmessagedata) | Model representation of the in-app message. | ##### snr_inAppMessageDidChangeSize(rect: CGRect) {id=injector-in-app-message-delegate-in-app-message-did-change-size} This method is called when an in-app message changes its size.
```Swift func snr_inAppMessageDidChangeSize(rect: CGRect) ```
```Objective-C - (void)SNR_inAppMessageDidChangeSize:(CGRect)rect ```
| Parameter | Type | Description | | --- | --- | --- | | **data** | [InAppMessageData](/developers/mobile-sdk/class-reference/ios/campaigns#inappmessagedata) | Model representation of the in-app message. | ##### snr_inAppMessageContextIsNeeded(data: InAppMessageData) -> [AnyHashable: Any]? {id=injector-in-app-message-delegate-in-app-message-context-is-needed} This method is called when an individual context (for example a profile ID, an item SKU) for an in-app message is needed.
```Swift func snr_inAppMessageContextIsNeeded(data: InAppMessageData) -> [AnyHashable: Any]? ```
```Objective-C - (nullable NSDictionary *)SNR_inAppMessageContextIsNeeded:(SNRInAppMessageData *)data ```
| Parameter | Type | Description | | --- | --- | --- | | **data** | [InAppMessageData](/developers/mobile-sdk/class-reference/ios/campaigns#inappmessagedata) | Model representation of the in-app message. | ##### snr_inAppMessageHandledAction(data: InAppMessageData, deepLink: String) {id=injector-in-app-message-delegate-in-app-message-handled-deeplink-action} This method is called when the [`SRInApp.openDeeplink(url)` method](/docs/campaign/in-app-messages/creating-inapp-templates/creating-inapp-template#open-deeplink) is used in an in-app message.
This method was renamed in 5.0.0 SDK version from `snr_inAppMessageHandledAction(data:deeplink:)`.
```Swift func snr_inAppMessageHandledAction(data: InAppMessageData, deepLink: String) ```
```Objective-C - (void)SNR_inAppMessageHandledDeeplinkAction:(SNRInAppMessageData *)data deepLink:(NSString *)deepLink ```
| Parameter | Type | Description | | --- | --- | --- | | **data** | [InAppMessageData](/developers/mobile-sdk/class-reference/ios/campaigns#inappmessagedata) | Model representation of the in-app message. | | **deepLink** | String | Deep link value from the action of the activity. | ##### snr_inAppMessageHandledAction(data: InAppMessageData, url: URL) {id=injector-in-app-message-delegate-in-app-message-handled-url-action} This method is called when the [`SRInApp.openUrl(url)` method](/docs/campaign/in-app-messages/creating-inapp-templates/creating-inapp-template#open-url) is used in an in-app message.
```Swift func snr_inAppMessageHandledAction(data: InAppMessageData, url: URL) ```
```Objective-C - (void)SNR_inAppMessageHandledURLAction:(SNRInAppMessageData *)data url:(NSURL *)url ```
| Parameter | Type | Description | | --- | --- | --- | | **data** | [InAppMessageData](/developers/mobile-sdk/class-reference/ios/campaigns#inappmessagedata) | Model representation of the in-app message. | | **url** | URL | URL value from the action of the activity. | ##### snr_inAppMessageHandledCustomAction(data: InAppMessageData, name: String, parameters: [AnyHashable: Any]) {id=injector-in-app-message-delegate-in-app-message-handled-custom-action} This method is called when the [`SRInApp.handleCustomAction(name, params)` method](/docs/campaign/in-app-messages/creating-inapp-templates/creating-inapp-template#trigger-a-custom-action) is used in an in-app message.
```Swift func snr_inAppMessageHandledCustomAction(data: InAppMessageData, name: String, parameters: [AnyHashable: Any]) ```
```Objective-C - (void)SNR_inAppMessageHandledCustomAction:(SNRInAppMessageData *)data name:(NSString *)name parameters:(NSDictionary *)parameters ```
| Parameter | Type | Description | | --- | --- | --- | | **data** | [InAppMessageData](/developers/mobile-sdk/class-reference/ios/campaigns#inappmessagedata) | Model representation of the in-app message. | | **name** | String | Custom action name for identification. | | **parameters** | [AnyHashable: Any] | Custom action parameters. | --- --- ### TrackerDelegate {id=tracker-delegate} A delegate to handle events from the Tracker. To set your object as delegate, you must use [this method](/developers/mobile-sdk/method-reference/ios/tracking#set-tracker-delegate).
```Swift Tracker.setDelegate(YOUR_OBJECT) ```
```Objective-C [SNRTracker setDelegate:YOUR_OBJECT]; ```
##### snr_locationUpdateRequired() {id=tracker-delegate-location-update-required} This method is called when the Tracker module requests a location update.
```Swift func snr_locationUpdateRequired() ```
```Objective-C - (void)SNR_locationUpdateRequired ```
--- --- ### NotificationServiceExtensionDelegate {id=notification-service-extension-delegate} A delegate to handle events from Notification Extension Service.
**NotificationServiceExtensionDelegate** is available from 4.0.0 SDK version.
To set your object as delegate, you must use this code in your Notification Service Extension.
```Swift NotificationServiceExtension.setDelegate(YOUR_OBJECT) ```
```Objective-C [SNRNotificationServiceExtension setDelegate:YOUR_OBJECT]; ```
##### notificationServiceExtensionDidFailDecryptionWithError(_: Error) {id=notification-service-extension-delegate-notification-service-extension-did-fail-decryption} This method is called when the decryption process fails.
```Swift func notificationServiceExtensionDidFailDecryptionWithError(_: Error) ```
```Objective-C - (void)notificationServiceExtensionDidFailDecryptionWithError:(NSError *)error ```
| Parameter | Type | Description | | --- | --- | --- | | **error** | NSError | The error that occurred | ##### notificationServiceExtensionDidFailProcessingWithError(_: Error) {id=notification-service-extension-delegate-notification-service-extension-did-fail-processing} This method is called when the processing notification operation fails.
```Swift func notificationServiceExtensionDidFailProcessingWithError(_: Error) ```
```Objective-C - (void)notificationServiceExtensionDidFailProcessingWithError:(NSError *)error ```
| Parameter | Type | Description | | --- | --- | --- | | **error** | NSError | The error that occurred | --- --- ### ContentWidgetDelegate {id=content-widget-delegate} A delegate to handle [Content Widget](/developers/mobile-sdk/displaying-recommendations/content-widget) actions. To set your object as delegate, you must use this code below.
```Swift let widget = ContentWidget(options: widgetOptions, appearance: widgetAppearance) widget.delegate = YOUR_OBJECT ```
```Objective-C SNRContentWidget *widget = [SNRContentWidget initWithOptions:options andAppearance:appearance]; widget.delegate = YOUR_OBJECT; ```
##### snr_widgetDidLoad(widget: ContentWidget) {id=content-widget-delegate-widget-did-load} This method is called after a widget is loaded.
```Swift func snr_widgetDidLoad(widget: ContentWidget) ```
```Objective-C - (void)SNR_widgetDidLoad:(SNRContentWidget *)widget ```
| Parameter | Type | Description | | --- | --- | --- | | **widget** | [ContentWidget](/developers/mobile-sdk/class-reference/ios/content-widget#contentwidget) | The widget instance that called the delegate method. | ##### snr_widgetDidNotLoad(widget:ContentWidget error: Error) {id=content-widget-delegate-widget-did-not-load} This method is called when an error occurs while loading a widget.
```Swift func snr_widgetDidNotLoad(widget:ContentWidget error: Error) ```
```Objective-C - (void)SNR_widget:(SNRContentWidget *)widget didNotLoadWithError:(NSError *)error ```
| Parameter | Type | Description | | --- | --- | --- | | **widget** | [ContentWidget](/developers/mobile-sdk/class-reference/ios/content-widget) | The widget instance that called the delegate method. | | **error** | NSError | The error that occurred. | ##### snr_widgetDidReceiveClickAction(widget:ContentWidget model: BaseModel) {id=content-widget-delegate-widget-did-receive-click-action} This method is called when the customer clicks a widget’s item.
```Swift func snr_widgetDidReceiveClickAction(widget:ContentWidget model: BaseModel) ```
```Objective-C - (void)SNR_widget:(SNRContentWidget *)widget didReceiveClickActionForModel:(SNRBaseModel *)model ```
| Parameter | Type | Description | | --- | --- | --- | | **widget** | [ContentWidget](/developers/mobile-sdk/class-reference/ios/content-widget) | The widget instance that called the delegate method. | | **model** | BaseModel | The model's object that was clicked. | ##### snr_widgetIsLoading(widget: ContentWidget isLoading: Bool) {id=content-widget-delegate-widget-is-loading} This method is called when the widget’s loading state changes.
```Swift func snr_widgetIsLoading(widget: ContentWidget isLoading: Bool) ```
```Objective-C - (void)SNR_widget:(SNRContentWidget *)widget isLoading:(BOOL)isLoading ```
| Parameter | Type | Description | | --- | --- | --- | | **widget** | [ContentWidget](/developers/mobile-sdk/class-reference/ios/content-widget) | The widget instance that called the delegate method. | | **isLoading** | Bool | Widget's loading state. | ##### snr_widgetDidChangeSize(widget: ContentWidget size: CGSize) {id=content-widget-delegate-widget-did-change-size} This method is called when the widget’s size changes.
```Swift func snr_widgetDidChangeSize(widget: ContentWidget size: CGSize) ```
```Objective-C - (void)SNR_widget:(SNRContentWidget *)widget didChangeToSize:(CGSize)size ```
| Parameter | Type | Description | | --- | --- | --- | | **widget** | [ContentWidget](/developers/mobile-sdk/class-reference/ios/content-widget) | The widget instance that called the delegate method. | | **size** | CGSize | Widget's new size. | --- --- ### InjectorWalkthroughDelegate {id=injector-walkthrough-delegate}
**InjectorWalkthroughDelegate** was removed in 5.0.0 SDK version.
--- --- ### InjectorBannerDelegate {id=injector-banner-delegate}
**InjectorBannerDelegate** was removed in 5.0.0 SDK version.
# Customer authentication --- ## Register customer account --- This method registers a new customer with an email, password, and optional data. This method requires the context object with a customer’s email, password, and optional data. Omitted fields are not modified. Depending on the backend configuration, the account may require activation. For details, see [customer registration](/developers/mobile-sdk/user-identification-and-authorization/overview). Do not allow signing in again (or signing up) when a customer is already signed in. Sign the customer out first. Do not create multiple instances nor call this method multiple times before execution. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_REGISTER_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** lib/modules/client/client_impl.dart **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> registerAccount(ClientAccountRegisterContext context, {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **context** | [ClientAccountRegisterContext](/developers/mobile-sdk/class-reference/flutter/client#clientaccountregistercontext) | yes | - | Object with the customer's email, password, and other optional data | | **onSuccess** | Function() | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
ClientAccountRegisterContext clientAccountRegisterContext = ClientAccountRegisterContext(email: email, password: password);

await Synerise.client.registerAccount(clientAccountRegisterContext, onSuccess: () {
  //onSuccess handling
}, onError: (SyneriseError error) {
  //onError handling
});
**Declaration:**
Future<void> registerAccount(ClientAccountRegisterContext context) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **context** | [ClientAccountRegisterContext](/developers/mobile-sdk/class-reference/flutter/client#clientaccountregistercontext) | yes | - | Object with the customer's email, password, and other optional data | **Return Value:** No value is returned. **Example:**
await Synerise.client.registerAccount(clientAccountRegisterContext).catchError((error)
## Request customer account activation --- This method requests sending an email with a URL that confirms the registration and activates the account. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_CONFIRMATION_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** lib/modules/client/client_impl.dart **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> requestAccountActivation(String email,
      {required void Function() onSuccess,
      required void Function(SyneriseError error) onError}) async
Before version 2.0.0, this method was called `activateAccount` **Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | String | yes | - | Customer’s email | | **onSuccess** | Function() | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
await Synerise.client.synerise-flutter-sdkAccount(email, onSuccess: () {
      //onSuccess handling
    }, onError: (SyneriseError error) {
      //onError handling
    });
**Declaration:**
Future<void> activateAccount(String email) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | String | yes | - | Customer’s email | **Return Value:** No value is returned. **Example:**
await Synerise.client.activateAccount(email).catchError((error)
## Confirm customer account activation --- This method confirms a customer account with the confirmation token. This method is a global operation and doesn't require customer authentication.
Returns the HTTP 400 status code if the account is already confirmed or 404 if the account does not exist.
The API key must have the `SAUTH_CONFIRMATION_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** lib/modules/client/client_impl.dart **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> confirmAccountActivation(String token, {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
Before version 1.0.0, this method was called `confirmAccount`.
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **token** | String | yes | - | Customer’s token provided by email | | **onSuccess** | Function() | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
await Synerise.client.confirmAccountActivation(token, onSuccess: () {
      //onSuccess handling
    }, onError: (SyneriseError error) {
      //onError handling
    });
**Declaration:**
Future<void> confirmAccountActivation(String token) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **token** | String | yes | - | Customer’s token provided by email | **Return Value:** No value is returned. **Example:**
await Synerise.client.confirmAccount(token).catchError((error)
## Request customer account activation by pin --- This method requests a customer's account registration process with the PIN code. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_PIN_CODE_RESEND_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** lib/modules/client/client_impl.dart **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> requestAccountActivationByPin(String email, {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
**Parameters:** | Parameter | Type | Mandatory | Description | | --- | --- | --- | --- | | **email** | String | yes | Customer's email | | **onSuccess** | Function() | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
await Synerise.client.requestAccountActivationByPin(email, onSuccess: () {
  //onSuccess handling
}, onError: (SyneriseError error) {
  //onError handling
});
**Declaration:**
Future<void> requestAccountActivationByPin(String email) async
**Parameters:** | Parameter | Type | Mandatory | Description | | --- | --- | --- | --- | | **email** | String | yes | Customer's email | **Return Value:** No value is returned. **Example:**
await Synerise.client.requestAccountActivationByPin(email).catchError((error) {
## Confirm customer account activation by pin --- This method confirms a customer's account registration process with the PIN code. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_PIN_CODE_RESEND_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** lib/modules/client/client_impl.dart **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> confirmAccountActivationByPin(String email, String pinCode, {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
**Parameters:** | Parameter | Type | Mandatory | Description | | --- | --- | --- | --- | | **pinCode** | String | yes | Code sent to a customer's email | | **email** | String | yes | Customer's email | | **onSuccess** | Function() | yes | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
await Synerise.client.confirmAccountActivationByPin(email, pinCode, onSuccess: () {
      //onSuccess handling
    }, onError: (SyneriseError error) {
      //onError handling
    });
**Declaration:**
Future<void> confirmAccountActivationByPin(String email, String pinCode) async
**Parameters:** | Parameter | Type | Mandatory | Description | | --- | --- | --- | --- | | **pinCode** | String | yes | Code sent to a customer's email | | **email** | String | yes | Customer's email | **Return Value:** No value is returned. **Example:**
await Synerise.client.confirmAccountActivationByPin(email, pinCode).catchError((error) {
## Sign in a customer --- This method signs a customer in to obtain a JSON Web Token (JWT) which can be used in subsequent requests. The SDK will refresh the token before each call if it is about to expire (but not expired). Do NOT allow signing in again (or signing up) when a customer is already signed in. First, sign the customer out. Do NOT create multiple instances nor call this method multiple times before execution. **Declared In:** lib/modules/client/client_impl.dart **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> signIn(String email, String password, {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | String | yes | - | Customer’s email | | **password** | String | yes | - | Customer’s password | | **onSuccess** | Function() | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
await Synerise.client.signIn(email, password, onSuccess: () {
  //onSuccess handling
}, onError: (SyneriseError error) {
  //onError handling
});
**Declaration:**
Future<void> signIn(String email, String password) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | String | yes | - | Customer’s email | | **password** | String | yes | - | Customer’s password | **Return Value:** No value is returned. **Example:**
await Synerise.client.signIn(email,password).catchError((error)
## Sign in a customer conditionally --- This method signs a customer in to obtain a JSON Web Token (JWT) which can be used in subsequent requests. The SDK will refresh the token before each call if it is about to expire (but not expired). Do NOT allow signing in again (or signing up) when a customer is already signed in. First, sign the customer out. Do NOT create multiple instances nor call this method multiple times before execution. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | **Declared In:** lib/modules/client/client_impl.dart **Related To:** [ClientConditionalAuthResult](/developers/mobile-sdk/class-reference/flutter/client#clientconditionalauthresult) **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> signInConditionally(String email, String password,
      {required void Function(ClientConditionalAuthResult) onSuccess,
      required void Function(SyneriseError error) onError}) async
**Parameters:** | Parameter | Type | Mandatory | Description | | --- | --- | --- | --- | | **email** | String | yes | Customer's email | | **password** | String | yes | Customer's password | **Return Value:** No value is returned. **Example:**
```Dart await Synerise.client.signInConditionally(email, password, onSuccess: (ClientConditionalAuthResult result) { //onSuccess handling }, onError: (SyneriseError error) { //onError handling }); ```
**Declaration:**
Future<ClientConditionalAuthResult> signInConditionally(String email, String password) async
**Parameters:** | Parameter | Type | Mandatory | Description | | --- | --- | --- | --- | | **email** | String | yes | Customer's email | | **password** | String | yes | Customer's password | **Return Value:** [ClientConditionalAuthResult](/developers/mobile-sdk/class-reference/flutter/client#clientconditionalauthresult) **Example:**
```Dart await Synerise.client.signInConditionally(email, password).catchError((error) ```
## Authenticate customer by IdentityProvider --- This method authenticates a customer with OAuth, Facebook, Google, Apple, or Synerise. If an account for the customer does not exist and the identity provider is different than Synerise, this request creates an account. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.7.6 | 3.8.0 | 0.9.19 | 0.3.0 | **Declared In:** lib/modules/client/client_impl.dart **Related To:** [ClientAuthContext](/developers/mobile-sdk/class-reference/flutter/client#clientauthcontext) [ClientIdentityProvider](/developers/mobile-sdk/class-reference/flutter/client#clientidentityprovider) **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> authenticate(ClientAuthContext clientAuthContext, IdentityProvider identityProvider, String tokenString,
    {required void Function(bool) onSuccess, required void Function(SyneriseError) onError}) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **clientAuthContext** | [ClientAuthContext](/developers/mobile-sdk/class-reference/flutter/client#clientauthcontext) | yes | - | Object which contains agreements, attributes, and identifier of authorization | | **identityProvider** | [ClientIdentityProvider](/developers/mobile-sdk/class-reference/flutter/client#clientidentityprovider) | yes | - | Provider of your token | | **tokenString** | String | yes | - | Token retrieved from provider | | **onSuccess** | Function() | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
await Synerise.client.authenticate(clientAuthContext, identityProvider, tokenString, onSuccess: (bool result) {
      //onSuccess handling
    }, onError: (SyneriseError error) {
      //onError handling
    });
**Declaration:**
Future<bool> authenticate(ClientAuthContext clientAuthContext, IdentityProvider identityProvider, String tokenString) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **clientAuthContext** | [ClientAuthContext](/developers/mobile-sdk/class-reference/flutter/client#clientauthcontext) | yes | - | Object which contains agreements, attributes, and identifier of authorization | | **identityProvider** | [ClientIdentityProvider](/developers/mobile-sdk/class-reference/flutter/client#clientidentityprovider) | yes | - | Provider of your token | | **tokenString** | String | yes | - | Token retrieved from provider | **Return Value:** **true** if the operation is success, otherwise it throws an error. **Example:**
await Synerise.client.authenticate(clientAuthContext, identityProvider, tokenString).catchError((error)
## Authenticate customer conditionally by IdentityProvider --- This method authenticates a customer with OAuth, Facebook, Google, Apple, or Synerise. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | **Declared In:** lib/modules/client/client_impl.dart **Related To:** [ClientConditionalAuthResult](/developers/mobile-sdk/class-reference/flutter/client#clientconditionalauthresult) [ClientIdentityProvider](/developers/mobile-sdk/class-reference/flutter/client#clientidentityprovider) **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> authenticateConditionally(ClientAuthContext clientAuthContext, IdentityProvider identityProvider, String tokenString,
    {String? authID, required void Function(ClientConditionalAuthResult) onSuccess, required void Function(SyneriseError) onError}) async
**Parameters:** | Parameter | Type | Optional | Description | | --- | --- | --- | --- | | **clientAuthContext** | [ClientAuthContext](/developers/mobile-sdk/class-reference/flutter/client#clientauthcontext) | no | Object which contains agreements and attributes | | **identityProvider** | [ClientIdentityProvider](/developers/mobile-sdk/class-reference/flutter/client#clientidentityprovider) | no | Provider of your token | | **tokenString** | String | no | Token retrieved from provider | | **authID** | String | yes | Optional identifier of authorization | | **onSuccess** | Function([ClientConditionalAuthResult](/developers/mobile-sdk/class-reference/flutter/client#clientconditionalauthresult) result) | yes | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | Function to be executed when the operation is completed with an error |
**authID** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** No value is returned. **Example:**
Token token = Token(tokenString: "tokenString", origin: TokenOrigin.anonymous, expirationDate: DateTime;
    await Synerise.client.retrieveToken(onSuccess: (Token token) {
      token = token;
    }, onError: (SyneriseError error) {
    //onError handling
    });
    String tokenString = token.tokenString;
    IdentityProvider identityProvider = IdentityProvider.oauth;
    
    await Synerise.client.authenticateConditionally(identityProvider, tokenString, onSuccess: (ClientConditionalAuthResult result) {
      //onSuccess handling
    }, onError: (SyneriseError error) {
      //onError handling
    });
**Declaration:**
Future<ClientConditionalAuthResult> authenticateConditionally(ClientAuthContext clientAuthContext, IdentityProvider identityProvider, String tokenString) async
**Parameters:** | Parameter | Type | Optional | Description | | --- | --- | --- | --- | | **token** | String | no | Token retrieved from provider | | **clientIdentityProvider** | [ClientIdentityProvider](/developers/mobile-sdk/class-reference/flutter/client#clientidentityprovider) | no | Provider of your token | | **authID** | String | yes | Optional identifier of authorization | | **context** | [ClientConditionalAuthContext](/developers/mobile-sdk/class-reference/flutter/client#clientconditionalauthcontext) | no | Object which contains agreements and attributes |
**authID** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** [ClientConditionalAuthResult](/developers/mobile-sdk/class-reference/flutter/client#clientconditionalauthresult) **Example:**
ClientAgreements? agreements = ClientAgreements(push: false, rfid: false, wifi: false);
    Map<String, Object>? attributes;
    ClientAuthContext clientAuthContext = ClientAuthContext(authId: 'AUTH_ID', agreements: agreements, attributes: attributes);
    Token token = await Synerise.client.retrieveToken().catchError((error) {
      String errorMessage = Utils.handlePlatformException(error);
      Utils.displaySimpleAlert("error on handling api call \n $errorMessage", context);
      throw Exception(errorMessage);
    });
    String tokenString = token.tokenString;
    IdentityProvider identityProvider = IdentityProvider.oauth;
    
    ClientConditionalAuthResult result =
        await Synerise.client.authenticateConditionally(clientAuthContext, identityProvider, tokenString).catchError((error) {
      String errorMessage = Utils.handlePlatformException(error);
      Utils.displaySimpleAlert("error on handling api call: you need to be signed in to authenticate \n $errorMessage", context);
      throw Exception(errorMessage);
    });
## Authenticate customer via Simple Profile Authentication --- This method authenticates a customer with Simple Profile Authentication. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.14.0 | 5.7.1 | 0.15.0 | 0.7.0 |
When you use this method, you must set a request validation salt by using the `Synerise.setRequestValidationSalt(_:)` method (if salt is enabled for Simple Profile Authentication).
The API key must have the `SAUTH_SIMPLE_AUTH_CREATE` from the **Auth** group.
**Declared In:** lib/modules/client/client_impl.dart **Related To:** [ClientSimpleAuthenticationData](/developers/mobile-sdk/class-reference/flutter/client#clientsimpleauthenticationdata) **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> simpleAuthentication(ClientSimpleAuthenticationData data, String authID, {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
**Parameters:** | Parameter | Type | Mandatory | Description | | --- | --- | --- | --- | | **data** | [ClientSimpleAuthenticationData](/developers/mobile-sdk/class-reference/flutter/client#clientsimpleauthenticationdata) | yes | Object which contains customer data | | **authID** | String | yes | Required identifier of authorization | | **onSuccess** | Function() | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | - | Function to be executed when the operation is completed with an error |
**authID** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** No value is returned. **Example:**
ClientSimpleAuthenticationData data =
        ClientSimpleAuthenticationData(firstName: firstName, lastName: lastName, email: email, customId: customID);
    await Synerise.client.simpleAuthentication(data, authID, onSuccess: () {
      //onSuccess handling
    }, onError: (SyneriseError error) {
      //onError handling
    });
**Declaration:**
Future<void> simpleAuthentication(ClientSimpleAuthenticationData clientSimpleAuthenticationData, String authID) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **data** | [ClientSimpleAuthenticationData](/developers/mobile-sdk/class-reference/flutter/client#clientsimpleauthenticationdata) | yes | - | Object which contains customer data | | **authID** | String | yes | null | Required identifier of authorization |
**authID** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** No value is returned.
## Check if a customer is signed in (via RaaS, OAuth, Facebook, Apple) --- This method checks if a customer is signed in (via Synerise Authentication - RaaS, OAuth, Facebook, Apple). **Declared In:** lib/modules/client/client_impl.dart **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client) **Declaration:**
Future<bool> isSignedIn() async
**Return Value:** **true** if the customer is signed in, otherwise returns **false**. **Example:**
bool isSignedInBool = await Synerise.client.isSignedIn();
## Check if a customer is signed in (via Simple Profile Authentication) --- This method checks if a customer is signed in (via Simple Profile Authentication). | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.14.0 | 5.7.1 | 0.15.0 | 0.7.0 | **Declared In:** lib/modules/client/client_impl.dart **Class:** [Client](/developers/mobile-sdk/class-reference/flutter/modules#client) **Declaration:**
Future<bool> isSignedInViaSimpleAuthentication() async
**Return Value:** **true** if the customer is signed in (via Simple Profile Authentication), otherwise returns **false**. **Example:**
await Synerise.client
        .isSignedInViaSimpleAuthentication()
        .then((bool result) {
      if (result == true) {
        //result handling
      } else {
        //error handling
      }
    });
## Sign out a customer --- This method signs out a customer out.
This method works with every authentication type (via Synerise, External Provider, OAuth or Simple Profile Authentication).
**Declared In:** lib/modules/client/client_impl.dart **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client) **Declaration:**
Future<void> signOut() async
**Return Value:** No value is returned. **Example:**
```Dart Synerise.client.signOut().whenComplete(() => { //onSuccess handling }); ```
## Sign out customer with mode or from all devices --- This method signs out a customer out with a chosen mode and Determines if the method should sign out all devices. Available modes: - `.signOut` mode signs out the customer. - `.signOutWithSessionDestroy` mode signs out the customer and additionally, clears the anonymous session and regenerates the customer UUID. The `fromAllDevices` parameter determines whether the method should notify the backend to sign out all devices. **IMPORTANT: It is an asynchronous method.** | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.11.0 | 5.1.0 | 0.14.0 | 1.0.0 |
This method works with every authentication type (via Synerise, External Provider, OAuth or Simple Profile Authentication).
**Declared In:** lib/modules/client/client_impl.dart **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> signOutWithMode(ClientSignOutMode mode, bool fromAllDevices, {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
**Parameters:** | Parameter | Type | Mandatory | Description | | --- | --- | --- | --- | | **mode** | [ClientSignOutMode](/developers/mobile-sdk/class-reference/flutter/client#clientsignoutmode) | yes | Mode of signing out | | **fromAllDevices** | bool | yes | Determines if the method should sign out all devices | | **onSuccess** | Function() | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
ClientSignOutMode mode = ClientSignOutMode.signOutWithSessionDestroy;
    bool fromAllDevices = true;
    await Synerise.client.signOutWithMode(mode, fromAllDevices, onSuccess: () {
      //onSuccess handling
    }, onError: (SyneriseError error) {
      //onError handling
    });
**Declaration:**
Future<void> signOutWithMode(ClientSignOutMode mode, bool fromAllDevices) async
**Parameters:** | Parameter | Type | Mandatory | Description | | --- | --- | --- | --- | | **mode** | [ClientSignOutMode](/developers/mobile-sdk/class-reference/flutter/client#clientsignoutmode) | yes | Mode of signing out | | **fromAllDevices** | bool | yes | Determines if the method should sign out all devices | **Return Value:** No value is returned. **Example:**
ClientSignOutMode mode = ClientSignOutMode.signOutWithSessionDestroy;
    bool fromAllDevices = true;
    await Synerise.client.signOutWithMode(mode, fromAllDevices).catchError((error) {
# Client ### ClientIdentityProvider This enum contains values which set the provider for deleting a profile (a profile itself and their account). **Declared In:** `com.synerise.sdk.client.model.ClientIdentityProvider` **Declaration:**
```Java public enum ClientIdentityProvider ```
```Kotlin public enum ClientIdentityProvider ```
**Values:** | Property | Value | Description | | --- | --- | --- | | **FACEBOOK** | "FACEBOOK" | Facebook provider | | **GOOGLE** | "GOOGLE" | Google provider | | **OAUTH** | "OAUTH" | Oauth provider | | **SYNERISE** | "SYNERISE" | Synerise provider | | **SIMPLE_AUTH** | "SIMPLE_AUTH" | Simple Profile Authentication provider | **Methods:** Get a provider.
public static ClientIdentityProvider getByProvider(String provider)
--- --- --- ### AuthConditions Auth conditions model. Model passes status and conditions. **Declared In:** `com.synerise.sdk.client.model` **Declaration:**
```Java public class AuthConditions ```
```Kotlin class AuthConditions ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **status** | [ConditionalAuthenticationStatus](/developers/mobile-sdk/class-reference/android/client#conditionalauthenticationstatus) | no | - | Status of authentication | | **conditions** | ArrayList | no | - | List of conditions |
All of the properties above are accessible by using getters.
**Methods:** There are getters and setters for the above properties. --- --- --- ### ConditionalAuthenticationStatus This enum contains values which describe the status of an after a log-in attempt. **Declared In:** `com.synerise.sdk.client.model.ConditionalAuthenticationStatus` **Declaration:**
```Java public enum ConditionalAuthenticationStatus ```
```Kotlin public enum ConditionalAuthenticationStatus ```
**Values:** | Property | Description | | --- | -- | | **SUCCESS** | Authentication successful | | **UNAUTHORIZED** | Currently unused | | **ACTIVATION_REQUIRED** |Currently unused | | **REGISTRATION_REQUIRED** | Currently unused | | **APPROVAL_REQUIRED** | Currently unused | | **TERMS_ACCEPTANCE_REQUIRED** | Currently unused | | **MFA_REQUIRED** | Currently unused | **Methods:** There are no methods. --- --- ### ClientData **Declared In:** `com.synerise.sdk.client.model.simpleAuth` **Declaration:**
```Java public final class ClientData extends ClientDataInformation ```
```Kotlin class ClientData : ClientDataInformation ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **email** | String | yes | - | Customer's email | | **phone** | String | yes | - | Customer's phone | | **customId** | String | yes | - | Customer's custom ID | | **uuid** | String | yes | - | Customer's uuid | | **firstName** | String | yes | - | Customer's first name | | **lastName** | String | yes | - | Customer's last name | | **displayName** | String | yes | - | Customer's display name | | **company** | String | yes | - | Customer's company | | **address** | String | yes | - | Customer's address | | **city** | String | yes | - | Customer's city | | **province** | String | yes | - | Customer's province | | **zipCode** | String | yes | - | Customer's ZIP code | | **countryCode** | String | yes | - | Customer's country code | | **birthDate** | String | yes | - | Customer's birthdate | | **sex** | [Sex](/developers/mobile-sdk/class-reference/android/client#sex) | yes | - | Customer's sex | | **avatarUrl** | String | yes | - | Customer's avatar URL | | **agreements** | [Agreements](/developers/mobile-sdk/class-reference/android/client#agreements) | yes | - | Customer's agreements | | **attributes** | [Attributes](/developers/mobile-sdk/class-reference/android/client#attributes) | yes | - | Customer's attributes |
All properties above are accessible by using setters.
**Initializers:** There are no initializers. **Methods:** There are only setters for above properties. --- --- ### ClientSessionEndReason This enum contains values which describe the reason for sending a session. **Declared In:** `com.synerise.sdk.core.types.enums.ClientSessionEndReason` **Declaration:**
```Java public enum ClientSessionEndReason ```
```Kotlin public enum ClientSessionEndReason ```
**Values:** | Property | Description | | --- | --- | | **SESSION_EXPIRATION** | Session ended due to token expiration. | | **SECURITY_EXCEPTION** | Session ended due to security errors. | | **USER_SIGN_OUT** | Session ended due to a profile sign-out. | | **SYSTEM_SIGN_OUT** | Session ended due to a remote sign out by the system. | | **SESSION_DESTROYED** | Session ended due to the `Client.destroySession` method. | | **CLIENT_REJECTED** | Session ended due to 401 or 410 response. | | **USER_ACCOUNT_DELETED** | Session ended due to profile account deletion. | **Methods:** There are no methods. --- --- ### ClientSignOutMode This enum contains values for the sign out mode. **Declared In:** `com.synerise.sdk.core.types.enums` **Declaration:**
```Java public enum ClientSignOutMode ```
```Kotlin public enum ClientSignOutMode ```
**Values:** | Property | Value | Description | | --- | --- | --- | | **SIGN_OUT** | "LOGOUT" | Sign out with a backend call. The token is invalidated and cleared in the SDK, but the UUID remains the same. | | **SIGN_OUT_WITH_SESSION_DESTROY** | "LOGOUT_WITH_SESSION_DESTROY" | Sign out with a backend call. The token is invalidated. The token and UUID are cleared in the SDK. | **Methods:** No methods. --- --- --- ### GetAccountInformation Class providing a profile account information. **Declared In:** `com.synerise.sdk.client.model.GetAccountInformation` **Declaration:**
```Java public final class GetAccountInformation extends AccountInformation implements Serializable ```
```Kotlin class GetAccountInformation:AccountInformation(), Serializable ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **clientId** | long | no | - | A unique ID of a profile | | **lastActivityDate** | Date | no | - | Profile's last performed activity date | | **email** | String | no | - | Profile's email | | **phone** | String | no | - | Profile's phone | | **customId** | String | no | - | Profile's customId | | **uuid** | String | no | - | Profile's UUID | | **firstName** | String | no | - | Profile's first name | | **lastName** | String | no | - | Profile's last name | | **displayName** | String | no | - | Profile's display name | | **company** | String | no | - | Profile's company | | **address** | String | no | - | Profile's address | | **city** | String | no | - | Profile's city | | **province** | String | no | - | Profile's province | | **zipCode** | String | no | - | Profile's ZIP code | | **countryCode** | String | no | - | Profile's country code | | **birthDate** | String | no | - | Profile's birth date | | **sex** | [Sex](/developers/mobile-sdk/class-reference/android/client#sex) | no | - | Profile's sex | | **avatarUrl** | String | no | - | Profile's avatar URL | | **anonymous** | Boolean | no | - | Defines if the profile is anonymous | | **agreements** | [Agreements](/developers/mobile-sdk/class-reference/android/client#agreements) | no | - | Profile's agreements | | **attributes** | [Attributes](/developers/mobile-sdk/class-reference/android/client#attributes) | no | - | Profile's attributes | | **tags** | List | no | - | Profile's tags |
All properties above are accessible by using getters.
**Initializers:** There are no initializers. **Methods:** There are only getters for the above properties. --- --- --- ### UpdateAccountBasicInformation Class providing data to update account basic information. **Declared In:** `com.synerise.sdk.client.model.UpdateAccountBasicInformation` **Declaration:**
```Java public final class UpdateAccountBasicInformation ```
```Kotlin class UpdateAccountBasicInformation ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **phoneNumber** | String | no | - | Profile's phone | | **firstName** | String | no | - | Profile's first name | | **lastName** | String | no | - | Profile's last name | | **displayName** | String | no | - | Profile's display name | | **company** | String | no | - | Profile's company | | **address** | String | no | - | Profile's address | | **city** | String | no | - | Profile's city | | **province** | String | no | - | Profile's province | | **zipCode** | String | no | - | Profile's ZIP code | | **countryCode** | String | no | - | Profile's country code | | **birthDate** | String | no | - | Profile's birth date | | **sex** | [Sex](/developers/mobile-sdk/class-reference/android/client#sex) | no | - | Profile's sex | | **avatarUrl** | String | no | - | Profile's avatar URL | | **anonymous** | Boolean | no | - | Defines if the profile is anonymous | | **agreements** | [Agreements](/developers/mobile-sdk/class-reference/android/client#agreements) | no | - | Profile's agreements | | **attributes** | [Attributes](/developers/mobile-sdk/class-reference/android/client#attributes) | no | - | Profile's attributes |
All properties above are accessible by using setters.
**Initializers:** There are no initializers. **Methods:** There are only setters for above properties. --- --- --- ### UpdateAccountInformation Class providing data to update account information. **Declared In:** `com.synerise.sdk.client.model.UpdateAccountInformation` **Declaration:**
```Java public final class UpdateAccountInformation extends AccountInformation ```
```Kotlin class UpdateAccountInformation:AccountInformation() ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **email** | String | no | - | Profile's email | | **phoneNumber** | String | no | - | Profile's phone | | **customId** | String | no | - | Profile's customId | | **uuid** | String | no | - | Profile's uuid | | **firstName** | String | no | - | Profile's first name | | **lastName** | String | no | - | Profile's last name | | **displayName** | String | no | - | Profile's display name | | **company** | String | no | - | Profile's company | | **address** | String | no | - | Profile's address | | **city** | String | no | - | Profile's city | | **province** | String | no | - | Profile's province | | **zipCode** | String | no | - | Profile's ZIP code | | **countryCode** | String | no | - | Profile's country code | | **birthDate** | String | no | - | Profile's birth date | | **sex** | [Sex](/developers/mobile-sdk/class-reference/android/client#sex) | no | - | Profile's sex | | **avatarUrl** | String | no | - | Profile's avatar URL | | **anonymous** | Boolean | no | - | Defines if the profile is anonymous | | **agreements** | [Agreements](/developers/mobile-sdk/class-reference/android/client#agreements) | no | - | Profile's agreements | | **attributes** | [Attributes](/developers/mobile-sdk/class-reference/android/client#attributes) | no | - | Profile's attributes |
All properties above are accessible by using setters.
**Initializers:** There are no initializers. **Methods:** There are only setters for above properties. --- --- --- ### RegisterClient Class responsible for registering a profile. **Declared In:** `com.synerise.sdk.client.model.client.RegisterClient` **Declaration:**
```Java public class RegisterClient extends BaseClient ```
```Kotlin class RegisterClient : BaseClient ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **agreements** | [Agreements](/developers/mobile-sdk/class-reference/android/client#agreements) | no | - | Profile's agreements | | **attributes** | [Attributes](/developers/mobile-sdk/class-reference/android/client#attributes) | no | - | Profile's attributes | | **city** | String | yes | - | Profile's city | | **company** | String | yes | - | Profile's company | | **countryCode** | String | yes | - | Profile's country code | | **customId** | String | yes | - | Profile's customId | | **firstName** | String | yes | - | Profile's first name | | **lastName** | String | yes | - | Profile's last name | | **phoneNumber** | String | yes | - | Profile's phone number | | **province** | String | yes | - | Profile's province | | **sex** | [Sex](/developers/mobile-sdk/class-reference/android/client#sex) | yes | - | Profile's sex | | **zipCode** | String | yes | - | Profile's ZIP code | | **uuid** | String | yes | - | Profile's UUID | | **email** | String | yes | - | Profile's email | | **password** | String | yes | - | Profile's password | **Initializers:** There are no initializers. **Methods:** All properties have their own setters. --- --- --- ### PasswordResetRequest Class responsible for creating a payload for password reset request. **Declared In:** `com.synerise.sdk.client.model.password.PasswordResetRequest` **Declaration:**
```Java public final class PasswordResetRequest ```
```Kotlin class PasswordResetRequest ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **email** | String | yes | - | Profile's email | **Initializers:** There is a constructor.
public PasswordResetRequest(@NonNull String email)
**Methods:** There are no methods. --- --- --- ### PasswordResetConfirmation Class responsible for creating a payload for password reset confirmation. **Declared In:** `com.synerise.sdk.client.model.password.PasswordResetConfirmation` **Declaration:**
```Java public final class PasswordResetConfirmation ```
```Kotlin class PasswordResetConfirmation ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **password** | String | no | - | Profile's password | | **token** | String | no | - | Profile's token | **Initializers:** There is a constructor.
public PasswordResetConfirmation(@NonNull String password, @NonNull String token)
**Methods:** There are no methods. --- --- --- ### Sex This enum contains values for the `sex` parameter. **Declared In:** `com.synerise.sdk.core.types.enums.Sex` **Declaration:**
```Java public enum Sex ```
```Kotlin public enum Sex ```
**Values:** | Property | Value | Description | | --- | --- | --- | | **FEMALE** | "FEMALE" | Female | | **MALE** | "MALE" | Male | | **OTHER** | "OTHER" | Other | | **NA** | "NOT_SPECIFIED" | Not specified | **Methods:** This method retrieves the value of the `sex` parameter.
public String getSex()
--- This method retrieves the value of the `sex` parameter.
public static Sex getSex(String name)
--- --- --- ### Agreements Class responsible for passing agreements. **Declared In:** `com.synerise.sdk.client.model.client.Agreements` **Declaration:**
```Java public class Agreements ```
```Kotlin class Agreements ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **email** | Boolean | yes | - | Email agreement | | **sms** | Boolean | yes | - | SMS agreement | | **push** | Boolean | yes | - | Push agreement | | **bluetooth** | Boolean | yes | - | Bluetooth agreement | | **rfid** | Boolean | yes | - | RFID agreement | | **wifi** | Boolean | yes | - | WiFi agreement | **Initializers:** There are no initializers. **Methods:** All properties have their own setters and getters. --- --- --- ### Attributes Class responsible for passing attributes. **Declared In:** `com.synerise.sdk.client.model.client.Attributes` **Declaration:**
```Java public class Attributes ```
```Kotlin class Attributes ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **properties** | HashMap | yes | - | A key-value pair of profile's attributes | **Initializers:** There are no initializers. **Methods:** This method adds attributes.
public Attributes add(String key, String value)
--- This method retrieves a value of an attribute.
public HashMap<String, String> getProperties()
--- --- --- ### ClientEventData Event data model. **Declared In:** `com.synerise.sdk.client.model.events.ClientEventData` **Declaration:**
```Java public class ClientEventData ```
```Kotlin class ClientEventData ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **time** | String | no | - | Event time | | **action** | String | no | - | Event action | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision Hub or Automation Hub. It isn't shown on a Profile card. | | **client** | HashMap | no | - | Profiles |
All properties above are accessible by using getters and setters.
**Initializers:** There are no initializers. **Methods:** This method returns the value of the `email` attribute from the profile hashmap.
public String getClientEmail()
--- This method returns the `uuid` attribute from the profile hashmap.
public String getClientUuid()
--- This method returns the `clientId` attribute from the profile hashmap.
public int getClientId()
--- --- --- ### ClientEventQuery Class responsible for creating a query to get events. **Declared In:** `com.synerise.sdk.client.model.client.ClientEventsQuery` **Declaration:**
```Java public class ClientEventsQuery ```
```Kotlin class ClientEventsQuery ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **actions** | List | yes | - | Event action | | **timeFrom** | Date | yes | - | Event time | | **label** | String | yes | - | This value is currently unused | | **limit** | int | yes | 1000 | Event limit |
All properties above are accessible by using setters.
**Initializers:** There are no initializers. **Methods:** There are no methods. --- --- --- ### TokenPayload TokenPayload model. **Declared In:** `com.synerise.sdk.core.types.model.TokenPayload` **Declaration:**
```Java public class TokenPayload ```
```Kotlin class TokenPayload ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **tokenString** | String | no | Token as a raw string | | **expirationDate** | Date | no | Token's expiration time | | **creationDate** | Date | no | Token's creation time | | **rlm** | [TokenRLM](/developers/mobile-sdk/class-reference/android/client#tokenrlm) | no | Token's RLM | | **origin** | [TokenOrigin](/developers/mobile-sdk/class-reference/android/client#tokenorigin) | no | Token's origin | | **uuid** | String | no | Customer's UUID | | **clientId** | String | no | Customer's ID | | **customId** | String | yes | Customer's custom ID |
All properties above are accessible by using getters.
**Initializers:** There are no initializers. **Methods:** There are only getters for the above properties. --- --- --- ### Token Token model. **Declared In:** `com.synerise.sdk.core.types.model.Token` **Declaration:**
```Java public class Token ```
```Kotlin class Token ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **rawJwt** | String | no | - | Raw JWT token string | | **expirationUnixTime** | long | no | - | Parsed expiration time in UNIX format | | **signKey** | String | no | - | Encrypted signing key | | **tokenRLM** | [TokenRLM](/developers/mobile-sdk/class-reference/android/client#tokenrlm) | no | - | Token scope | | **tokenOrigin** | [TokenOrigin](/developers/mobile-sdk/class-reference/android/client#tokenorigin) | no | - | Token source origin | | **clientId** | String | no | - | Token customer ID | | **customId** | String | no | - | Token customId |
All properties above are accessible by using getters.
**Initializers:**
public static Token createToken(String signKey, String rawJwt, long expirationUnixTime, String rlm, String origin)
--- --- --- ### TokenOrigin This enum contains values for a token origin. **Declared In:** `com.synerise.sdk.core.types.model.Token.TokenOrigin` **Declaration:**
```Java public enum TokenOrigin ```
```Kotlin public enum TokenOrigin ```
**Values:** | Property | Value | Description | | --- | --- | --- | | **SYNERISE** | "SYNERISE" | Token comes from Synerise | | **SIMPLE_AUTH** | "SIMPLE_AUTH" | Token comes from Synerise Simple Profile Authentication | | **FACEBOOK** | "FACEBOOK" | Token comes from Facebook | | **OAUTH** | "OAUTH" | Token comes from OAuth | | **UNKNOWN** | "UNKNOWN" | Unknown token source | **Methods:** This method retrieves the value of the `origin` parameter.
public String getOrigin()
--- This method retrieves the value of the `origin` parameter.
public static TokenOrigin getOrigin(String rlm)
--- --- --- ### TokenRLM This enum contains values for a token realm. **Declared In:** `com.synerise.sdk.core.types.model.Token.TokenRLM` **Declaration:**
```Java public enum TokenRLM ```
```Kotlin public enum TokenRLM ```
**Values:** | Property | Value | Description | | --- | --- | --- | | **ANONYMOUS** | "anonymous_client" | Anonymous profile | | **CLIENT** | "client" | Recognized profile | **Methods:** This method retrieves the value of the `rlm` parameter.
public String getRlm()
--- This method retrieves the value of the `rlm` parameter.
public static TokenRLM getRlm(String rlm)
--- # Installation and configuration In this section, you will find out how to install, configure, and initialize SDK in the Android, iOS and React Native mobile applications. ## Contents # React Native ## Class reference - React Native # Silent push ## Overview --- Silent push is a hidden notification that is delivered to the app. It does not cause any interaction with the user like a typical push. Silent notifications quietly deliver a certain set of data to the app so you may use it to notify that new content is available or inform about changes in the content. This kind of campaign does not affect your UI. Within the silent push campaign, the SDK provides features such as remote sign out or acquiring location by using a silent push command. Read more in the [SDK Commands](#sdk-commands) section. ## Configuration --- Silent push campaign is served by push notifications. See: - [Configuring push notifications - Android](/developers/mobile-sdk/configuring-push-notifications/android) - [Configuring push notifications - iOS](/developers/mobile-sdk/configuring-push-notifications/ios) - [Configuring push notifications - React Native](/developers/mobile-sdk/configuring-push-notifications/react-native) - [Configuring push notifications - Flutter](/developers/mobile-sdk/configuring-push-notifications/flutter) Additionally, check possible available configuration options in the [Settings](/developers/mobile-sdk/settings#notifications). ## Checking custom notification payloads --- The silent push campaign is designed to send notifications with your own payload and in this case should not be passed to the SDK. However, the campaign allows sending any data in payload including [SDK commands](#sdk-commands). Then, the notification must be handled correctly. You may use the samples below.
```Java @Override public void onMessageReceived(RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); Map data = remoteMessage.getData(); if (Injector.isSynerisePush(data)) { if (Injector.isSilentCommand(data)) { try { SilentCommand silentCommand = Injector.getSilentCommand(data); <> } catch (ValidationException e) { e.printStackTrace(); } } } else { <> } } ```
```Swift extension NotificationService: UNUserNotificationCenterDelegate { func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { let userInfo = notification.userInfo let isSyneriseNotification: Bool = Synerise.isSyneriseNotification(userInfo) if (isSyneriseNotification == true) { let isSyneriseSilentCommand: Bool = Synerise.isSyneriseSilentCommand(userInfo) if isSyneriseSilentCommand { <> } } else { <> } completionHandler(.alert) } } ```
```JavaScript Synerise.onReady(function() { onNotification: function(payload, actionIdentifier) { let isSyneriseNotification = Synerise.Notifications.isSyneriseNotification(payload); if (isSyneriseNotification == true) { let isSyneriseSilentCommand = Synerise.Notifications.isSilentCommand(payload); if (isSyneriseSilentCommand == true) { <> } else { <> } } } }); ```
## Payload ---
{
  "data": {
    <<campaign content>>
  }
}
{
  "aps": {
    "content-available": 1
  },
  <<campaign content>>
}
## SDK Commands --- ### SIGN_OUT {id=sdk-commands-sign-out}
{
  "data": {
    "issuer": "Synerise",
    "message-type": "dynamic-content",
    "content-type": "silent-sdk-command",
    "content": {
      "class_name": "com.synerise.sdk.injector.Injector",
      "method_name": "SIGN_OUT",
      "method_parameters": []
    }
  }
}
{
  "aps": {
    "content-available": 1
  },
  "issuer": "Synerise",
  "message-type": "dynamic-content",
  "content-type": "silent-sdk-command",
  "content": {
    "class_name": "com.synerise.sdk.injector.Injector",
    "method_name": "SIGN_OUT",
    "method_parameters": []
  }
}
### GET_LOCATION {id=sdk-commands-get-location}
{
  "data": {
    "issuer": "Synerise",
    "message-type": "dynamic-content",
    "content-type": "silent-sdk-command",
    "content": {
      "class_name": "com.synerise.sdk.injector.Injector",
      "method_name": "GET_LOCATION",
      "method_parameters": []
    }
  }
}
{
  "aps": {
    "content-available": 1
  },
  "issuer": "Synerise",
  "message-type": "dynamic-content",
  "content-type": "silent-sdk-command",
  "content": {
    "class_name": "com.synerise.sdk.injector.Injector",
    "method_name": "GET_LOCATION",
    "method_parameters": []
  }
}
# Settings This article describes options that allow you to change some SDK behaviors. It contains all settings you can configure to change some SDK behaviors. The settings are divided into groups: - [General](/developers/mobile-sdk/settings#general) - This group contains options related to the general functioning of mobile SDK. - [Notifications](/developers/mobile-sdk/settings#notifications) - This group contains options related to push notifications. - [In-app messaging](/developers/mobile-sdk/settings#in-app-messaging) - This group contains options related to the [in-app messages](/docs/campaign/in-app-messages) feature. - [Tracker](/developers/mobile-sdk/settings#tracker) - This group contains options related to tracking the customer activities in a mobile application. - [Injector](/developers/mobile-sdk/settings#injector) - This group contains options related to displaying [campaigns](/docs/campaign/Mobile). ## Pre-initialization settings Some of the pre-initialization settings are optional. If you want to use them, they must be configured before Synerise SDK is initialized, before invoking the following methods: - Synerise.Builder.build() (Android) - [Synerise.initialize(apiKey:)](/developers/mobile-sdk/method-reference/ios/lifecycle#initialization) (iOS) **Pre-initialization settings:** - [Set up App Group Identifier](#set-up-app-group-identifier) (iOS only) - [Set up Keychain Group Identifier](#set-up-keychain-group-identifier) (iOS only) - [Maintaining customer session on different API keys](#maintaining-customer-session-on-different-api-keys) - [Turn on/turn off notification encryption](#turn-onturn-off-notification-encryption) **The rest of the options can be changed dynamically anytime.**
See advanced initialization example with all settings options for: - [Advanced initialization - Android](/developers/mobile-sdk/installation-and-configuration/android#initialization) - [Advanced initialization - iOS](/developers/mobile-sdk/installation-and-configuration/ios#advanced-initialization) - [Advanced initialization - React Native](/developers/mobile-sdk/installation-and-configuration/react-native#advanced-initialization)
## General ### Enable/disable SDK --- This parameter specifies if the SDK is enabled. If the SDK is disabled, it means: - the SDK does not send any events - the SDK does not handle notifications - the SDK does not show in-app messages Available on: **Android**, **iOS**, **React Native**, **Flutter**.
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.sdk.enabled` | `Boolean` | true |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.sdk.enabled` | `Bool` | true |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.Settings.sdk.enabled`| `boolean` | true |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.sdk.enabled`| `bool` | true |
### Minimum time interval to refresh token --- This parameter sets a time interval (in seconds) counting backwards from the expiration time. Within this time, the authorization token will be automatically refreshed by the SDK. Available on: **Android**, **iOS**, **React Native**, **Flutter**.
| Method | Type | Default | Minimum | | --- | --- | --- | --- | | `Synerise.settings.sdk.setMinTokenRefreshInterval(value)` | `TimeInterval` | 1800 | 1800 |
| Parameter | Type | Default | Minimum | | --- | --- | --- | --- | | `Synerise.settings.sdk.minTokenRefreshInterval` | `TimeInterval` | 1800 | 1800 |
| Parameter | Type | Default | Minimum | | --- | --- | --- | --- | | `Synerise.Settings.sdk.minTokenRefreshInterval` | `number` | 1800 | 1800 |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.sdk.minTokenRefreshInterval`| `double` | 1800 |
### Maintaining customer session on different API keys --- This parameter specifies if a session is destroyed after the Profile API (formerly Client) key changes.
This option must be configured when Synerise SDK is initialized.
Available on: **Android**, **iOS**, **React Native**, **Flutter**.
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.sdk.shouldDestroySessionOnApiKeyChange` | `Boolean` | true |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.sdk.shouldDestroySessionOnApiKeyChange` | `Bool` | true |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.Settings.sdk.shouldDestroySessionOnApiKeyChange` | `boolean` | true |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.sdk.shouldDestroySessionOnApiKeyChange`| `bool` | true |
This option works only if you change the Profile (formerly Client) API key within one workspace. To change the API key from a different workspace, use the following method: - for Android [Client.changeApiKey](/developers/mobile-sdk/method-reference/android/lifecycle#change-profile-api-key-dynamically) - for iOS [Synerise.changeApiKey](/developers/mobile-sdk/method-reference/ios/lifecycle#change-profile-api-key-dynamically) - for React Native [Synerise.changeApiKey](/developers/mobile-sdk/method-reference/react-native/lifecycle#change-profile-api-key-dynamically) - for Flutter [Synerise.changeApiKey](/developers/mobile-sdk/method-reference/flutter/lifecycle#change-profile-api-key-dynamically)
### Set up App Group Identifier --- This parameter identifies the user default group applications and extensions belong to.
This option must be configured when Synerise SDK is initialized, before invoking the [Synerise.initialize(apiKey:)](/developers/mobile-sdk/method-reference/ios/lifecycle#initialization) method.
Available on: **iOS**, **React Native (iOS)**, **Flutter (iOS)**.
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.sdk.appGroupIdentifier` | `String` | nil |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.Settings.sdk.appGroupIdentifier` | `string` | null |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.sdk.appGroupIdentifier`| `String` | null |
Synerise SDK requires this parameter to be configured for storing your non-sensitive data and sharing it between your app and extensions. Your App Group must be registered on the [Apple Developer](https://developer.apple.com/) portal. It is recommended to use reverse-domain name style and prefix it with `group.` by default. For example, your App Group can be `group.com.synerise.sdk.sample`. When your App Group is registered, add it as a capability on the [Apple Developer](https://developer.apple.com/) portal in App ID Configuration and in Xcode in the **Signing&Capabilities** tab. Documentation is available at [Apple Developer - App Groups](https://developer.apple.com/documentation/bundleresources/entitlements/com_apple_security_application-groups). Once configured, you need to set it up in the SDK: #### Example
```Swift Synerise.settings.sdk.appGroupIdentifier = "group.com.synerise.sdk.sample" ```
```Objective-C SNRSynerise.settings.sdk.appGroupIdentifier = @"group.com.synerise.sdk.sample"; ```
```JavaScript Synerise.Settings.sdk.appGroupIdentifier = "group.com.synerise.sdk.sample"; ```
```Dart Synerise.settings.sdk.appGroupIdentifier = "group.com.synerise.sdk.sample"; ```
### Set up Keychain Group Identifier --- This parameter identifies the keychain group used by applications, extensions and services that your app belongs to.
This option must be configured when Synerise SDK is initialized, before invoking the [Synerise.initialize(apiKey:)](/developers/mobile-sdk/method-reference/ios/lifecycle#initialization) method.
Available on: **iOS**, **React Native (iOS)**, **Flutter (iOS)**.
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.sdk.keychainGroupIdentifier` | `String` | nil |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.Settings.sdk.keychainGroupIdentifier` | `string` | null |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.sdk.keychainGroupIdentifier`| `String` | null |
Synerise SDK requires that parameter to be configured for storing your data safely and sharing it between your app and extensions. Your Keychain Group Identifier is made of: - your Keychain Group - your $(AppIdentifierPrefix), also called Team ID. For example, if your Keychain Group is set to `SharedItems` and your Team ID is `ABC1234DEF`, the complete literal that you should set as Keychain Group Identifier is `ABC1234DEF.SharedItems`. Documentation is available at [Apple Developer - Sharing Access to Keychain Items Among a Collection of Apps](https://developer.apple.com/documentation/security/keychain_services/keychain_items/sharing_access_to_keychain_items_among_a_collection_of_apps). Once configured, you need to set it up in the SDK: #### Example
```Swift Synerise.settings.sdk.keychainGroupIdentifier = "ABC1234DEF.SharedItems" ```
```Objective-C SNRSynerise.settings.sdk.keychainGroupIdentifier = @"ABC1234DEF.SharedItems"; ```
```JavaScript Synerise.Settings.sdk.keychainGroupIdentifier = "ABC1234DEF.SharedItems"; ```
```Dart Synerise.settings.sdk.keychainGroupIdentifier = "ABC1234DEF.SharedItems"; ```
### Localize some strings occurring in the SDK --- This parameter specifies the localization of some strings occurring in the SDK. When this option isn't used, the SDK uses default strings. Available on: **iOS**, **React Native (iOS)**, **Flutter (iOS)**.
| Parameter | Type | Default | Min. SDK version | | --- | --- | --- | --- | | `Synerise.settings.sdk.localizable` | `[LocalizableStringKey: String]` | nil | 4.14.12 |
| Parameter | Type | Default | Min. SDK version | | --- | --- | --- | --- | | `Synerise.Settings.sdk.localizable` | `object` | null | 0.19.0 |
| Parameter | Type | Default | Min. SDK version | | --- | --- | --- | --- | | `Synerise.settings.sdk.localizable` | `Map` | null | 1.0.0 |
We recommend updating the property when you change the language in the Host App.
## Notifications ### Enable/disable notifications --- This parameter specifies if handling notifications by the SDK is enabled. Available on: **Android**, **iOS**, **React Native**, **Flutter**.
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.notifications.enabled` | `Boolean` | true |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.notifications.enabled` | `Bool` | true |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.Settings.notifications.enabled` | `boolean` | true |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.notifications.enabled` | `bool` | true |
### Turn on/turn off notification encryption --- This parameter specifies if encryption for push notifications is enabled.
This option must be configured when Synerise SDK is initialized.
Available on: **Android**, **iOS**, **React Native**, **Flutter**.
| Method | Type | Default | | --- | --- | --- | | `Synerise.settings.notifications.setEncryption(value)` | `Boolean` | false |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.notifications.encryption` | `Bool` | false |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.Settings.notifications.encryption` | `boolean` | false |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.notifications.encryption` | `bool` | false |
Encryption must be enabled in the [workspace settings](https://app.synerise.com/spa/modules/old-settings/setting/integration), in the Firebase integration section.
The application must be properly configured and implemented for notification encryption: - [Configure Notification Encryption for Android.](/developers/mobile-sdk/configuring-push-notifications/android#configure-notification-encryption) - [Configure Notification Encryption for iOS.](/developers/mobile-sdk/configuring-push-notifications/ios#configure-notification-encryption) - [Configure Notification Encryption for React Native.](/developers/mobile-sdk/configuring-push-notifications/react-native#configure-notification-encryption) - [Configure Notification Encryption for Flutter.](/developers/mobile-sdk/configuring-push-notifications/flutter#configure-notification-encryption)
### Enable/disable notification in-app alerts --- This parameter determines whether the SDK displays an additional alert in the application right after a notification is delivered. If you have your own notification implementation, or you do not want to display alerts with notification content, you should disable in-app notification alerts from the Synerise SDK. Also, read [here](/developers/mobile-sdk/campaigns/simple-push#additional-in-app-alert-when-simple-push-is-received). Available on: **iOS**, **React Native (iOS)**, **Flutter (iOS)**.
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.notifications.disableInAppAlerts` | `Bool` | false |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.Settings.notifications.disableInAppAlerts` | `boolean` | false |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.notifications.disableInAppAlerts` | `bool` | false |
## In-app messaging ### Check Global Control Groups when fetching definitions --- This parameter specifies if global control groups should be checked immediately after in-app definitions are fetched. Available on: **Android**, **iOS**, **React Native**, **Flutter**.
| Parameter | Type | Default | Min. SDK version | | --- | --- | --- | --- | | `Synerise.settings.inAppMessaging.checkGlobalControlGroupsOnDefinitionsFetch` | `Boolean` | false | 5.15.0 |
| Parameter | Type | Default | Min. SDK version | | --- | --- | --- | --- | | `Synerise.settings.inAppMessaging.checkGlobalControlGroupsOnDefinitionsFetch` | `Bool` | false | 4.15.0 |
| Parameter | Type | Default | Min. SDK version | | --- | --- | --- | --- | | `Synerise.Settings.notifications.checkGlobalControlGroupsOnDefinitionsFetch` | `boolean` | false | 0.19.0 |
| Parameter | Type | Default | Min. SDK version | | --- | --- | --- | --- | | `Synerise.settings.inAppMessaging.checkGlobalControlGroupsOnDefinitionsFetch` | `bool` | false | 0.8.3 |
### Maximum time interval between in-app definition updates --- This parameter sets the maximum interval (in seconds) between automatic [in-app message](/docs/campaign/in-app-messages) definition updates. Available on: **Android**, **iOS**, **React Native**, **Flutter**.
| Method | Type | Default | Minimum | Min. SDK version | | --- | --- | --- | --- | --- | | `Synerise.settings.inAppMessaging.setMaxDefinitionUpdateIntervalLimit(value)` | `TimeInterval` | 600.0 | 600.0 | 4.7.0 |
| Parameter | Type | Default | Minimum | Min. SDK version | | --- | --- | --- | --- | --- | | `Synerise.settings.inAppMessaging.maxDefinitionUpdateIntervalLimit` | `TimeInterval` | 600.0 | 600.0 | 4.6.0 |
| Parameter | Type | Default | Minimum | Min. SDK version | | --- | --- | --- | --- | --- | | `Synerise.Settings.inAppMessaging.maxDefinitionUpdateIntervalLimit` | `number` | 600.0 | 600.0 | 0.12.0 |
| Parameter | Type | Default | Minimum | Min. SDK version | | --- | --- | --- | --- | --- | | `Synerise.settings.inAppMessaging.maxDefinitionUpdateIntervalLimit` | `double` | 600.0 | 600.0 | 0.4.0 |
### Content base URL for in-app message --- This parameter defines the base URL for loading external resources (such as JavaScript files, CSS stylesheets, images, or fonts) within your in-app content. This is particularly useful when resources are hosted on your own server and you have set up **CORS (Cross-Origin Resource Sharing) policies**.
Thanks to the base URL, the app will know where to look for all external resources that are loaded dynamically. This helps avoid specifying full URLs each time a resource is requested and ensures that resources are consistently loaded from the correct location.
Available on: **Android**, **iOS**, **React Native**, **Flutter**.
| Parameter | Type | Default | Min. SDK version | | --- | --- | --- | --- | | `Synerise.settings.inAppMessaging.contentBaseUrl` | `String` | null | 5.21.0 |
| Parameter | Type | Default | Min. SDK version | | --- | --- | --- | --- | | `Synerise.settings.inAppMessaging.contentBaseUrl` | `String` | nil | 4.21.0 |
| Parameter | Type | Default | Min. SDK version | | --- | --- | --- | --- | | `Synerise.Settings.inAppMessaging.contentBaseUrl` | `string` | null | 0.24.0 |
| Parameter | Type | Default | Min. SDK version | | --- | --- | --- | --- | | `Synerise.settings.inAppMessaging.contentBaseUrl` | `String` | null | 1.4.0 |
#### Example You should set `contentBaseUrl` to the root URL of the server hosting your resources. This is especially important when hosting assets such as fonts, images, or scripts from a specific domain or server.
```Swift Synerise.settings.inAppMessaging.contentBaseUrl = "https://www.synerise.com" ```
```Objective-C SNRSynerise.settings.inAppMessaging.contentBaseUrl = @"https://www.synerise.com"; ```
```JavaScript Synerise.Settings.inAppMessaging.contentBaseUrl = "https://www.synerise.com" ```
```Dart Synerise.settings.inAppMessaging.contentBaseUrl = "https://www.synerise.com" ```
### Maximum time for in-app message rendering --- This parameter sets a timeout (in seconds) for in-app message rendering. Available on: **Android**, **iOS**, **React Native**, **Flutter**.
| Parameter | Type | Default | Minimum | Min. SDK version | | --- | --- | --- | --- | --- | | `Synerise.settings.inAppMessaging.renderingTimeout` | `TimeInterval` | 2.0 | - | 4.7.0 |
| Parameter | Type | Default | Minimum | Min. SDK version | | --- | --- | --- | --- | --- | | `Synerise.settings.inAppMessaging.renderingTimeout` | `TimeInterval` | 5.0 | 1.0 | 4.6.0 |
| Parameter | Type | Default | Minimum | Min. SDK version | | --- | --- | --- | --- | --- | | `Synerise.Settings.inAppMessaging.renderingTimeout` | `number` | 2.0 (Android)
5.0 (iOS) | - (Android)
1.0 (iOS) | 0.12.0 |
| Parameter | Type | Default | Minimum | Min. SDK version | | --- | --- | --- | --- | --- | | `Synerise.settings.inAppMessaging.renderingTimeout` | `double` | 2.0 (Android)
5.0 (iOS) | - (Android)
1.0 (iOS) | 0.4.0 |
### Enable/disable sending inApp.capping event --- This parameter specifies if the SDK should send the `inApp.capping` event. Available on: **Android**, **iOS**, **React Native**, **Flutter**.
| Parameter | Type | Default | Min. SDK version | | --- | --- | --- | --- | | `Synerise.settings.inAppMessaging.shouldSendInAppCappingEvent` | `Boolean` | true | 5.10.1 |
| Parameter | Type | Default | Min. SDK version | | --- | --- | --- | --- | | `Synerise.settings.inAppMessaging.shouldSendInAppCappingEvent` | `Bool` | true | 4.14.8 |
| Parameter | Type | Default | Min. SDK version | | --- | --- | --- | --- | | `Synerise.Settings.inAppMessaging.shouldSendInAppCappingEvent` | `boolean` | true | 0.16.0 |
| Parameter | Type | Default | Min. SDK version | | --- | --- | --- | --- | | `Synerise.settings.inAppMessaging.shouldSendInAppCappingEvent` | `bool` | true | 0.7.2 |
## Tracker ### Enable/disable declarative tracking --- This parameter specifies if the [declarative tracking](/developers/mobile-sdk/event-tracking#declarative-tracking) feature is enabled. Available on: **Android**, **iOS**.
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.tracker.tracking.enabled` | `Boolean` | true |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.tracker.tracking.enabled` | `Bool` | true |
### Enable/disable auto-tracking ---
Autotracking is **NOT** available when building apps with Jetpack Compose (Android) and SwiftUI (iOS).
This parameter specifies if the [auto-tracking feature](/developers/mobile-sdk/event-tracking#auto-tracking) is enabled. Available on: **Android**, **iOS**.
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.tracker.autoTracking.enabled` | `Boolean` | true |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.tracker.autoTracking.enabled` | `Bool` | true |
### Require/do not require backend time synchronization to send events --- This parameter specifies if events are sent when the server time synchronization has failed. Available on: **Android**, **iOS**, **React Native**, **Flutter**.
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.tracker.isBackendTimeSyncRequired` | `Boolean` | true |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.tracker.isBackendTimeSyncRequired` | `Bool` | true |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.Settings.tracker.isBackendTimeSyncRequired` | `Bool` | true |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.tracker.isBackendTimeSyncRequired` | `bool` | true |
### Minimum number of events in queue --- This parameter sets the minimum number of events in queue required to send the queue. Available on: **Android**, **iOS**, **React Native**, **Flutter**.
| Method | Type | Default | Minimum | Maximum | | --- | --- | --- | --- | --- | | `Synerise.settings.tracker.setMinimumBatchSize(value)` | `Integer` | 10 | 1 | 100 |
| Parameter | Type | Default | Minimum | Maximum | | --- | --- | --- | --- | --- | | `Synerise.settings.tracker.minBatchSize` | `Int` | 10 | 1 | 100 |
| Parameter | Type | Default | Minimum | Maximum | | --- | --- | --- | --- | --- | | `Synerise.Settings.tracker.minBatchSize` | `number` | 10 | 1 | 100 |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.tracker.minBatchSize` | `int` | 10 | 1 | 100 |
If the [timer](/developers/mobile-sdk/settings#timeout-to-send-events-automatically) runs out, events are sent even if the queue is smaller than defined in **minBatchSize**.
### Maximum number of events in queue --- This parameter sets the maximum number of events which may be sent in a single batch. Available on: **Android**, **iOS**, **React Native**, **Flutter**.
| Method | Type | Default | Minimum | Maximum | | --- | --- | --- | --- | --- | | `Synerise.settings.tracker.setMaximumBatchSize(value)` | `Integer` | 100 | 1 | 100 |
| Parameter | Type | Default | Minimum | Maximum | | --- | --- | --- | --- | --- | | `Synerise.Settings.tracker.maxBatchSize` | `number` | 100 | 1 | 100 |
| Parameter | Type | Default | Minimum | Maximum | | --- | --- | --- | --- | --- | | `Synerise.Settings.tracker.maxBatchSize` | `number` | 100 | 1 | 100 |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.tracker.maxBatchSize` | `int` | 100 | 1 | 100 |
### Timeout to send events automatically --- This parameter sets the time (in milliseconds for Android, in seconds for other SDKs) required before an attempt is made to send the queue. Available on: **Android**, **iOS**, **React Native**, **Flutter**.
| Method | Type | Default | Minimum | Maximum | | --- | --- | --- | --- | --- | | `Synerise.settings.tracker.setAutoFlushTimeout(value)` | `TimeInterval` | 5000 | 50 | - |
| Parameter | Type | Default | Minimum | Maximum | | --- | --- | --- | --- | --- | | `Synerise.settings.tracker.autoFlushTimeout` | `TimeInterval` | 5.0 | 0.5 | - |
| Parameter | Type | Default | Minimum | Maximum | | --- | --- | --- | --- | --- | | `Synerise.Settings.tracker.autoFlushTimeout` | `number` | 5.0 | 0.5 | - |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.tracker.autoFlushTimeout` | `double` | 5.0 | 0.5 | - |
If the [minimum queue size](/developers/mobile-sdk/settings#minimum-number-of-events-in-queue) is met, events are sent even if the timer has not run out.
### Events triggering flush mechanism --- This parameter sets an array of event 'action' values which trigger the flush mechanism. The list can be modified or cleared - including removing the default values. Available on: **Android** (5.17.0 or newer), **iOS** (4.17.0 or newer).
| Parameter | Type | Default | Min. SDK version | | --- | --- | --- | --- | | `Synerise.settings.tracker.eventsTriggeringFlush` | `List` | ["push.click", "push.view", "push.notView", "push.button.click", "push.dismiss"] | 5.17.0 |
In iOS, `push.view` events are handled by the Notification Service Extension and always sent immediately, regardless of this setting.
| Parameter | Type | Default | Min. SDK version | | --- | --- | --- | --- | | `Synerise.settings.tracker.eventsTriggeringFlush` | `[String]` | ["push.openInApp", "push.click", "push.button.click", "push.dismiss"] | 4.17.0 |
### Automatic location event sending --- This parameter specifies if location events are sent automatically. Available on: **Android**, **iOS**.
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.tracker.locationAutomatic` | `Boolean` | false |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.tracker.locationAutomatic` | `Bool` | false |
### Auto-tracking mode --- This parameter parameter defines the [auto-tracking](/developers/mobile-sdk/event-tracking#auto-tracking-configuration) mode. Available on: **Android**, **iOS**.
- `PLAIN` - listeners are set to track screen visits only. - `FINE` - listeners are attached to nearly everything that is clickable in your app, including screen visits. | Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.tracker.autoTracking.trackMode` | TrackMode | FINE |
- `.disabled` - listeners are disabled (default). - `.plain` - listeners are set to on-click only. - `.fine` - listeners are attached to nearly everything in your app (even to activities and `viewDidAppear`, the method that records [**VisitedScreen**](/developers/mobile-sdk/class-reference/ios/events#visitedscreenevent) events). | Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.tracker.autoTracking.mode` | `TrackerAutoTrackMode` | .disabled |
### Classes excluded from auto-tracking --- This parameter excludes classes from auto-tracking. Available on: **Android**, **iOS**.
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.tracker.autoTracking.excludedClasses` | `List` | [] |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.tracker.autoTracking.excludedClasses` | `[AnyClass]` | [] |
### View Tags excluded from auto-tracking --- This parameter excludes view tags from [auto-tracking](/developers/mobile-sdk/event-tracking#auto-tracking-configuration). Available on: **iOS**.
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.tracker.autoTracking.excludedViewTags` | `[Int]` | [] |
## Injector ### Enable/disable automatic starting of mobile campaigns (deprecated) --- This parameter specifies if walkthrough is processed automatically or not. - **DEPRECATED** Available on: **Android**, **iOS**, **React Native**, **Flutter**.
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.injector.automatic` | `Boolean` | false |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.injector.automatic` | `Bool` | false |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.Settings.injector.automatic` | `boolean` | false |
| Parameter | Type | Default | | --- | --- | --- | | `Synerise.settings.injector.automatic` | `bool` | false |
# React Native ## React Native listeners #### Initialization {id=initialization} A listener to handle the SDK lifecycle events.
```JavaScript Synerise.onReady(function() { ... }); Synerise.onError(function(error) { ... }) ```
--- --- #### NotificationsListener {id=notifications-listener} A listener to handle actions from the notifications module.
```JavaScript Synerise.Notifications.setListener({ // The following method is called when Synerise receives a registration token from the native part of application // It is optional function onRegistrationToken: function(token) { ... }, // The following method is called when registration for Push Notifications is needed. // It is optional function onNotification: function(payload) { ... }, // The following method is called when Synerise receives a notification's payload from the native part of application. // It is optional function onRegistrationRequired: function() { ... } }); ```
After invoking **onRegistrationRequired()** function, you must invoke the [Synerise.Notifications.registerForNotifications(registrationToken, mobileAgreement, onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/campaigns#register-for-push-notifications) method again.
--- --- #### ClientStateListener {id=client-state-listener} A listener to handle customer's sign-in state changes.
```JavaScript Synerise.Client.setClientStateListener({ // The following method is called when a customer signs in. // It is optional function onClientSignedIn: function() { ... }, // The following method is called when a customer signs out // It is optional function onClientSignedOut: function(reason) { ... } }); ```
--- --- #### InjectorListener {id=injector-listener} A listener to handle URL and deeplink actions from the injector module.
```JavaScript Synerise.Injector.setListener({ // The following method is called when Synerise handles URL action from campaign activities // It is required function onOpenUrl: function(url) { ... }, // The following method is called when Synerise handles deep link action from campaign activities // It is required function onDeepLink: function(deepLink) { ... } }); ```
--- --- #### InjectorInAppMessageListener {id=injector-in-app-message-listener} A listener to handle the states of [in-app messages](/developers/mobile-sdk/campaigns/in-app-message).
```JavaScript Synerise.Injector.setInAppMessageListener({ shouldPresent: function(data) { return true; }, // The following method is called after an in-app message appears onPresent: function (data) { ... }, // The following method is called after an in-app message disappears onHide: function(data) { ... }, // This method is called when a individual context for an in-app message is needed contextIsNeeded: function(data) { return {} }, // This method is called when the SRInApp.openUrl(url) method is used in an in-app message. onOpenUrl: function (data, url) { ... }, // This method is called when the SRInApp.openDeeplink(url) method is used in an in-app message. onDeepLink: function (data, deepLink) { ... }, // This method is called when the // SRInApp.handleCustomAction(name, params) method is used in an in-app message. onCustomAction: function(data, name, parameters) { } }) ```
--- --- ### InjectorWalkthroughListener {id=injector-walkthrough-listener}
**InjectorWalkthroughListener** was removed in SDK version 1.0.0..
--- --- ### InjectorBannerListener {id=injector-banner-listener}
**InjectorBannerListener** was removed in SDK version 1.0.0..
# React Native ## Method reference - React Native # Customer account management --- ## Get customer account information --- This method gets a customer’s account information. This method requires customer authentication.
The API key must have the `API_PERSONAL_INFORMATION_CLIENT_READ` permission from the **Client** group.
**Declared In:** lib/main/modules/ClientModule.js **Related To:** [ClientAccountInformation](/developers/mobile-sdk/class-reference/react-native/client#clientaccountinformation) **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public getAccount(onSuccess: (clientAccountInformation: ClientAccountInformation) => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Client.getAccount(function(clientAccountInformation) { //success }, function(error) { //failure }); ```
## Update customer account basic information --- This method updates a customer’s account’s basic information (without identification data: uuid, customId, email). This method requires the context object with the customer’s account information. Omitted fields are not modified. This method does not require customer authentication and can be used by anonymous profiles. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.22.0 | 5.21.0 | 0.24.0 | 1.4.0 |
The API key must have the `API_BASIC_INFORMATION_CLIENT_UPDATE` permission from the **Client** group.
**Declared In:** lib/main/modules/ClientModule.js **Related To:** [ClientAccountBasicInformationUpdateContext](/developers/mobile-sdk/class-reference/react-native/client#clientaccountupdatebasicinformationcontext) **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public updateAccountBasicInformation(context: ClientAccountBasicInformationUpdateContext, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **context** | [ClientAccountBasicInformationUpdateContext](/developers/mobile-sdk/class-reference/react-native/client#clientaccountupdatebasicinformationcontext) | yes | - | Object with customer’s first name, phone, and other optional data | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript let context = new ClientAccountBasicInformationUpdateContext(); context.firstName = 'John'; context.lastName = 'Rise'; context.displayName = 'John Rise'; context.sex = ClientSex.Male; context.phone = '123456789'; context.birthDate = '1989-08-03'; context.company = 'Synerise'; context.address = 'Marszałkowska'; context.city = 'Warszawa'; context.province = 'Mazowieckie'; context.zipCode = '00-000'; context.countryCode = '+48'; context.agreements = new ClientAgreements({ email: true, sms: true, push: true, bluetooth: true, rfid: true, wifi: true }); context.attributes = { ATTRIBUTE_1: 'ATTRIBUTE_1' } Synerise.Client.updateAccountBasicInformation(context, function() { // success }, function(error) { // failure }) ```
## Update customer account information --- This method updates a customer’s account information. This method requires the context object with the customer’s account information. Omitted fields are not modified. This method requires customer authentication.
The API key must have the `API_PERSONAL_INFORMATION_CLIENT_UPDATE` permission from the **Client** group.
**Declared In:** lib/main/modules/ClientModule.js **Related To:** [ClientAccountUpdateContext](/developers/mobile-sdk/class-reference/react-native/client#clientaccountupdatecontext) **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public updateAccount(context: ClientAccountUpdateContext, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **context** | [ClientAccountUpdateContext](/developers/mobile-sdk/class-reference/react-native/client#clientaccountupdatecontext) | yes | - | Object with customer's email, password, and other optional data | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript let context = new ClientAccountUpdateContext(); context.email = 'hello@synerise.com'; context.phone = '123456789'; context.customId = '000111'; context.firstName = 'John'; context.lastName = 'Rise'; context.displayName = 'John Rise'; context.sex = ClientSex.Male; context.birthDate = '1989-08-03'; context.company = 'Synerise'; context.address = 'Marszałkowska'; context.city = 'Warszawa'; context.province = 'Mazowieckie'; context.zipCode = '00-000'; context.countryCode = '+48'; context.agreements = new ClientAgreements({ email: true, sms: true, push: true, bluetooth: true, rfid: true, wifi: true }); context.attributes = { ATTRIBUTE_1: 'ATTRIBUTE_1' } Synerise.Client.updateAccount(context, function() { // success }, function(error) { // failure }) ```
## Change customer's account password --- This method changes a customer’s password. This method requires customer authentication.
Returns the HTTP 403 status code if the provided old password is invalid.
The API key must have the `SAUTH_CHANGE_PASSWORD_CLIENT_UPDATE` permission from the **Client** group.
**Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public changePassword(oldPassword: string, newPassword: string, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **newPassword** | string | yes | - | Customer's new password | | **oldPassword** | string | yes | - | Customer's old password | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript let newPassword = "NEW_PASSWORD"; let oldPassword = "OLD_PASSWORD"; Synerise.Client.changePassword(newPassword, oldPassword, function() { // success }, function(error) { // failure }); ```
## Request password reset for customer account --- This method requests a customer’s password reset with email. The customer will receive a token to the provided email address. That token is then used for the confirmation of password reset. This method requires the customer’s email. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_PASSWORD_RESET_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public requestPasswordReset(email: string, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | string | yes | - | Customer's email | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Client.requestPasswordReset("EMAIL", function() { // success }, function(error) { // failure }); ```
## Confirm password reset for customer account --- This method confirm a customer’s password reset with the new password and token provided by password reset request. This method requires the customer’s new password and the confirmation token received by e-mail. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_PASSWORD_RESET_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public confirmPasswordReset(password: string, token: string, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **password** | string | yes | - | Customer's new password | | **token** | string | yes | - | Customer's token provided in an email | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Client.confirmPasswordReset("PASSWORD", "TOKEN", function() { // success }, function(error) { // failure }); ```
## Request email change for customer account --- This method requests a customer's email change. This method is a global operation and doesn't require customer authentication.
Returns the HTTP 403 status code if the provided token or the password is invalid.
The API key must have the `SAUTH_CHANGE_EMAIL_CLIENT_UPDATE` permission from the **Client** group.
**Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public requestEmailChange(email: string, password: string | null, externalToken: string | null, authID: string | null, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | string | yes | - | Customer's new email | | **password** | string | yes | - | Customer's password | | **externalToken** | AnyObject | no | - | Customer's token (if OAuth, Facebook, and so on) | | **authID** | String | no | - | Optional identifier of authorization | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Client.requestEmailChange("EMAIL", "PASSWORD", function() { // success }, function(error) { // failure }); ```
## Confirm email change for customer account --- This method confirms an email change. This method is a global operation and doesn't require customer authentication.
Returns the HTTP 403 status code if the provided token is invalid.
The API key must have the `SAUTH_CHANGE_EMAIL_CLIENT_UPDATE` permission from the **Client** group.
**Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public confirmEmailChange(token: string, newsletterAgreement: Boolean, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **token** | string | yes | - | Customer's token provided in an email | | **newsletterAgreement** | boolean | yes | - | Agreement for sending newsletters to the provided email | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Client.confirmEmailChange("TOKEN", true, function() { // success }, function(error) { // failure }); ```
## Request phone update on customer account --- This method requests a customer's phone update. A confirmation code is sent to the phone number. This method is a global operation and doesn't require customer authentication.
The API key must have the `API_PERSONAL_PHONE_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public requestPhoneUpdate(phone: string, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **phone** | string | yes | - | Customer's new phone number | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Client.requestPhoneUpdate("PHONE", function() { // success }, function(error) { // failure }); ```
## Confirm phone update on customer account --- This method confirms a phone number update. This action requires the new phone number and confirmation code as parameters. This method is a global operation and doesn't require customer authentication.
Returns the HTTP 403 status code if the provided UUID does not exist or the password is invalid.
The API key must have the `API_PERSONAL_PHONE_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public confirmPhoneUpdate(phone: string, confirmationCode: string, smsAgreement: Boolean, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **phone** | string | yes | - | New phone number | | **confirmationCode** | string | yes | - | A confirmation code received by a text message | | **smsAgreement** | boolean | yes | - | Agreement for sending SMS to the provided number | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Client.confirmPhoneUpdate("PHONE", "CONFIRMATION_CODE", true, function() { // success }, function(error) { // failure }); ```
## Delete customer account by Identity Provider --- This method deletes a customer's account. This method requires customer authentication.
HTTP 403 status code is returned if the provided password or token is invalid.
The API key must have the `SAUTH_CLIENT_DELETE`, `SAUTH_OAUTH_CLIENT_DELETE`, `SAUTH_FACEBOOK_CLIENT_DELETE`, `SAUTH_APPLE_CLIENT_DELETE` permissions from the **Client** group.
**Declared In:** lib/main/modules/ClientModule.js **Related To:** [ClientIdentityProvider](/developers/mobile-sdk/class-reference/react-native/client#clientidentityprovider) **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public deleteAccountByIdentityProvider(clientAuthFactor: string, clientIdentityProvider: ClientIdentityProvider, authID: string | null, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **clientAuthFactor** | string | yes | - | Token retrieved from provider | | **clientIdentityProvider** | [ClientIdentityProvider](/developers/mobile-sdk/class-reference/react-native/client#clientidentityprovider) | yes | - | Provider of your token | | **authID** | string | no | null | Optional identifier of authorization | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. ## Deprecated methods ### Delete customer account --- This method deletes a customer's account. This method requires customer authentication. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.11 | 3.6.13 | 0.9.12 | n/a | | Deprecated in: | 3.6.19 | 3.6.19 | 0.14.0 | n/a | | Removed in: | 5.0.0 | 6.0.0 | n/a | n/a |
Returns the HTTP 403 status code is returned if the provided password is invalid.
The API key must have the `SAUTH_CLIENT_DELETE` permission from the **Client** group.
**Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public deleteAccount(password: string, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **password** | string | yes | - | Customer's password | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript let password = "PASSWORD"; Synerise.Client.deleteAccount(password, function(token) { // success }, function(error) { // failure }); ```
### Delete customer account by OAuth --- This method deletes a customer's account by OAuth. This method requires customer authentication. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.11 | 3.6.13 | 0.9.12 | n/a | | Deprecated in: | 3.6.19 | 3.6.19 | 0.14.0 | n/a | | Removed in: | 5.0.0 | 6.0.0 | n/a | n/a |
The API key must have the `SAUTH_CLIENT_DELETE` and `SAUTH_OAUTH_CLIENT_DELETE` permissions from the **Client** group.
**Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public deleteAccountByOAuth(accessToken: string, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **accessToken** | string | yes | - | OAuth Access Token | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Client.deleteAccountByOAuth(accessToken, function(token) { // success }, function(error) { // failure }); ```
### Delete customer account by Facebook --- This method deletes a customer's account by Facebook. This method requires customer authentication. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.3.8 | 3.3.0 | 0.9.12 | n/a | | Deprecated in: | 3.6.19 | 3.6.19 | 0.14.0 | n/a | | Removed in: | 5.0.0 | 6.0.0 | n/a | n/a |
The API key must have the `SAUTH_CLIENT_DELETE` and `SAUTH_FACEBOOK_CLIENT_DELETE` permissions from the **Client** group.
**Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public deleteAccountByFacebook(facebookToken: string, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **facebookToken** | string | yes | - | Facebook Access Token | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Client.deleteAccountByFacebook(facebookToken, function(token) { // success }, function(error) { // failure }); ```
# Events ### Event Main event abstract class for inheriting classes.
This is an abstract class and it is not meant to be instantiated directly. You should use concrete `RecommendationEvent` subclasses instead.
**Declared In:** lib/classes/events/Event.js **Declaration:**
abstract class Event
**Initializers:**
constructor(type: string, label: string, action: string | null, parameters: object)
--- --- ### CustomEvent
DO NOT send `transaction.charge` events as custom events.
Transactions must be tracked with these endpoints: - [`/v4/transactions`](https://hub.synerise.com/api-reference/data-management#operation/CreateATransaction) (single transaction) - [`/v4/transactions/batch`](https://hub.synerise.com/api-reference/data-management#operation/BatchAddOrUpdateTransactions) (multiple transactions)
Represents a custom client event. **Declared In:** lib/classes/events/other/CustomEvent.js **Inherits From:** [Event](/developers/mobile-sdk/class-reference/react-native/events#event) **Declaration:**
class CustomEvent extends Event
**Initializers:**
constructor(label: string, action: string, parameters?: Record<string, any>)
--- --- ### PushViewedEvent Represents a 'client viewed push' event. This event is used for push message interaction tracking. **Declared In:** lib/classes/events/push/ViewedPushEvent.js **Inherits From:** [Event](/developers/mobile-sdk/class-reference/react-native/events#event) **Declaration:**
class PushViewedEvent extends Event
**Initializers:**
constructor(label: string, parameters?: object)
--- --- ### PushClickedEvent Represents a 'client clicked push' event. This event is used for push message interaction tracking. **Declared In:** lib/classes/events/push/ClickedPushEvent.js **Inherits From:** [Event](/developers/mobile-sdk/class-reference/react-native/events#event) **Declaration:**
class PushClickedEvent extends Event
**Initializers:**
constructor(label: string, parameters?: object)
--- --- ### PushCancelledEvent Represents a 'client viewed push' event. This event is used for push message interaction tracking. **Declared In:** lib/classes/events/push/CancelledPushEvent.js **Inherits From:** [Event](/developers/mobile-sdk/class-reference/react-native/events#event) **Declaration:**
class PushCancelledEvent extends Event
**Initializers:**
constructor(label: string, parameters?: object)
--- --- ### CartEvent Main cart action abstract class for inheriting classes.
This is an abstract class and it is not meant to be instantiated directly. You should use concrete `CartEvent` subclasses instead.
**Declared In:** lib/classes/events/cart/CartEvent.js **Inherits From:** [Event](/developers/mobile-sdk/class-reference/react-native/events#event) **Declaration:**
class CartEvent extends Event
**Initializers:**
constructor(type: string, label: string, sku: string, finalPrice: UnitPrice, quantity: number, parameters?: object)
**Methods:** This method sets a value for the `name` parameter.
public setName(name: string)
--- This method sets a value for the `category` parameter.
public setCategory(category: string)
--- This method sets values for the `categories` parameter.
public setCategories(categories: string[])
--- This method sets a value for the `offline` parameter.
public setOffline(offline: boolean)
--- This method sets the value of the `regularPrice` parameter.
public setRegularPrice(regularPrice: UnitPrice)
--- This method sets the value of the `discountedPrice` parameter.
public setDiscountedPrice(discountedPrice: UnitPrice)
--- This method sets the value of the `url` parameter.
public setUrl(url: string)
--- This method sets the value of the `producer` parameter (producer can signify a brand of the item).
public setProducer(producer: string)
--- --- ### UnitPrice **Declared In:** lib/classes/events/cart/UnitPrice.js **Declaration:**
class UnitPrice
**Initializers:**
constructor(amount: number, currency: string)
--- --- ### ProductAddedToCartEvent Represents a 'client added product to cart' event. **Declared In:** lib/classes/events/product/ProductAddedToCartEvent.js **Inherits From:** [Event](/developers/mobile-sdk/class-reference/react-native/events#event) **Declaration:**
class ProductAddedToCartEvent extends CartEvent
**Initializers:**
constructor(label: string, sku: string, finalPrice: UnitPrice, quantity: number, parameters?: object)
--- --- ### ProductRemovedFromCartEvent Represents a 'client removed product from cart' event. **Declared In:** lib/classes/events/cart/RemovedFromCartEvent.js **Inherits From:** [Event](/developers/mobile-sdk/class-reference/react-native/events#event) **Declaration:**
class ProductRemovedFromCartEvent extends CartEvent
**Initializers:**
constructor(label: string, sku: string, finalPrice: UnitPrice, quantity: number, parameters?: object)
--- --- ### ProductViewedEvent Represents a 'client viewed product' event. **Declared In:** lib/classes/events/product/ProductViewEvent.js **Inherits From:** [Event](/developers/mobile-sdk/class-reference/react-native/events#event) **Declaration:**
class ProductViewedEvent extends Event
**Initializers:**
constructor(label: string, productId: string, name: string, parameters?: object)
**Methods:** This method sets a value for the `category` parameter.
public setCategory(category: string)
--- This method sets the value of the `url` parameter.
public setUrl(url: string)
--- --- ### ProductAddedToFavoritesEvent Represents a 'client added product to favorites' event. **Declared In:** lib/classes/events/product/ProductAddedToFavouritesEvent.js **Inherits From:** [Event](/developers/mobile-sdk/class-reference/react-native/events#event) **Declaration:**
class ProductAddedToFavouritesEvent extends Event
**Initializers:**
constructor(label: string, parameters?: object)
--- --- ### LoggedInEvent Represents a 'client logged in' event. **Declared In:** lib/classes/events/auth/LoggedInEvent.js **Inherits From:** [Event](/developers/mobile-sdk/class-reference/react-native/events#event) **Declaration:**
class LoggedInEvent extends Event
--- --- ### LoggedOutEvent Represents a 'client logged out' event. **Declared In:** lib/classes/events/auth/LoggedOutEvent.js **Inherits From:** [Event](/developers/mobile-sdk/class-reference/react-native/events#event) **Declaration:**
class LoggedOutEvent extends Event
--- --- ### RegisteredEvent Represents a 'client registered' event. **Declared In:** lib/classes/events/auth/RegisteredEvent.js **Inherits From:** [Event](/developers/mobile-sdk/class-reference/react-native/events#event) **Declaration:**
class RegisteredEvent extends Event
**Initializers:**
constructor(label: string, parameters?: object)
--- --- ## RecommendationEvent Main recommendation abstract class for inheriting classes.
This is an abstract class and it is not meant to be instantiated directly. You should use concrete `RecommendationEvent` subclasses instead.
**Declared In:** lib/classes/events/recommendation/RecommendationEvent.js **Inherits From:** [Event](/developers/mobile-sdk/class-reference/react-native/events#event) **Declaration:**
class RecommendationEvent extends Event
**Initializers:**
constructor(type: string, label: string, productId: string, name: string, campaignId: string, campaignHash: string, parameters?: object)
--- --- ### RecommendationSeenEvent Represents a 'client saw a recommendation' event. **Declared In:** lib/classes/events/recommendation/RecommendationSeenEvent.js **Inherits From:** [Event](/developers/mobile-sdk/class-reference/react-native/events#event) **Declaration:**
class RecommendationSeenEvent extends RecommendationEvent
**Initializers:**
constructor(label: string, productId: string, name: string, campaignId: string, campaignHash: string, parameters?: object)
--- --- ### RecommendationClickEvent Represents a 'client clicked a recommendation' event. **Declared In:** lib/classes/events/recommendation/RecommendationClickEvent.js **Inherits From:** [Event](/developers/mobile-sdk/class-reference/react-native/events#event) [RecommendationEvent](/developers/mobile-sdk/class-reference/react-native/events#recommendationevent) **Declaration:**
class RecommendationClickEvent extends RecommendationEvent
**Initializers:**
constructor(label: string, productId: string, name: string, campaignId: string, campaignHash: string, parameters?: object)
--- --- ### VisitedScreenEvent Represents a 'client visited screen' event. This can be used for mobile screen usage tracking. **Declared In:** lib/classes/events/other/VisitedScreenEvent.js **Inherits From:** [Event](/developers/mobile-sdk/class-reference/react-native/events#event) **Declaration:**
class VisitedScreenEvent extends Event
**Initializers:**
constructor(label: string, parameters?: object)
--- --- ### HitTimerEvent Represents a 'client hit timer' event. This could be used for profiling or activity time monitoring - you can send a `HitTimerEvent` when your client starts doing something and send it once again when they finish, but this time with the different time signature. Then you can use our analytics engine to measure, for example, average activity time. **Declared In:** lib/classes/events/other/HitTimerEvent.js **Inherits From:** [Event](/developers/mobile-sdk/class-reference/react-native/events#event) **Declaration:**
class HitTimerEvent extends Event
**Initializers:**
constructor(label: string, parameters?: object)
--- --- ### SearchedEvent Represents a 'client searched' event. **Declared In:** lib/classes/events/other/SearchedEvent.js **Inherits From:** [Event](/developers/mobile-sdk/class-reference/react-native/events#event) **Declaration:**
class SearchedEvent extends Event
**Initializers:**
constructor(label: string, parameters?: object)
--- --- ### SharedEvent Represents a 'client shared' event. **Declared In:** lib/classes/events/other/SharedEvent.js **Inherits From:** [Event](/developers/mobile-sdk/class-reference/react-native/events#event) **Declaration:**
class SharedEvent extends Event
**Initializers:**
constructor(label: string, parameters?: object)
--- --- ### AppearedInLocationEvent Represents a 'client appeared in location' event. **Declared In:** lib/classes/events/other/AppearedInLocationEvent.js **Inherits From:** [Event](/developers/mobile-sdk/class-reference/react-native/events#event) **Declaration:**
class AppearedInLocationEvent extends Event
**Initializers:**
constructor(label: string, lat: number, lon: number, parameters?: object)
# Customer account management ## Get customer account information --- This method gets a customer’s account information. This method requires customer authentication.
The API key must have the `API_PERSONAL_INFORMATION_CLIENT_READ` permission from the **Client** group.
**Declared In:** Headers/SNRClient.h **Related To:** [ClientAccountInformation](/developers/mobile-sdk/class-reference/ios/client#clientaccountinformation) **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func getAccount(success: ((ClientAccountInformation) -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)getAccountWithSuccess:(nonnull void (^)(SNRClientAccountInformation *accountInformation))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **success** | ((ClientAccountInformation) -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```Swift Client.getAccount(success: { (clientAccountInformation) in // success }) { (error) in // failure } ```
```Objective-C [SNRClient getAccountWithSuccess:^(SNRClientAccountInformation *accountInformation) { // success } failure:^(SNRApiError *error) { // failure }]; ```
## Get customer's events --- This method retrieves events for an authenticated customer. This method requires customer authentication. **Declared In:** Headers/SNRClient.h **Related To:** [ClientEventsApiQuery](/developers/mobile-sdk/class-reference/ios/client#clienteventsapiquery) **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func getEvents(apiQuery: ClientEventsApiQuery, success: (([ClientEventData]) -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)getEventsWithApiQuery:(nonnull SNRClientEventsApiQuery *)apiQuery success:(nonnull void (^)(NSArray *events))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **apiQuery** | [ClientEventsApiQuery](/developers/mobile-sdk/class-reference/ios/client#clienteventsapiquery) | yes | - | Object responsible for storing all query parameters | | **success** | (([ClientEventData]) -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error | **Return Value:** No value is returned. ## Update customer account basic information --- This method updates a customer’s account’s basic information (without identification data: uuid, customId, email). This method requires the context object with the customer’s account information. Omitted fields are not modified. This method does not require customer authentication and can be used by anonymous profiles. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.22.0 | 5.21.0 | 0.24.0 | 1.4.0 |
The API key must have the `API_BASIC_INFORMATION_CLIENT_UPDATE` permission from the **Client** group.
**Declared In:** Headers/SNRClient.h **Related To:** [ClientUpdateAccountBasicInformationContext](/developers/mobile-sdk/class-reference/ios/client#clientupdateaccountbasicinformationcontext) **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func updateAccountBasicInformation(context: ClientUpdateAccountBasicInformationContext, success: (() -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)updateAccountBasicInformation:(nonnull SNRClientUpdateAccountBasicInformationContext *)context success:(nonnull void (^)(void))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **context** | [ClientUpdateAccountBasicInformationContext](/developers/mobile-sdk/class-reference/ios/client#clientupdateaccountbasicinformationcontext) | yes | - | Object with customer's basic information optional data | | **success** | (() -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
Since version 5.0.0, the **success** closure does NOT contain the `isSuccess` parameter.
**Return Value:** No value is returned. ## Update customer account information --- This method updates a customer’s account information. This method requires the context object with the customer’s account information. Omitted fields are not modified. This method requires customer authentication.
The API key must have the `API_PERSONAL_INFORMATION_CLIENT_UPDATE` permission from the **Client** group.
**Declared In:** Headers/SNRClient.h **Related To:** [ClientUpdateAccountContext](/developers/mobile-sdk/class-reference/ios/client#clientupdateaccountcontext) **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func updateAccount(context: ClientUpdateAccountContext, success: (() -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)updateAccount:(nonnull SNRClientUpdateAccountContext *)context success:(nonnull void (^)(void))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **context** | [ClientUpdateAccountContext](/developers/mobile-sdk/class-reference/ios/client#clientupdateaccountcontext) | yes | - | Object with customer's email, password, and other optional data | | **success** | (() -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
Since version 5.0.0, the **success** closure does NOT contain the `isSuccess` parameter.
**Return Value:** No value is returned. **Example:**
```Swift let agreements: ClientAgreements = ClientAgreements() agreements.email = true agreements.sms = true agreements.push = true agreements.bluetooth = true agreements.rfid = true agreements.wifi = true let context: ClientUpdateAccountContext = ClientUpdateAccountContext() context.email = "hello@synerise.com" context.phone = "123-456-789" context.customId = "CUSTOM_ID" context.uuid = "UUID" context.firstName = "FIRST_NAME" context.lastName = "LAST_NAME" context.displayName = "DISPLAY_NAME" context.sex = .male context.company = "Synerise" context.address = "Lubostroń 1" context.city = "Kraków" context.province = "Małopolskie" context.zipCode = "30-383" context.countryCode = "+48" context.birthDate = "01-01-2019" context.avatarUrl = "http://www.synerise.com" context.agreements = agreements context.attributes = ["attribute1": "value1", "attribute2": "value2"] context.tags = ["tag1", "tag2" "tag3"] Client.updateAccount(context: context, success: { // success }) { (error) in // failure } ```
```Objective-C SNRClientAgreements *agreements = [SNRClientAgreements new]; agreements.email = true; agreements.sms = true; agreements.push = true; agreements.bluetooth = true; agreements.rfid = true; agreements.wifi = true; SNRClientUpdateAccountContext *context = [SNRClientUpdateAccountContext new]; context.email = @"hello@synerise.com" context.phone = @"123-456-789"; context.customId = @"CUSTOM_ID" context.firstName = @"FIRST_NAME"; context.lastName = @"LAST_NAME"; context.displayName = @"DISPLAY_NAME" context.sex = SNRClientSexMale; context.company = @"Synerise"; context.address = @"Lubostroń 1"; context.city = @"Kraków"; context.province = @"Małopolskie"; context.zipCode = @"30-383"; context.countryCode = @"+48"; context.birthDate = @"01-01-2019" context.avatarUrl = @"http://www.synerise.com" context.agreements = agreements; context.attributes = @{@"attribute": @"value"}; context.tags = @[@"tag1", @"tag2" @"tag3"]; [SNRClient updateAccount:context success:^() { // success } failure:^(NSError * _Nonnull error) { // failure }]; ```
## Change customer's account password --- This method changes a customer’s password. This method requires customer authentication.
Returns the HTTP 403 status code if the provided old password is invalid.
The API key must have the `SAUTH_CHANGE_PASSWORD_CLIENT_UPDATE` permission from the **Client** group.
**Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func changePassword(password: String, oldPassword: String, success: (() -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)changePassword:(nonnull NSString *)password oldPassword:(nonnull NSString *)oldPassword success:(nonnull void (^)(void))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **password** | String | yes | - | Customer's new password | | **oldPassword** | String | yes | - | Customer's old password | | **success** | (() -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
Since version 5.0.0, the **success** closure does NOT contain the `isSuccess` parameter.
**Return Value:** No value is returned. **Example:**
```Swift let newPassword: String = "NEW_PASSWORD" let oldPassword: String = "OLD_PASSWORD" Client.changePassword(password: newPassword, oldPassword: oldPassword, success: { // success }, failure: { (error) in // failure }) ```
```Objective-C NSString *newPassword = @"NEW_PASSWORD"; NSString *oldPassword = @"OLD_PASSWORD"; [SNRClient changePassword:newPassword oldPassword:oldPassword success:^() { // success } failure:^(SNRApiError *error) { // failure }]; ```
## Request password reset for customer account --- This method requests a customer’s password reset with email. The customer will receive a token to the provided email address. That token is then used for the confirmation of password reset. This method requires the customer’s email. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_PASSWORD_RESET_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** Headers/SNRClient.h **Related To:** [ClientPasswordResetRequestContext](/developers/mobile-sdk/class-reference/ios/client#clientpasswordresetrequestcontext) **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func requestPasswordReset(context: ClientPasswordResetRequestContext, success: (() -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)requestPasswordReset:(nonnull SNRClientPasswordResetRequestContext *)context success:(nonnull void (^)(void))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **context** | [ClientPasswordResetRequestContext](/developers/mobile-sdk/class-reference/ios/client#clientpasswordresetrequestcontext) | yes | - | Object with the customer's email | | **success** | (() -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
Since version 5.0.0, the **success** closure does NOT contain the `isSuccess` parameter.
**Return Value:** No value is returned. **Example:**
```Swift let email: String = "EMAIL" let context: ClientPasswordResetRequestContext = ClientPasswordResetRequestContext(email: email) Client.requestPasswordReset(context: context, success: { // success }, failure: { (error) in // failure }) ```
```Objective-C NSString *email = @"EMAIL"; SNRClientPasswordResetRequestContext *context = [SNRClientPasswordResetRequestContext alloc] initWithEmail:email]; [SNRClient requestPasswordReset:context success:^() { // success } failure:^(SNRApiError *error) { // failure }]; ```
## Confirm password reset for customer account --- This method confirm a customer’s password reset with the new password and token provided by password reset request. This method requires the customer’s new password and the confirmation token received by e-mail. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_PASSWORD_RESET_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** Headers/SNRClient.h **Related To:** [ClientPasswordResetConfirmationContext](/developers/mobile-sdk/class-reference/ios/client#clientpasswordresetconfirmationcontext) **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func confirmResetPassword(context: ClientPasswordResetConfirmationContext, success: (() -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)confirmResetPassword:(nonnull SNRClientPasswordResetConfirmationContext *)context success:(nonnull void (^)(void))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **context** | [ClientPasswordResetConfirmationContext](/developers/mobile-sdk/class-reference/ios/client#clientpasswordresetconfirmationcontext) | yes | - | Object with customer's password and token | | **success** | (() -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
Since version 5.0.0, the **success** closure does NOT contain the `isSuccess` parameter.
**Return Value:** No value is returned. **Example:**
```Swift let password: String = "PASSWORD" let token: String = "TOKEN" let context: ClientPasswordResetConfirmationContext = ClientPasswordResetConfirmationContext(password: password, token: token) Client.confirmResetPassword(context: context, success: { // success }, failure: { (error) in // failure }) ```
```Objective-C NSString *password = @"PASSWORD" NSString *token = @"TOKEN" SNRClientPasswordResetConfirmationContext *context = [[SNRClientPasswordResetConfirmationContext alloc] initWithPassword:password andToken:token]; [SNRClient confirmResetPassword:context success:^() { // success } failure:^(NSError * _Nonnull error) { // failure }]; ```
## Request email change for customer account --- This method requests a customer's email change. This method is a global operation and doesn't require customer authentication.
Returns the HTTP 403 status code if the provided token or the password is invalid.
The API key must have the `SAUTH_CHANGE_EMAIL_CLIENT_UPDATE` permission from the **Client** group.
**Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func requestEmailChange(email: String, password: String, externalToken: AnyObject?, authID: String?, success: (() -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)requestEmailChange:(nonnull NSString *)email password:(NSString *)password externalToken:(id)externalToken authID:(NSString *)authID success:(nonnull void (^)(void))success failure:(nonnull void (^)(SNRApiError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | String | yes | - | Customer's new email | | **password** | String | yes | - | Customer's password | | **externalToken** | AnyObject | no | - | Customer's token (if OAuth, Facebook, and so on) | | **authID** | String | no | - | Optional identifier of authorization | | **success** | (() -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
Since version 5.0.0, the **success** closure does NOT contain the `isSuccess` parameter.
**Return Value:** No value is returned. ## Confirm email change for customer account --- This method confirms an email change. This method is a global operation and doesn't require customer authentication.
Returns the HTTP 403 status code if the provided token is invalid.
The API key must have the `SAUTH_CHANGE_EMAIL_CLIENT_UPDATE` permission from the **Client** group.
**Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func confirmEmailChange(token: String, newsletterAgreement: Bool, success: (() -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)confirmEmailChange:(nonnull NSString *)token newsletterAgreement:(BOOL)newsletterAgreement success:(nonnull void (^)(void))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **token** | String | yes | - | Customer's token provided in an email | | **newsletterAgreement** | Bool | yes | - | Agreement for sending newsletters to the provided email | | **success** | (() -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
Since version 5.0.0, the **success** closure does NOT contain the `isSuccess` parameter.
**Return Value:** No value is returned. **Example:**
```Swift let token: String = "TOKEN" Client.confirmEmailChange(token: token, success: { // success }) { (error) in // failure } ```
```Objective-C NSString *token = @"TOKEN"; [SNRClient confirmEmailChange:token newsletterAgreement:YES success:^() { // success } failure:^(SNRApiError *error) { // failure }]; ```
## Request phone update on customer account --- This method requests a customer's phone update. A confirmation code is sent to the phone number. This method is a global operation and doesn't require customer authentication.
The API key must have the `API_PERSONAL_PHONE_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func requestPhoneUpdate(phone: String, success: (() -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)requestPhoneUpdate:(nonnull NSString *)phone success:(nonnull void (^)(void))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **phone** | String | yes | - | Customer's new phone number | | **success** | (() -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
Since version 5.0.0, the **success** closure does NOT contain the `isSuccess` parameter.
**Return Value:** No value is returned. **Example:**
```Swift let phone: String = "123-456-789" Client.requestPhoneUpdate(phone: phone, success: { // success }, failure: { (error) in // failure }) ```
```Objective-C NSString *phone = @"123-456-789"; [SNRClient requestPhoneUpdate:phone success:^() { // success } failure:^(SNRApiError *error) { // failure }]; ```
## Confirm phone update on customer account --- This method confirms a phone number update. This action requires the new phone number and confirmation code as parameters. This method is a global operation and doesn't require customer authentication.
Returns the HTTP 403 status code if the provided UUID does not exist or the password is invalid.
The API key must have the `API_PERSONAL_PHONE_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func confirmPhoneUpdate(phone: String, confirmationCode: String, smsAgreement: Bool, success: (() -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)confirmPhoneUpdate:(nonnull NSString *)phone confirmationCode:(nonnull NSString *)confirmationCode smsAgreement:(BOOL)smsAgreement success:(nonnull void (^)(void))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **phone** | String | yes | - | New phone number | | **confirmationCode** | String | yes | - | A confirmation code received by a text message | | **smsAgreement** | Bool | yes | - | Agreement for sending SMS to the provided number | | **success** | (() -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
Since version 5.0.0, the **success** closure does NOT contain the `isSuccess` parameter.
**Return Value:** No value is returned. **Example:**
```Swift let phone: String = "123-456-789" let confirmationCode: String = "CONFIRMATION_CODE" Client.confirmPhoneUpdate(phone: phone, confirmationCode: confirmationCode, smsAgreement: true, success: { // success }) { (error) in // failure } ```
```Objective-C NSString *phone = @"123-456-789"; NSString *confirmationCode = @"CONFIRMATION_CODE"; [SNRClient confirmPhoneUpdate:phone confirmationCode:confirmationCode smsAgreement:YES success:^() { // success } failure:^(SNRApiError *error) { // failure }]; ```
## Delete customer account by Identity Provider --- This method deletes a customer's account. This method requires customer authentication.
HTTP 403 status code is returned if the provided password or token is invalid.
The API key must have the `SAUTH_CLIENT_DELETE`, `SAUTH_OAUTH_CLIENT_DELETE`, `SAUTH_FACEBOOK_CLIENT_DELETE`, `SAUTH_APPLE_CLIENT_DELETE` permissions from the **Client** group.
**Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func deleteAccount(clientAuthFactor: String, clientIdentityProvider: ClientIdentityProvider, authID: String, success: (() -> Void), failure: ((ApiError) -> Void)) ```
```Objective-C + (void)deleteAccount:(nonnull id)clientAuthFactor clientIdentityProvider:(SNRClientIdentityProvider)clientIdentityProvider authID:(nullable NSString *)authID success:(nonnull void (^)(void))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **clientAuthFactor** | String | yes | - | Customer's token from the identity provider | | **clientIdentityProvider** | [ClientIdentityProvider](/developers/mobile-sdk/class-reference/ios/client#clientidentityprovider) | yes | - | Customer's identity provider | | **authID** | String | no | - | Optional identifier of authorization | | **success** | (() -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error |
Since version 5.0.0, the **success** closure does NOT contain the `isSuccess` parameter.
**Return Value:** No value is returned. ## Removed methods ### Request email change for customer account by Facebook {#request-email-change-for-customer-account-by-facebook} --- This method requests a customer's email change by Facebook. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_CHANGE_EMAIL_CLIENT_UPDATE` permission from the **Client** group.
**Replaced By:** [Request email change for customer account](/developers/mobile-sdk/method-reference/ios/client-account#request-email-change-for-customer-account) **Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func requestEmailChangeByFacebook(email: String, success: ((Bool) -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)requestEmailChangeByFacebook:(nonnull NSString *)email success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | String | yes | - | Customer's new email | | **success** | ((Bool) -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```Swift let email: String = "EMAIL" Client.requestEmailChange(email: email, success: { success in // success }) { (error) in // failure } ```
```Objective-C NSString *email = @"EMAIL"; [SNRClient requestEmailChangeByFacebook:email success:^(BOOL isSuccess) { // success } failure:^(SNRApiError *error) { // failure }]; ```
### Delete customer account {#delete-customer-account} --- This method deletes a customer's account. This method requires customer authentication. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.11 | 3.6.13 | 0.9.12 | n/a | | Deprecated in: | 3.6.19 | 3.6.19 | 0.14.0 | n/a | | Removed in: | 5.0.0 | 6.0.0 | n/a | n/a |
Returns the HTTP 403 status code is returned if the provided password is invalid.
The API key must have the `SAUTH_CLIENT_DELETE` permission from the **Client** group.
**Replaced By:** [Delete customer account by Identity Provider](/developers/mobile-sdk/method-reference/ios/client-account#delete-customer-account-by-identity-provider) **Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func deleteAccount(password: String, success: ((Bool) -> Void), failure: ((ApiError) -> Void)) ```
```Objective-C + (void)deleteAccount:(nonnull NSString *)password success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **password** | String | yes | - | Customer's password | | **success** | ((Bool) -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```Swift let password: String = "PASSWORD" Client.deleteAccount(password: password, success: { (success) in // success }) { (error) in // failure } ```
```Objective-C NSString *password = "PASSWORD"; [SNRClient deleteAccount:password success:^(BOOL isSuccess) { // success } failure:^(SNRApiError *error) { // failure }]; ```
### Delete customer account by OAuth {#delete-customer-account-by-oauth} --- This method deletes a customer's account by OAuth. This method requires customer authentication. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.11 | 3.6.13 | 0.9.12 | n/a | | Deprecated in: | 3.6.19 | 3.6.19 | 0.14.0 | n/a | | Removed in: | 5.0.0 | 6.0.0 | n/a | n/a |
The API key must have the `SAUTH_CLIENT_DELETE` and `SAUTH_OAUTH_CLIENT_DELETE` permissions from the **Client** group.
**Replaced By:** [Delete customer account by Identity Provider](/developers/mobile-sdk/method-reference/ios/client-account#delete-customer-account-by-identity-provider) **Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func deleteAccountByOAuth(accessToken: String, success: ((Bool) -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)deleteAccountByOAuth:(nonnull NSString *)accessToken success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **accessToken** | String | yes | - | OAuth Access Token | | **success** | ((Bool) -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error | **Return Value:** No value is returned. ### Delete customer account by Facebook {#delete-customer-account-by-facebook} --- This method deletes a customer's account by Facebook. This method requires customer authentication. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.3.8 | 3.3.0 | 0.9.12 | n/a | | Deprecated in: | 3.6.19 | 3.6.19 | 0.14.0 | n/a | | Removed in: | 5.0.0 | 6.0.0 | n/a | n/a |
The API key must have the `SAUTH_CLIENT_DELETE` and `SAUTH_FACEBOOK_CLIENT_DELETE` permissions from the **Client** group.
**Replaced By:** [Delete customer account by Identity Provider](/developers/mobile-sdk/method-reference/ios/client-account#delete-customer-account-by-identity-provider) **Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func deleteAccountByFacebook(facebookToken: String, success: ((Bool) -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)deleteAccountByFacebook:(nonnull NSString *)facebookToken success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **facebookToken** | String | yes | - | Token from an active Facebook session | | **success** | ((Bool) -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```Swift guard let facebookToken = FBSDKAccessToken.current()?.tokenString else { return } Client.deleteAccountByFacebookToken(facebookToken: facebookToken, success: { (success) in // success }, failure: { (error) in // failure }) ```
```Objective-C NSString *facebookToken = [FBSDKAccessToken currentAccessToken].tokenString; [SNRClient deleteAccountByFacebook:facebookToken success:^(BOOL isSuccess) { // success } failure:^(SNRApiError *error) { // failure }]; ```
### Delete customer account by Apple Sign In {#delete-customer-account-by-apple-sign-in} --- This method deletes a customer's account information by Sign In With Apple. This method requires customer authentication. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.11 | 3.6.13 | 0.9.12 | n/a | | Deprecated in: | 3.6.19 | 3.6.19 | 0.14.0 | n/a | | Removed in: | 5.0.0 | n/a | n/a | n/a |
The API key must have the `SAUTH_CLIENT_DELETE` and `SAUTH_APPLE_CLIENT_DELETE` permissions from the **Client** group.
**Replaced By:** [Delete customer account by Identity Provider](/developers/mobile-sdk/method-reference/ios/client-account#delete-customer-account-by-identity-provider) **Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func deleteAccountByAppleSignIn(identityToken: Data, success: ((Bool) -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)deleteAccountByAppleSignIn:(nonnull NSData *)identityToken success:(nonnull void (^)(BOOL isSuccess))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **identityToken** | Data | yes | - | Token from Sign In With Apple session | | **success** | ((Bool) -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error | **Return Value:** No value is returned. # OAuth This article contains instruction on authenticating a customer in a mobile application with your backend by an OAuth-like method. Prepare your backend for this solution and then you perform part of the configuration on a user interface in the Synerise platform (`app.synerise.com`).
This is the recommended authentication method.
OAuth diagram
OAuth process diagram
Additionally, in the Synerise platform (`app.synerise.com`) you can define the following settings: - [Assignment of loyalty card](/docs/settings/tool/iam-for-apps/general#loyalty-card-assignment) - [JWT longevity](/docs/settings/tool/iam-for-apps/general#jwt-lifetime) - [Custom ID overwriting](/docs/settings/tool/iam-for-apps/general#custom-id-overwriting) - [External ID overwriting](/docs/settings/tool/iam-for-apps/general#external-id-overwriting) ## Logic explained --- The authentication process works in the following way: 1. A customer sign-in to the application generates an authentication request to your backend. 2. Your backend provides the application with an access token. 3. The access token is passed to Synerise by using the following methods: 4. Synerise passes that access token: - if the access token is JWT, to external JWK service for validation - if the access token isn't JWT, back to your backend in order to check if it's valid. 5. In response: - If authentication is successful, Synerise receives customer information such as the email, first name, last name, or other details* (the data can be mapped to fields in our system). For more information, check our [guide](/docs/settings/tool/iam-for-apps/oauth). - If the access token is not valid, the response type is different than HTTP 2xx. 6. If the authentication was successful, Synerise provides the application with our JWT access token for the customer (if this the first time this customer is authenticated, they are also registered with the provided information). *You can declare on user interface in Synerise if you want to update the customer's data with each login or only during the first log-in. ## Authentication methods ---
Conditional authentication lets you verify if a customer exists. This way, you can display screens with agreements or processes necessary for the first log-in.
| OS | Method | |--------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Android | - [Client.authenticate(token, provider, agreements, attributes, authId)](/developers/mobile-sdk/method-reference/android/client-authentication#authenticate-customer-by-identityprovider)
- [Client.authenticateConditionally(token, provider, agreements, attributes, authId)](/developers/mobile-sdk/method-reference/android/client-authentication#authenticate-customer-conditionally-by-identityprovider) | | iOS | - [Client.authenticate(token:clientIdentityProvider:authID:context:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-authentication#authenticate-customer-conditionally-by-identityprovider)
- [Client.authenticateConditionally(token:clientIdentityProvider:authID:context:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-authentication#authenticate-customer-conditionally-by-identityprovider) | | React Native | - [Synerise.Client.authenticate(token, clientIdentityProvider, authID, context, onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/client-authentication#authenticate-customer-by-identityprovider)
- [Synerise.Client.authenticateConditionally(token, clientIdentityProvider, authID context, onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/client-authentication#authenticate-customer-conditionally-by-identityprovider) | | Flutter | - [Synerise.client.authenticate(clientAuthContext, clientIdentityProvider, token)](/developers/mobile-sdk/method-reference/flutter/client-authentication#authenticate-customer-by-identityprovider)) |
**authId/authID** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
## Other methods --- ### Check if a customer is signed in This method checks if a customer is signed in through oAuth, Facebook, Sign in with Apple, or RaaS
This method returns `false` if a customer is authenticated through [Simple Profile Authentication](/developers/mobile-sdk/user-identification-and-authorization/simple-authentication).
| OS | Method | |--------------|-------------------------------------------------------------------------------------------------------------------------------------------| | Android | [Client.isSignedIn()](/developers/mobile-sdk/method-reference/android/client-authentication#check-if-a-customer-is-signed-in-via-raas-oauth-facebook-apple) | | iOS | [Client.isSignedIn()](/developers/mobile-sdk/method-reference/ios/client-authentication#check-if-a-customer-is-signed-in-via-raas-oauth-facebook-apple) | | React Native | [Synerise.Client.isSignedIn()](/developers/mobile-sdk/method-reference/react-native/client-authentication#check-if-a-customer-is-signed-in-via-raas-oauth-facebook-apple) | | Flutter | [Synerise.client.isSignedIn()](/developers/mobile-sdk/method-reference/flutter/client-authentication#check-if-a-customer-is-signed-in-via-raas-oauth-facebook-apple) | ### Customer sign out If you want to provide the customer with a logout feature in your application, use this method. The method terminates the JWT token and ends the customer session. | OS | Method | |--------------|-----------------------------------------------------------------------------------------------------------------------| | Android | [Client.signOut()](/developers/mobile-sdk/method-reference/android/client-authentication#sign-out-customer) | | iOS | [Client.signOut()](/developers/mobile-sdk/method-reference/ios/client-authentication#sign-out-customer) | | React Native | [Synerise.Client.signOut()](/developers/mobile-sdk/method-reference/react-native/client-authentication#sign-out-a-customer) | | Flutter | [Synerise.client.signOut()](/developers/mobile-sdk/method-reference/flutter/client-authentication#sign-out-a-customer) | ## What's next --- When the customer's is signed in, you can implement [profile management methods](/developers/mobile-sdk/user-identification-and-authorization/identification-and-user-management#profile-management-methods) and [session management methods](/developers/mobile-sdk/user-identification-and-authorization/session-management). # Events ### TrackerParams Represents custom parameters that may be added to tracked events. **Declared In:** Headers/SNRTrackerParams.h **Related To:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) **Inherits From:** [NSObject](https://developer.apple.com/documentation/objectivec/nsobject) **Declaration:**
```Swift class TrackerParams: NSObject ```
```Objective-C @interface SNRTrackerParams : NSObject ```
**Initializers:**
```Swift static func makeWithBuilder(_: ((TrackerParamsBuilder) -> ())) ```
```Objective-C + (instancetype)makeWithBuilder:(nonnull void (^)(SNRTrackerParamsBuilder *builder))buildBlock ```
--- --- ### TrackerParamsBuilder Object that is used to create parameters for the event classes. **Declared In:** Headers/SNRTrackerParamsBuilder.h **Related To:** [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [Event](/developers/mobile-sdk/class-reference/ios/events#event) **Inherits From:** [NSObject](https://developer.apple.com/documentation/objectivec/nsobject) **Declaration:**
```Swift class TrackerParamsBuilder: NSObject ```
```Objective-C @interface SNRTrackerParamsBuilder : NSObject ```
**Initializers:**
```Swift init() ```
```Objective-C - (instancetype)init ```
**Methods:**
```Swift func setString(_: String) ```
```Objective-C - (void)setString:(nonnull NSString *)string forKey:(nonnull NSString *)key ```
---
```Swift func setInt(_: Int) ```
```Objective-C - (void)setInt:(NSInteger)integer forKey:(nonnull NSString *)key ```
---
```Swift func setDouble(_: Double) ```
```Objective-C - (void)setDouble:(double)doubleValue forKey:(nonnull NSString *)key ```
---
```Swift func setFloat(_: Float) ```
```Objective-C - (void)setFloat:(float)floatValue forKey:(nonnull NSString *)key ```
---
```Swift func setBool(_: Bool) ```
```Objective-C - (void)setBool:(BOOL)boolValue forKey:(nonnull NSString *)key ```
---
```Swift func setObject(_: AnyClass) ```
```Objective-C - (void)setObject:(nonnull id)object forKey:(nonnull NSString *)key ```
--- --- ### Event Main event abstract class for inheriting classes.
This is an abstract class and it is not meant to be instantiated directly. You should use concrete `Event` subclasses instead.
**Declared In:** Headers/SNREvent.h **Related To:** [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Inherits From:** [NSObject](https://developer.apple.com/documentation/objectivec/nsobject) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class Event: NSObject ```
```Objective-C @interface SNREvent : NSObject ```
**Initializers:**
```Swift init(label: String) ```
```Objective-C - (instancetype)initWithLabel:(nonnull NSString *)label ```
---
```Swift init(label: String, params: TrackerParams) ```
```Objective-C - (instancetype)initWithLabel:(nonnull NSString *)label andParams:(nullable SNRTrackerParams *)params ```
--- --- ### CustomEvent
DO NOT send `transaction.charge` events as custom events.
Transactions must be tracked with these endpoints: - [`/v4/transactions`](https://hub.synerise.com/api-reference/data-management#operation/CreateATransaction) (single transaction) - [`/v4/transactions/batch`](https://hub.synerise.com/api-reference/data-management#operation/BatchAddOrUpdateTransactions) (multiple transactions)
Represents a custom event. **Declared In:** Headers/SNRCustomEvent.h **Related To:** [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Inherits From:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class CustomEvent: Event ```
```Objective-C @interface SNRCustomEvent : SNREvent ```
**Initializers:**
```Swift init(type: String, label: String, action: String, params: TrackerParams?) ```
```Objective-C - (instancetype)initWithType:(nonnull NSString *)type label:(nonnull NSString *)label action:(nonnull NSString *)action andParams:(nullable SNRTrackerParams *)params ```

```Swift init(label: String, action: String, params: TrackerParams?) ```
```Objective-C - (instancetype)initWithLabel:(nonnull NSString *)label action:(nonnull NSString *)action andParams:(nullable SNRTrackerParams *)params ```

```Swift init(label: String, action: String) ```
```Objective-C - (instancetype)initWithLabel:(nonnull NSString *)label action:(nonnull NSString *)action ```
--- --- ### PushViewedEvent Represents a 'client viewed push' event. This event is used for push message interaction tracking. **Declared In:** Headers/SNRPushViewedEvent.h **Related To:** [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Inherits From:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class PushViewedEvent: Event ```
```Objective-C @interface SNRPushViewedEvent : SNREvent ```
--- --- ### PushClickedEvent Represents a 'client clicked push' event. This event is used for push message interaction tracking. **Declared In:** Headers/SNRPushClickedEvent.h **Related To:** [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Inherits From:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class PushClickedEvent: Event ```
```Objective-C @interface SNRPushClickedEvent : SNREvent ```
--- --- ### PushCancelledEvent Represents a 'client viewed push' event. This event is used for push message interaction tracking. **Declared In:** Headers/SNRCancelledPushEvent.h **Related To:** [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Inherits From:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class CancelledPushEvent: Event ```
```Objective-C @interface SNRCancelledPushEvent : SNREvent ```
--- --- ### CartEvent Main cart action abstract class for inheriting classes.
This is an abstract class and it is not meant to be instantiated directly. You should use concrete `CartEvent` subclasses instead.
**Declared In:** Headers/SNRCartEvent.h **Related To:** [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Inherits From:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class CartEvent: Event ```
```Objective-C @interface SNRCartEvent : SNREvent ```
**Initializers:**
```Swift init(label: String, sku String, finalPrice: UnitPrice, quantity: Int, params: TrackerParams?) ```
```Objective-C - (instancetype)initWithLabel:(nonnull NSString *)label sku:(nonnull NSString *)sku finalPrice:(nonnull SNRUnitPrice *)unitPrice quantity:(NSInteger)quantity andParams:(nullable SNRTrackerParams *)params ```
---
```Swift init(label: String, sku: String, finalPrice: UnitPrice, quantity: Int) ```
```Objective-C - (instancetype)initWithLabel:(nonnull NSString *)label sku:(nonnull NSString *)sku finalPrice:(nonnull SNRUnitPrice *)unitPrice quantity:(NSInteger)quantity ```
**Methods:** This method sets a value for the `name` parameter.
```Swift func setName(_: String) ```
```Objective-C - (void)setName:(nonnull NSString *)name ```
--- This method sets a value for the `category` parameter.
```Swift func setCategory(_: String) ```
```Objective-C - (void)setCategory:(nonnull NSString *)category ```
--- This method sets values for the `categories` parameter.
```Swift func setCategories(_: [String]) ```
```Objective-C - (void)setCategories:(nonnull NSArray *)categories ```
--- This method sets a value for the `offline` parameter.
```Swift func setOffline(_: Bool) ```
```Objective-C - (void)setOffline:(BOOL)isOffline ```
--- This method sets the value of the `regularPrice` parameter.
```Swift func setRegularPrice(_: UnitPrice) ```
```Objective-C - (void)setRegularPrice:(nonnull SNRUnitPrice *)price ```
--- This method sets the value of the `discountedPrice` parameter.
```Swift func setDiscountedPrice(_: UnitPrice) ```
```Objective-C - (void)setDiscountedPrice:(nonnull SNRUnitPrice *)price ```
--- This method sets the value of the `url` parameter.
```Swift func setURL(_: URL) ```
```Objective-C - (void)setURL:(nonnull NSURL *)url ```
--- This method sets the value of the `producer` parameter (producer can signify a brand of the item).
```Swift func setProducer(_: String) ```
```Objective-C - (void)setProducer:(nonnull NSString *)producer ```
--- --- ### UnitPrice **Declared In:** Headers/SNRUnitPrice.h **Inherits From:** [NSObject](https://developer.apple.com/documentation/objectivec/nsobject) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class UnitPrice: NSObject ```
```Objective-C @interface SNRUnitPrice : NSObject ```
**Initializers:**
```Swift init(amount: Float) ```
```Objective-C - (instancetype)initWithAmount:(float)amount ```
---
```Swift init(amount: Float, locale: NSLocale) ```
```Objective-C - (instancetype)initWithAmount:(float)amount locale:(nonnull NSLocale *)locale ```
--- --- ### ProductAddedToCartEvent Represents a 'client added product to cart' event. **Declared In:** Headers/SNRProductAddedToCartEvent.h **Related To:** [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Inherits From:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) [CartEvent](/developers/mobile-sdk/class-reference/ios/events#cartevent) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class ProductAddedToCartEvent: CartEvent ```
```Objective-C @interface SNRProductAddedToCartEvent : SNRCartEvent ```
--- --- ### ProductRemovedFromCartEvent Represents a 'client removed product from cart' event. **Declared In:** Headers/SNRProductRemovedFromCartEvent.h **Related To:** [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Inherits From:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) [CartEvent](/developers/mobile-sdk/class-reference/ios/events#cartevent) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class ProductRemovedFromCartEvent: CartEvent ```
```Objective-C @interface SNRProductRemovedFromCartEvent : SNRCartEvent ```
--- --- ### ProductViewedEvent Represents a 'client viewed product' event. **Declared In:** Headers/SNRProductViewedEvent.h **Related To:** [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Inherits From:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class ProductViewedEvent: Event ```
```Objective-C @interface SNRProductViewedEvent : SNREvent ```
**Initializers:**
```Swift init(label: String, productName: String, productId: String, params: TrackerParams?) ```
```Objective-C - (instancetype)initWithLabel:(nonnull NSString *)label productName:(nonnull NSString *)productName productId:(nonnull NSString *)productId andParams:(nullable SNRTrackerParams *)params ```
**Methods:** Sets if a product is recommended or not.
```Swift func setIsRecommended(_: Bool) ```
```Objective-C - (void)setIsRecommended:(BOOL)isRecommended ```
--- This method sets a value for the `category` parameter.
```Swift func setCategory(_: String) ```
```Objective-C - (void)setCategory:(NSString *)category ```
--- This method sets the value of the `url` parameter.
```Swift func setURL(_: URL) ```
```Objective-C - (void)setURL:(NSURL *)url ```
--- --- ### ProductAddedToFavoritesEvent Represents a 'client added product to favorites' event. **Declared In:** Headers/SNRProductAddedToFavoritesEvent.h **Related To:** [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Inherits From:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class ProductAddedToFavoritesEvent: Event ```
```Objective-C @interface SNRProductAddedToFavoritesEvent : SNREvent ```
--- --- ### LoggedInEvent Represents a 'client logged in' event. **Declared In:** Headers/SNRLoggedInEvent.h **Related To:** [TrackerParams](/developers/mobile-sdk/class-reference/ios/events/#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events/#trackerparamsbuilder) **Inherits From:** [Event](/developers/mobile-sdk/class-reference/ios/events/#event) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class LoggedInEvent: Event ```
```Objective-C @interface SNRLoggedInEvent : SNREvent ```
--- --- ### LoggedOutEvent Represents a 'client logged out' event. **Declared In:** Headers/SNRLoggedOutEvent.h **Related To:** [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Inherits From:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class LoggedOutEvent: Event ```
```Objective-C @interface SNRLoggedOutEvent : SNREvent ```
--- --- ### RegisteredEvent Represents a 'client registered' event. **Declared In:** Headers/SNRCancelledPushEvent.h **Related To:** [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Inherits From:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class RegisteredEvent: Event ```
```Objective-C @interface SNRRegisteredEvent : SNREvent ```
--- --- ### RecommendationEvent Main recommendation abstract class for inheriting classes.
This is an abstract class and it is not meant to be instantiated directly. You should use concrete `RecommendationEvent` subclasses instead.
**Declared In:** Headers/SNRRecommendationEvent.h **Related To:** [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Inherits From:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class RecommendationEvent: Event ```
```Objective-C @interface SNRRecommendationEvent : SNREvent ```
--- --- ### RecommendationViewEvent Represents a 'client viewed a recommendation' event. **Declared In:** Headers/SNRRecommendationViewEvent.h **Related To:** [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Inherits From:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) [RecommendationEvent](/developers/mobile-sdk/class-reference/ios/events#recommendationevent) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class RecommendationViewEvent: RecommendationEvent ```
```Objective-C @interface SNRRecommendationViewEvent : SNRRecommendationEvent ```
**Initializers:**
```Swift init(label: String, campaignID: String, campaignHash: String, correlationId: String, params: TrackerParams?) ```
```Objective-C - (instancetype)initWithLabel:(NSString *)label campaignID:(NSString *)campaignID campaignHash:(NSString *)campaignHash correlationId:(NSString *)correlationId andParams:(nullable SNRTrackerParams *)params ```
---
```Swift init(label: String, items: [String], campaignID: String, campaignHash: String, correlationId: String, params: TrackerParams?) ```
```Objective-C - (instancetype)initWithLabel:(NSString *)label items:(nullable NSArray *)items campaignID:(NSString *)campaignID campaignHash:(NSString *)campaignHash correlationId:(NSString *)correlationId andParams:(nullable SNRTrackerParams *)params ```
**Methods:** This method sets a value for the `items` parameter.
```Swift func setItems(_ items: [String]) ```
```Objective-C - (void)setItems:(NSArray *)items ```
--- --- ### RecommendationSeenEvent Represents a 'client saw a recommendation' event. **Declared In:** Headers/SNRRecommendationSeenEvent.h **Related To:** [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Inherits From:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) [RecommendationEvent](/developers/mobile-sdk/class-reference/ios/events#recommendationevent) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class RecommendationSeenEvent: RecommendationEvent ```
```Objective-C @interface SNRRecommendationSeenEvent : SNRRecommendationEvent ```
**Initializers:**
```Swift init(label: String, productName: String, productId: String, campaignID: String, campaignHash: String, params: TrackerParams?) ```
```Objective-C - (instancetype)initWithLabel:(nonnull NSString *)label productName:(nonnull NSString *)productName productId:(nonnull NSString *)productId campaignID:(nonnull NSString *)campaignID campaignHash:(nonnull NSString *)campaignHash andParams:(nullable SNRTrackerParams *)params ```
**Methods:** Set a product's category.
```Swift func setCategory(_: String) ```
```Objective-C - (void)setCategory:(nonnull NSString *)category ```
--- Set a product's URL.
```Swift func setURL(_: URL) ```
```Objective-C - (void)setURL:(nonnull NSURL *)url ```
--- --- ### RecommendationClickEvent Represents a 'client clicked a recommendation' event. **Declared In:** Headers/SNRRecommendationSeenEvent.h **Related To:** [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Inherits From:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) [RecommendationEvent](/developers/mobile-sdk/class-reference/ios/events#recommendationevent) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class RecommendationClickEvent: RecommendationEvent ```
```Objective-C @interface SNRRecommendationClickEvent : SNRRecommendationEvent ```
**Initializers:**
```Swift init(label: String, productName: String, productId: String, campaignID: String, campaignHash: String, params: TrackerParams?) ```
```Objective-C - (instancetype)initWithLabel:(nonnull NSString *)label productName:(nonnull NSString *)productName productId:(nonnull NSString *)productId campaignID:(nonnull NSString *)campaignID campaignHash:(nonnull NSString *)campaignHash andParams:(nullable SNRTrackerParams *)params ```
**Methods:** Set a product's category.
```Swift func setCategory(_: String) ```
```Objective-C - (void)setCategory:(nonnull NSString *)category ```
--- Set a product's URL.
```Swift func setURL(_: URL) ```
```Objective-C - (void)setURL:(nonnull NSURL *)url ```
--- --- ### VisitedScreenEvent Represents a 'client visited screen' event. This can be used for mobile screen usage tracking. **Declared In:** Headers/SNRVisitedScreenEvent.h **Related To:** [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Inherits From:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class VisitedScreenEvent: Event ```
```Objective-C @interface SNRVisitedScreenEvent : SNREvent ```
**Initializers:**
```Swift init(label: String) ```
```Objective-C - (instancetype)initWithLabel:(nonnull NSString *)label ```
---
```Swift init(label: String, params: TrackerParams?) ```
```Objective-C - (instancetype)initWithLabel:(nonnull NSString *)label andParams:(nullable SNRTrackerParams *)params ```
--- --- ### HitTimerEvent Represents a 'client hit timer' event. This could be used for profiling or activity time monitoring - you can send a `HitTimerEvent` when a client starts doing something and send it once again when they finish, but this time with the different time signature. Then you can use our analytics engine to measure, for example, average activity time. **Declared In:** Headers/SNRHitTimerEvent.h **Related To:** [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Inherits From:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class HitTimerEvent: Event ```
```Objective-C @interface SNRHitTimerEvent : SNREvent ```
**Initializers:**
```Swift init(label: String) ```
```Objective-C - (instancetype)initWithLabel:(nonnull NSString *)label ```
---
```Swift init(label: String, params: TrackerParams?) ```
```Objective-C - (instancetype)initWithLabel:(nonnull NSString *)label andParams:(nullable SNRTrackerParams *)params ```
--- --- ### SearchedEvent Represents a 'client searched' event. **Declared In:** Headers/SNRSearchedEvent.h **Related To:** [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Inherits From:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class SearchedEvent: Event ```
```Objective-C @interface SNRSearchedEvent : SNREvent ```
**Initializers:**
```Swift init(label: String) ```
```Objective-C - (instancetype)initWithLabel:(nonnull NSString *)label ```
---
```Swift init(label: String, params: TrackerParams?) ```
```Objective-C - (instancetype)initWithLabel:(nonnull NSString *)label andParams:(nullable SNRTrackerParams *)params ```
--- --- ### SharedEvent Represents a 'client shared' event. **Declared In:** Headers/SNRSharedEvent.h **Related To:** [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Inherits From:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class SharedEvent: Event ```
```Objective-C @interface SNRSharedEvent : SNREvent ```
**Initializers:**
```Swift init(label: String) ```
```Objective-C - (instancetype)initWithLabel:(nonnull NSString *)label ```
---
```Swift init(label: String, params: TrackerParams?) ```
```Objective-C - (instancetype)initWithLabel:(nonnull NSString *)label andParams:(nullable SNRTrackerParams *)params ```
--- --- ### AppearedInLocationEvent Represents a 'client appeared in location' event. **Declared In:** Headers/SNRAppearedInLocationEvent.h **Related To:** [CCLocation](https://developer.apple.com/documentation/corelocation/cllocation) [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Inherits From:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class AppearedInLocationEvent: Event ```
```Objective-C @interface SNRAppearedInLocationEvent : SNREvent ```
**Initializers:**
```Swift init(label: String, location: CCLocation) ```
```Objective-C - (instancetype)initWithLabel:(nonnull NSString *)label andLocation:(nonnull CLLocation *)location ```
---
```Swift init(label: String, location: CCLocation, params: TrackerParams?) ```
```Objective-C - (instancetype)initWithLabel:(nonnull NSString *)label andLocation:(nonnull CLLocation *)location andParams:(nullable SNRTrackerParams *)params ```
--- --- ### CrashEvent Represents an 'application crashed' event. **Declared In:** Headers/SNRCrashEvent.h **Related To:** [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Inherits From:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) **Conforms To:** [NSCopying](https://developer.apple.com/documentation/foundation/nscopying) **Declaration:**
```Swift class CrashEvent: Event ```
```Objective-C @interface SNRCrashEvent : SNREvent ```
**Initializers:**
```Swift init(label: String) ```
```Objective-C - (instancetype)initWithLabel:(nonnull NSString *)label ```

```Swift init(label: String, params: TrackerParams?) ```
```Objective-C - (instancetype)initWithLabel:(nonnull NSString *)label andParams:(nullable SNRTrackerParams *)params ```
**Methods:** This method sets the exception's `name` parameter.
```Swift func setExceptionName(_: String) ```
```Objective-C - (void)setExceptionName:(nonnull NSString *)exceptionName ```
--- This method sets the exception's `reason` parameter.
```Swift func setExceptionReason(_: String) ```
```Objective-C - (void)setExceptionReason:(nonnull NSString *)exceptionReason ```
--- This method sets the exception's `stacktrace` parameter.
```Swift func setExceptionStacktrace(_: String) ```
```Objective-C - (void)setExceptionStacktrace:(nonnull NSString *)exceptionStacktrace ```
# Customer account management --- ## Get customer account information --- This method gets a customer’s account information. This method requires customer authentication.
The API key must have the `API_PERSONAL_INFORMATION_CLIENT_READ` permission from the **Client** group.
**Declared In:** lib/modules/client/client_impl.dart **Related To:** [ClientAccountInformation](/developers/mobile-sdk/class-reference/flutter/client#clientaccountinformation) **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> getAccount({required void Function(ClientAccountInformation) onSuccess, required void Function(SyneriseError) onError}) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **onSuccess** | Function([ClientAccountInformation](/developers/mobile-sdk/class-reference/flutter/client#clientaccountinformation) clientAccountInformation) | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
await Synerise.client.getAccount(onSuccess: (ClientAccountInformation result) {
  //onSuccess handling
}, onError: (SyneriseError error) {
  //onError handling
});
**Declaration:**
Future<ClientAccountInformation> getAccount() async
**Return Value:** [ClientAccountInformation](/developers/mobile-sdk/class-reference/flutter/client#clientaccountinformation) **Example:**
final ClientAccountInformation clientAccountInformation = await Synerise.client.getAccount().catchError((error)
## Update customer account basic information --- This method updates a customer’s account’s basic information (without identification data: uuid, customId, email). This method requires the context object with the customer’s account information. Omitted fields are not modified. This method does not require customer authentication and can be used by anonymous profiles. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.22.0 | 5.21.0 | 0.24.0 | 1.4.0 |
The API key must have the `API_BASIC_INFORMATION_CLIENT_UPDATE` permission from the **Client** group.
**Declared In:** lib/modules/client/client_impl.dart **Related To:** [ClientAccountUpdateBasicInformationContext](/developers/mobile-sdk/class-reference/flutter/client#clientaccountupdatebasicinformationcontext) **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client) **Declaration:**
Future<void> updateAccountBasicInformation(ClientAccountUpdateBasicInformationContext context,
      {required void Function() onSuccess,
      required void Function(SyneriseError error) onError}) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **context** | [ClientAccountUpdateBasicInformationContext](/developers/mobile-sdk/class-reference/flutter/client#clientaccountupdatebasicinformationcontext) | yes | - | Object with customer’s first name, phone, and other optional data | | **onSuccess** | Function() | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
ClientAccountUpdateBasicInformationContext context = ClientAccountUpdateBasicInformationContext(
        email: email,
        password: password,
        firstName: firstName,
        lastName: lastName,
        sex: ClientSex.getClientSexFromString(sex));

    await Synerise.client.updateAccountBasicInformation(clientAccountUpdateContext, onSuccess: () {
      //onSuccess handling
    }, onError: (SyneriseError error) {
      //onError handling
    });
## Update customer account information --- This method updates a customer’s account information. This method requires the context object with the customer’s account information. Omitted fields are not modified. This method requires customer authentication.
The API key must have the `API_PERSONAL_INFORMATION_CLIENT_UPDATE` permission from the **Client** group.
**Declared In:** lib/modules/client/client_impl.dart **Related To:** [ClientAccountUpdateContext](/developers/mobile-sdk/class-reference/flutter/client#clientaccountupdatecontext) **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> updateAccount(ClientAccountUpdateContext context,
      {required void Function() onSuccess,
      required void Function(SyneriseError error) onError}) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **context** | [ClientAccountUpdateContext](/developers/mobile-sdk/class-reference/flutter/client#clientaccountupdatecontext) | yes | - | Object with customer's email, password, and other optional data | | **onSuccess** | Function() | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
ClientAccountUpdateContext clientAccountUpdateContext = ClientAccountUpdateContext(
        email: email,
        password: password,
        firstName: firstName,
        lastName: lastName,
        sex: ClientSex.getClientSexFromString(sex));

    await Synerise.client.updateAccount(clientAccountUpdateContext, onSuccess: () {
      //onSuccess handling
    }, onError: (SyneriseError error) {
      //onError handling
    });
**Declaration:**
Future<void> updateAccount(ClientAccountUpdateContext context) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **context** | [ClientAccountUpdateContext](/developers/mobile-sdk/class-reference/flutter/client#clientaccountupdatecontext) | yes | - | Object with customer's email, password, and other optional data | **Return Value:** No value is returned. **Example:**
ClientAccountUpdateContext clientAccountUpdateContext = ClientAccountUpdateContext(
        email: email,
        password: password,
        firstName: firstName,
        lastName: lastName,
        sex: ClientSex.getClientSexFromString(sex));

    await Synerise.client.updateAccount(clientAccountUpdateContext).catchError((error) {
      //onError handling
    });
## Change customer's account password --- This method changes a customer’s password. This method requires customer authentication.
Returns the HTTP 403 status code if the provided old password is invalid.
The API key must have the `SAUTH_CHANGE_PASSWORD_CLIENT_UPDATE` permission from the **Client** group.
**Declared In:** lib/modules/client/client_impl.dart **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> changePassword(String oldPassword, String newPassword,
    {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **oldPassword** | String | yes | - | Customer’s old password | | **newPassword** | String | yes | - | Customer’s new password | | **onSuccess** | Function() | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
await Synerise.client.changePassword(oldPassword, newPassword, onSuccess: () {
      //onSuccess handling
    }, onError: (SyneriseError error) {
      //onError handling
    });
**Declaration:**
Future<void> changePassword(String oldPassword,  String password) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **newPassword** | String | yes | - | Customer’s new password | | **oldPassword** | String | yes | - | Customer’s old password | **Return Value:** No value is returned. **Example:**
await  Synerise.client.changePassword(oldPassword, password).catchError((error)
## Request password reset for customer account --- This method requests a customer’s password reset with email. The customer will receive a token to the provided email address. That token is then used for the confirmation of password reset. This method requires the customer’s email. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_PASSWORD_RESET_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** lib/modules/client/client_impl.dart **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> requestPasswordReset(String email, {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | String | yes | - | Customer’s email | | **onSuccess** | Function() | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
await Synerise.client.requestPasswordReset(email, onSuccess: () {
  //onSuccess handling
}, onError: (SyneriseError error) {
  //onError handling
});
**Declaration:**
Future<void> requestPasswordReset(String email) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | String | yes | - | Customer’s email | **Return Value:** No value is returned. **Example:**
await  Synerise.client.requestPasswordReset(email).catchError((error)
## Confirm password reset for customer account --- This method confirm a customer’s password reset with the new password and token provided by password reset request. This method requires the customer’s new password and the confirmation token received by e-mail. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_PASSWORD_RESET_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** lib/modules/client/client_impl.dart **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> confirmPasswordReset(String password, String token, {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **password** | String | yes | - | New password for the customer | | **token** | String | yes | - | Customer's token provided in an email | | **onSuccess** | Function() | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
await Synerise.client.confirmPasswordReset(password, token, onSuccess: () {
  //onSuccess handling
}, onError: (SyneriseError error) {
  //onError handling
});
**Declaration:**
Future<void> confirmPasswordReset(String password, String token) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | String | yes | - | Customer’s email | | **token** | String | yes | - | Customer's token provided in an email | **Return Value:** No value is returned. **Example:**
await  Synerise.client.confirmPasswordReset(email, token).catchError((error)
## Delete customer account --- This method deletes a customer's account. This method requires customer authentication. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.11 | 3.6.13 | 0.9.12 | n/a | | Deprecated in: | 3.6.19 | 3.6.19 | 0.14.0 | n/a | | Removed in: | 5.0.0 | 6.0.0 | n/a | n/a |
Returns the HTTP 403 status code is returned if the provided password is invalid.
The API key must have the `SAUTH_CLIENT_DELETE` permission from the **Client** group.
**Declared In:** lib/modules/client/client_impl.dart **Related To:** [ClientIdentityProvider](/developers/mobile-sdk/class-reference/flutter/client#clientidentityprovider) **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> deleteAccount(String clientAuthFactor, IdentityProvider identityProvider, {String? authId, required void Function() onSuccess, required void Function(SyneriseError) onError}) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **clientAuthFactor** | String | yes | - | Customer’s password or token from the identity provider | | **identityProvider** | [ClientIdentityProvider](/developers/mobile-sdk/class-reference/flutter/client#clientidentityprovider) | yes | - | Customer's identity provider | | **authID** | String | no | null | Optional identifier of authorization | | **onSuccess** | Function() | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
await Synerise.client.deleteAccount(clientAuthFactor, identityProvider, authId, onSuccess: () {
  //onSuccess handling
}, onError: (SyneriseError error) {
  //onError handling
});
**Declaration:**
Future<void> deleteAccount(String clientAuthFactor,  IdentityProvider identityProvider,  String? authId) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **clientAuthFactor** | String | yes | - | Customer’s password or token from the identity provider | | **identityProvider** | [ClientIdentityProvider](/developers/mobile-sdk/class-reference/flutter/client#clientidentityprovider) | yes | - | Customer's identity provider | | **authID** | String | yes | null | Optional identifier of authorization | **Return Value:** No value is returned. **Example:**
await  Synerise.client.deleteAccount(clientAuthFactor, identityProvider, authId).catchError((error)
## Request email change for customer account --- This method requests a customer's email change. This method is a global operation and doesn't require customer authentication.
Returns the HTTP 403 status code if the provided token or the password is invalid.
The API key must have the `SAUTH_CHANGE_EMAIL_CLIENT_UPDATE` permission from the **Client** group.
**Declared In:** lib/modules/client/client_impl.dart **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> requestEmailChange(String email, String password, {String? externalToken, String? authID, required void Function() onSuccess, required void Function(SyneriseError) onError}) async
**Parameters:** | Parameter | Type | Mandatory | Description | | --- | --- | --- | --- | | **email** | String | yes | Customer's new email | | **password** | String | yes | Customer's password | | **externalToken** | String | no | Customer's token (if OAuth, Facebook, and so on) | | **authID** | String | no | Optional identifier of authorization | | **onSuccess** | Function() | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
await Synerise.client.requestEmailChange(email, password, externalToken: externalToken, authID: authID, onSuccess: () {
  //onSuccess handling
}, onError: (SyneriseError error) {
  //onError handling
});
**Declared In:** lib/modules/client/client_impl.dart **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client) **Declaration:**
Future<void> requestEmailChange(String email, String password, [String? externalToken, String? authID]) async
**Parameters:** | Parameter | Type | Mandatory | Description | | --- | --- | --- | --- | | **email** | String | yes | Customer's new email | | **password** | String | yes | Customer's password | | **externalToken** | String | no | Customer's token (if OAuth, Facebook, and so on) | | **authID** | String | no | Optional identifier of authorization | **Return Value:** No value is returned. **Example:**
await Synerise.client.requestEmailChange(email, password).catchError((error) {
## Confirm email change for customer account --- This method confirms an email change. This method is a global operation and doesn't require customer authentication.
Returns the HTTP 403 status code if the provided token is invalid.
The API key must have the `SAUTH_CHANGE_EMAIL_CLIENT_UPDATE` permission from the **Client** group.
**Declared In:** lib/modules/client/client_impl.dart **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> confirmEmailChange(String token, bool newsletterAgreement,
      {required void Function() onSuccess,
      required void Function(SyneriseError error) onError}) async
**Parameters:** | Parameter | Type | Mandatory | Description | | --- | --- | --- | --- | | **token** | String | yes | Customer's token provided in an email | | **newsletterAgreement** | bool | yes | Agreement for sending newsletters to the provided email | | **onSuccess** | Function() | yes | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
await Synerise.client.confirmAccountActivationByPin(email, pinCode, onSuccess: () {
    //onSuccess handling
  }, onError: (SyneriseError error) {
    //onError handling
  });
**Declaration:**
Future<void> confirmEmailChange(String token, bool newsletterAgreement) async
**Parameters:** | Parameter | Type | Mandatory | Description | | --- | --- | --- | --- | | **token** | String | yes | Customer's token provided in an email | | **newsletterAgreement** | bool | yes | Agreement for sending newsletters to the provided email | **Return Value:** No value is returned. **Example:**
await Synerise.client.confirmEmailChange(token, true).catchError((error) {
## Request phone update on customer account --- This method requests a customer's phone update. A confirmation code is sent to the phone number. This method is a global operation and doesn't require customer authentication.
The API key must have the `API_PERSONAL_PHONE_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** lib/modules/client/client_impl.dart **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> requestPhoneUpdate(String phone, {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
**Parameters:** | Parameter | Type | Mandatory | Description | | --- | --- | --- | --- | | **phone** | String | yes | Customer's new phone number | | **onSuccess** | Function() | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
await Synerise.client.requestPhoneUpdate(phone, onSuccess: () {
  //onSuccess handling
}, onError: (SyneriseError error) {
  //onError handling
});
**Declaration:**
Future<void> requestPhoneUpdate(String phone) async
**Parameters:** | Parameter | Type | Mandatory | Description | | --- | --- | --- | --- | | **phone** | String | yes | Customer's new phone number | **Return Value:** No value is returned. **Example:**
await Synerise.client.requestPhoneUpdate(phone).catchError((error) {
## Confirm phone update on customer account --- This method confirms a phone number update. This action requires the new phone number and confirmation code as parameters. This method is a global operation and doesn't require customer authentication.
Returns the HTTP 403 status code if the provided UUID does not exist or the password is invalid.
The API key must have the `API_PERSONAL_PHONE_CLIENT_CREATE` permission from the **Client** group.
**Declared In:** lib/modules/client/client_impl.dart **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> confirmPhoneUpdate(String phone, String confirmationCode, bool smsAgreement, {required void Function() onSuccess, required void Function(SyneriseError) onError}) async
**Parameters:** | Parameter | Type | Mandatory | Description | | --- | --- | --- | --- | | **phone** | String | yes | New phone number | | **confirmationCode** | String | yes | A confirmation code received by a text message | | **smsAgreement** | bool | yes | Agreement for sending SMS to the provided number | | **onSuccess** | Function() | yes | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
await Synerise.client.confirmPhoneUpdate(phone, confirmationCode, smsAgreement, onSuccess: () {
  //onSuccess handling
}, onError: (SyneriseError error) {
  //onError handling
});
**Declaration:**
Future<void> confirmPhoneUpdate(String phone, String confirmationCode, bool smsAgreement) async
**Parameters:** | Parameter | Type | Mandatory | Description | | --- | --- | --- | --- | | **phone** | String | yes | New phone number | | **confirmationCode** | String | yes | A confirmation code received by a text message | | **smsAgreement** | bool | yes | Agreement for sending SMS to the provided number | **Return Value:** No value is returned. **Example:**
await Synerise.client.confirmPhoneUpdate(phone, confirmationCode, true).catchError((error) {
# Events ### Event Class model for events. **Declared In:** `com.synerise.sdk.event.Event` **Declaration:**
```Java public abstract class Event implements Serializable ```
```Kotlin abstract class Event : Serializable ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **eventTime** | Date | no | - | Event time | | **type** | String | no | - | Event type | | **action** | String | no | - | Event action | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hubs. It isn't shown on a Profile card. | | **clientParams** | HashMap | no | - | Profile parameters | | **params** | HashMap | no | - | Event params |
All properties above are accessible by using getters.
**Initializers:** There are no initializers. **Methods:** This method retrieves the value of the `label` parameter.
public String getLabel()
--- This method retrieves the value of the `action` parameter.
public String getAction()
--- This method retrieves the values of the `clientParams` object.
public HashMap<String, Object> getClientParams()
--- This method retrieves the value of the `eventTime` parameter.
public Date getEventTime()
--- This method retrieves the value of the `type` parameter.
public String getType()
--- This method retrieves the values of the `eventParams` object.
public HashMap<String, Object> getParams()
--- --- --- ### CustomEvent
DO NOT send `transaction.charge` events as custom events.
Transactions must be tracked with these endpoints: - [`/v4/transactions`](https://hub.synerise.com/api-reference/data-management#operation/CreateATransaction) (single transaction) - [`/v4/transactions/batch`](https://hub.synerise.com/api-reference/data-management#operation/BatchAddOrUpdateTransactions) (multiple transactions)
Class model for _custom_ event. **Declared In:** `com.synerise.sdk.event.model.CustomEvent` **Declaration:**
```Java public class CustomEvent extends Event ```
```Kotlin class CustomEvent : Event ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hubs. It isn't shown on a Profile card. | | **action** | String | no | - | Event action | | **params** | TrackerParams | yes | - | Event tracker parameters | **Initializers:** The following constructors are available:
public CustomEvent(@NonNull String action, @NonNull String label)
public CustomEvent(@NonNull String action, @NonNull String label, @Nullable TrackerParams params)
public CustomEvent(@NonNull String type, @NonNull String action, @NonNull String label, @Nullable TrackerParams params)
**Methods:** There are no methods. --- --- ### AppStartedEvent Class model for the application started event. **Declared In:** `com.synerise.sdk.event.model.interaction.AppStartedEvent` **Declaration:**
```Java public class AppStartedEvent extends Event ```
```Kotlin class AppStartedEvent : Event ```
This event will be sent every time an application is started.
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hub. It isn't shown on a Profile card. | | **params** | TrackerParams | yes | - | Event tracker parameters | #### Parameters tracked | Parameter | Description | | --- | --- | | **currentSDKVersion** | Current SDK version | | **lastSDKVersion** | Last SDK version | | **sdkVersionCode** | Current SDK version code | | **applicationName** | Application name | | **version** | Application version | | **appVersionCode** | Application version code | | **deviceId** | Device ID. Can be null | | **deviceModel** | Device model | | **deviceManufacturer** | Device manufacturer | | **deviceResolution** | Device resolution | | **deviceType** | Device type | | **os** | OS type | | **osVersion** | OS version | | **osLanguage** | System language | | **systemPushConsent** | System push agreement | | **networkType** | Network type | | **origin** | Origin of SDK | | **networkCountry** | Country of network | | **cellType** | Cell type | | **cellCarrier** | Cell carrier | | **cellCountry** | Cell country | | **cellRoaming** | Cell roaming | **Initializers:** The following constructors are available:
public AppStartedEvent(@NonNull String label)
public AppStartedEvent(@NonNull String label, @Nullable TrackerParams params)
**Methods:** There are no methods. --- --- ### AutoTrackingEvent Class model for _autotracking_ events. **Declared In:** `com.synerise.sdk.event.model.interaction.AutoTrackingEvent` **Declaration:**
```Java public class AutoTrackingEvent extends Event ```
```Kotlin class AutoTrackingEvent : Event ```
This event is sent only by the Synerise SDK. Sending this event in your application on your own is **not recommended**.
**Properties:** There are no public properties.
The `screen.interaction` and `screen.view` events are sent by the [auto-tracking module](/developers/mobile-sdk/event-tracking#events-tracked-automatically).
**Initializers:** There are no public constructors. **Methods:** There are no methods. --- --- ### ViewedPushEvent Class model for the `push.view` event. **Declared In:** `com.synerise.sdk.event.model.push.ViewedPushEvent` **Declaration:**
```Java public class ViewedPushEvent extends Event ```
```Kotlin class ViewedPushEvent : Event ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hubs. It isn't shown on a Profile card. | | **params** | TrackerParams | yes | - | Event tracker parameters | **Initializers:** The following constructors are available:
public ViewedPushEvent(@NonNull String label)
public ViewedPushEvent(@NonNull String label, @Nullable TrackerParams params)
**Methods:** There are no methods. --- --- ### ClickedPushEvent Class model for the `push.click` event. **Declared In:** `com.synerise.sdk.event.model.push.ClickedPushEvent` **Declaration:**
```Java public class ClickedPushEvent extends Event ```
```Kotlin class ClickedPushEvent : Event ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hub. It isn't shown on a Profile card. | | **params** | TrackerParams | yes | - | Event tracker parameters | **Initializers:** The following constructors are available:
public ClickedPushEvent(@NonNull String label)
public ClickedPushEvent(@NonNull String label, @Nullable TrackerParams params)
**Methods:** There are no methods. --- --- ### CancelledPushEvent Class model for the cancel push event generated. **Declared In:** `com.synerise.sdk.event.model.push.CancelledPushEvent` **Declaration:**
```Java public class CancelledPushEvent extends Event ```
```Kotlin class CancelledPushEvent : Event ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hub. It isn't shown on a Profile card. | | **params** | TrackerParams | yes | - | Event tracker parameters | **Initializers:** The following constructors are available:
public CancelledPushEvent(@NonNull String label)
public CancelledPushEvent(@NonNull String label, @Nullable TrackerParams params)
**Methods:** There are no methods. --- --- ### CartEvent Class model for the events related to a cart. **Declared In:** `com.synerise.sdk.event.model.products.cart.CartEvent` **Declaration:**
```Java public abstract class CartEvent extends Event ```
```Kotlin abstract class CartEvent : Event ```
#### Inheriting classes [AddedToCartEvent](/developers/mobile-sdk/class-reference/ios/events#productaddedtocartevent) [RemovedFromCartEvent](/developers/mobile-sdk/class-reference/ios/events#productremovedfromcartevent) **Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **type** | String | no | - | Event type | | **sku** | String | no | - | SKU of the item | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hub. It isn't shown on a Profile card. | | **finalPrice** | `UnitPrice` | no | - | Final price of the item | | **quantity** | int | no | - | Quantity of the item | | **params** | TrackerParams | yes | - | Event tracker parameters |
The following keys: `sku`, `name`, `category`, `categories`, `offline`, `regularUnitPrice`, `discountedUnitPrice`, `finalUnitPrice`, `url`, `producer`, `quantity` are reserved by Synerise for the `params` object.
**Initializers:**
CartEvent(@NonNull String type, @NonNull String label, @NonNull String sku, @NonNull UnitPrice finalPrice, int quantity,
              @Nullable TrackerParams params)
**Methods:** This method sets a value for the `name` parameter.
public void setName(String name)
--- This method sets a value for the `category` parameter.
public void setCategory(String category)
--- This method sets values for the `categories` parameter.
public void setCategories(List<String> categories)
--- This method sets a value for the `offline` parameter.
public void setOffline(boolean offline)
--- This method sets the value of the `regularPrice` parameter.
public void setRegularPrice(UnitPrice regularPrice)
--- This method sets the value of the `discountedPrice` parameter.
public void setDiscountedPrice(UnitPrice discountedPrice)
--- This method sets the value of the `url` parameter.
public void setUrl(String url)
--- This method sets the value of the `producer` parameter (producer can signify a brand of the item).
public void setProducer(String producer)
--- --- --- ### AddedToCartEvent Class model for _add to cart_ event. **Declared In:** `com.synerise.sdk.event.model.products.cart.AddedToCartEvent` **Declaration:**
```Java public class AddedToCartEvent extends CartEvent ```
```Kotlin class AddedToCartEvent : CartEvent ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **type** | String | no | - | Event type | | **sku** | String | no | - | SKU of the product | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hubs. It isn't shown on a Profile card. | | **finalPrice** | UnitPrice | no | - | Final price of the product | | **quantity** | int | no | - | Quantity of the product | | **params** | TrackerParams | yes | - | Event tracker params |
The `"sku"`, `"name"`, `"category"`, `"categories"`, `"offline"` , `"regularUnitPrice"`, `"discountedUnitPrice"`, `"finalUnitPrice"`, `"url"`, `"producer"` , `"quantity"` keys are reserved by Synerise in params.
**Initializers:** The following constructors are available:
public AddedToCartEvent(@NonNull String label, @NonNull String sku, @NonNull UnitPrice finalPrice, int quantity)
public AddedToCartEvent(@NonNull String label, @NonNull String sku, @NonNull UnitPrice finalPrice, int quantity,
                            @Nullable TrackerParams params)
**Methods:** This method defines the value of the `name` parameter.
public void setName(String name)
--- This method defines the value of the `category` parameter.
public void setCategory(String category)
--- This method defines the values of the `categories` parameter.
public void setCategories(List<String> categories)
--- This method defines the value of the `offline` parameter. The offline parameter describes whether an event occurred outside website, for example in a cash register.
public void setOffline(boolean offline)
--- This method defines the value of the `regularPrice` parameter.
public void setRegularPrice(UnitPrice regularPrice)
--- This method defines the value of the `discountedPrice` parameter.
public void setDiscountedPrice(UnitPrice discountedPrice)
--- This method defines the value of the `url` parameter.
public void setUrl(String url)
--- This method defines the value of the `producer` parameter. A producer is a manufacturer of the item.
public void setProducer(String producer)
--- --- --- ### RemovedFromCartEvent Class model for _remove from cart_ event. **Declared In:** `com.synerise.sdk.event.model.products.cart.RemovedFromCartEvent` **Declaration:**
```Java public class RemovedFromCartEvent extends CartEvent ```
```Kotlin class RemovedFromCartEvent : CartEvent ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **type** | String | no | - | Event type | | **sku** | String | no | - | SKU of the product | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hubs. It isn't shown on a Profile card. | | **finalPrice** | `UnitPrice` | no | - | Final price of the product | | **quantity** | int | no | - | Quantity of the product | | **params** | TrackerParams | yes | - | Event tracker params |
The keys `"sku"`, `"name"`, `"category"`, `"categories"`, `"offline"` , `"regularUnitPrice"`, `"discountedUnitPrice"`, `"finalUnitPrice"`, `"url"`, `"producer"` , `"quantity"` are reserved by Synerise in params.
**Initializers:** The following constructors are available:
public RemovedFromCartEvent(@NonNull String label, @NonNull String sku, @NonNull UnitPrice finalPrice, int quantity)
public RemovedFromCartEvent(@NonNull String label, @NonNull String sku, @NonNull UnitPrice finalPrice, int quantity,
                            @Nullable TrackerParams params)
**Methods:** This method defines the value of the `name` parameter.
public void setName(String name)
--- This method defines the value of the `category` parameter.
public void setCategory(String category)
--- This method defines the values of the `categories` parameter.
public void setCategories(List<String> categories)
--- This method defines the value of the `offline` parameter. The offline parameter describes whether an event occurred outside website, for example in a cash register.
public void setOffline(boolean offline)
--- This method defines the value of the `regularPrice` parameter.
public void setRegularPrice(UnitPrice regularPrice)
--- This method defines the value of the `discountedPrice` parameter.
public void setDiscountedPrice(UnitPrice discountedPrice)
--- This method defines the value of the `url` parameter.
public void setUrl(String url)
--- This method defines the value of the `producer` parameter. A producer is a manufacturer of the item.
public void setProducer(String producer)
--- --- --- ### ProductEvent Class model for _product_ events. **Declared In:** `com.synerise.sdk.event.model.ai.ProductEvent` **Declaration:**
```Java public class ProductEvent extends Event ```
```Kotlin class ProductEvent : Event ```
#### Inheriting classes ProductViewEvent **Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **name** | String | no | - | Product name | | **type** | String | no | - | Event type | | **productId** | String | no | - | Product ID | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hubs. It isn't shown on a Profile card. | | **params** | TrackerParams | yes | - | Event tracker params |
The `"productId"`, `"name"`, `"category"`, `"url"` keys are reserved by Synerise in params.
**Initializers:**
public ProductEvent(@NonNull String type, @NonNull String label, @NonNull String productId, @NonNull String name,
                        @Nullable TrackerParams params)
**Methods:** This method defines the value of the `category` parameter.
public void setCategory(String category)
--- This method defines the value of the `url` parameter.
public void setUrl(String url)
--- --- --- ### ProductViewEvent Class model for _the product view_ event. **Declared In:** `com.synerise.sdk.event.model.ai.ProductViewEvent` **Declaration:**
```Java public class ProductViewEvent extends ProductEvent ```
```Kotlin class ProductViewEvent : ProductEvent ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **name** | String | no | - | Product name | | **productId** | String | no | - | Product ID | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hubs. It isn't shown on a Profile card. | | **params** | TrackerParams | yes | - | Event tracker params |
The `"productId"`, `"name"`, `"category"`, `"url"` keys are reserved by Synerise in params.
**Initializers:** The following constructors are available:
public ProductViewEvent(@NonNull String label, @NonNull String productId, @NonNull String name)
public ProductViewEvent(@NonNull String label, @NonNull String productId, @NonNull String name,
                            @Nullable TrackerParams params)
**Methods:** There are no methods. --- --- ### AddedToFavoritesEvent Class model for _add to favourites_ event. **Declared In:** `com.synerise.sdk.event.model.products.AddedToFavoritesEvent` **Declaration:**
```Java public class AddedToFavoritesEvent extends Event ```
```Kotlin class AddedToFavoritesEvent : Event ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hubs. It isn't shown on a Profile card. | | **params** | TrackerParams | yes | - | Event tracker params | **Initializers:** The following constructors are available:
public AddedToFavoritesEvent(@NonNull String label)
public AddedToFavoritesEvent(@NonNull String label, @Nullable TrackerParams params)
**Methods:** There are no methods. --- --- ### LoggedInEvent Class model for _Log in_ event. **Declared In:** `com.synerise.sdk.event.model.session.LoggedInEvent` **Declaration:**
```Java public class LoggedInEvent extends Event ```
```Kotlin class LoggedInEvent : Event ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hubs. It isn't shown on a Profile card. | | **params** | TrackerParams | yes | - | Event tracker params | **Initializers:** The following constructors are available:
public LoggedInEvent(@NonNull String label)
public LoggedInEvent(@NonNull String label, @Nullable TrackerParams params)
**Methods:** There are no methods. --- --- ### LoggedOutEvent Class model for _Log out_ event. **Declared In:** `com.synerise.sdk.event.model.session.LoggedOutEvent` **Declaration:**
```Java public class LoggedOutEvent extends Event ```
```Kotlin class LoggedOutEvent : Event ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hubs. It isn't shown on a Profile card. | | **params** | TrackerParams | yes | - | Event tracker params | **Initializers:** The following constructors are available:
public LoggedOutEvent(@NonNull String label)
public LoggedOutEvent(@NonNull String label, @Nullable TrackerParams params)
**Methods:** There are no methods. --- --- ### RegisteredEvent Class model for _client register_ event. . **Declared In:** `com.synerise.sdk.event.model.session.RegisteredEvent` **Declaration:**
```Java public class RegisteredEvent extends Event ```
```Kotlin class RegisteredEvent : Event ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hubs. It isn't shown on a Profile card. | | **params** | TrackerParams | yes | - | Event tracker params | **Initializers:** The following constructors are available:
public RegisteredEvent(@NonNull String label)
public RegisteredEvent(@NonNull String label, @Nullable TrackerParams params)
**Methods:** There are no methods. --- --- ### RecommendationEvent Class model for _recommendation_ events. **Declared In:** `com.synerise.sdk.event.model.ai.RecommendationEvent` **Declaration:**
```Java public class RecommendationEvent extends Event ```
```Kotlin class RecommendationEvent : Event ```
#### Inheriting classes RecommendationClickEvent RecommendationSeenEvent **Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **name** | String | no | - | Product name | | **type** | String | no | - | Event type | | **productId** | String | no | - | Product ID | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hubs. It isn't shown on a Profile card. | | **campaignId** | String | no | - | Recommendation campaign ID | | **campaignHash** | String | no | - | Recommendation campaign hash | | **params** | TrackerParams | yes | - | Event tracker params |
The `"productId"`, `"name"`, `"category"`, `"url"`, `"campaignId"` , `"campaignHash"` keys are reserved by Synerise in params.
**Initializers:**
public RecommendationEvent(@NonNull String type, @NonNull String label, @NonNull String productId, @NonNull String name,
                               @NonNull String campaignId, @NonNull String campaignHash,
                               @Nullable TrackerParams params)
**Methods:** This method defines the value of the `category` parameter.
public void setCategory(String category)
--- This method defines the value of the `url` parameter.
public void setUrl(String url)
--- --- --- ### RecommendationViewEvent Class model for _recommendation_ events. **Declared In:** `com.synerise.sdk.event.model.ai.RecommendationViewEvent` **Declaration:**
```Java public class RecommendationViewEvent extends Event ```
```Kotlin class RecommendationViewEvent : Event ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **productId** | String | no | - | Product ID. If this parameter is used, it is translated into a single-item `items` list automatically. If `items` is used, this parameter should be omitted. | | **items** | `List` | no | - | List of product IDs. If `productId` is used to define a single item in the event, this parameter should be omitted. | | **correlationId** | String | no | - | Correlation ID of the recommendation | | **campaignId** | String | no | - | Campaign ID | | **campaignHash** | String | no | - | Campaign hash |
The `"items"`, `"correlationId"`, `"category"`, `"url"`, `"campaignId"` , `"campaignHash"` keys are reserved by Synerise in params.
**Initializers:**
public RecommendationViewEvent(@NonNull String productId, @NonNull String correlationId,
                                   @NonNull String campaignId, @NonNull String campaignHash)

public RecommendationViewEvent(@NonNull String label, @NonNull String productId, @NonNull String correlationId,
                                   @NonNull String campaignId, @NonNull String campaignHash, @Nullable TrackerParams params)
    
public RecommendationViewEvent(@NonNull List<String> items, @NonNull String correlationId,
                                   @NonNull String campaignId, @NonNull String campaignHash)

public RecommendationViewEvent(@NonNull String label, @NonNull List<String> items, @NonNull String correlationId,
                                   @NonNull String campaignId, @NonNull String campaignHash, @Nullable TrackerParams params)
**Methods:** This method defines the value of the `category` parameter.
public void setCategory(String category)
--- This method defines the value of the `url` parameter.
public void setUrl(String url)
--- --- --- ### RecommendationSeenEvent Class model for _recommendation seen_ event. **Declared In:** `com.synerise.sdk.event.model.ai.RecommendationSeenEvent` **Declaration:**
```Java public class RecommendationSeenEvent extends RecommendationEvent ```
```Kotlin class RecommendationSeenEvent : RecommendationEvent ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **name** | String | no | - | Product name | | **productId** | String | no | - | Product ID | | **campaignId** | String | no | - | Recommendation campaign ID | | **campaignHash** | String | no | - | Recommendation campaign hash | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hubs. It isn't shown on a Profile card. | | **params** | TrackerParams | yes | - | Event tracker params |
The `"productId"`, `"name"`, `"category"`, `"url"`, `"campaignId"` , `"campaignHash"` keys are reserved by Synerise in params.
**Initializers:** The following constructors are available:
public RecommendationSeenEvent(@NonNull String label, @NonNull String productId, @NonNull String name,
                                   @NonNull String campaignId, @NonNull String campaignHash)
public RecommendationSeenEvent(@NonNull String label, @NonNull String productId, @NonNull String name,
                                   @NonNull String campaignId, @NonNull String campaignHash, @Nullable TrackerParams params)
**Methods:** There are no methods. --- --- ### RecommendationClickEvent Class model for _recommendation click_ event. **Declared In:** `com.synerise.sdk.event.model.ai.RecommendationClickEvent` **Declaration:**
```Java public class RecommendationClickEvent extends RecommendationEvent ```
```Kotlin class RecommendationClickEvent : RecommendationEvent ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **name** | String | no | - | Product name | | **productId** | String | no | - | Product ID | | **campaignId** | String | no | - | Recommendation campaign ID | | **campaignHash** | String | no | - | Recommendation campaign hash | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hubs. It isn't shown on a Profile card. | | **params** | TrackerParams | yes | - | Event tracker params |
The `"productId"`, `"name"`, `"category"`, `"url"`, `"campaignId"` , `"campaignHash"` keys are reserved by Synerise in params.
**Initializers:** The following constructors are available:
public RecommendationClickEvent(@NonNull String label, @NonNull String productId, @NonNull String name,
                                    @NonNull String campaignId, @NonNull String campaignHash)
public RecommendationClickEvent(@NonNull String label, @NonNull String productId, @NonNull String name,
                                    @NonNull String campaignId, @NonNull String campaignHash, @Nullable TrackerParams params)
**Methods:** There are no methods. --- --- ### VisitedScreenEvent Class model for _visited screen_ event. **Declared In:** `com.synerise.sdk.event.model.interaction.VisitedScreenEvent` **Declaration:**
```Java public class VisitedScreenEvent extends Event ```
```Kotlin class VisitedScreenEvent : Event ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hubs. It isn't shown on a Profile card. | | **params** | TrackerParams | yes | - | Event tracker params | **Initializers:** The following constructors are available:
public VisitedScreenEvent(@NonNull String label)
public VisitedScreenEvent(@NonNull String label, @Nullable TrackerParams params)
**Methods:** There are no methods. --- --- ### HitTimerEvent Class model for _hit timer_ event. Record a "customer hit timer" event. This could be used for profiling or activity time monitoring - you can send "hit timer" when your customer starts doing something and send it once again when they finish, but this time with a different time signature. Then you can use [Decision Hub](/docs/analytics) to measure, for example, average activity time. **Declared In:** `com.synerise.sdk.event.model.interaction.HitTimerEvent` **Declaration:**
```Java public class HitTimerEvent extends Event ```
```Kotlin class HitTimerEvent : Event ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hubs. It isn't shown on a Profile card. | | **params** | TrackerParams | yes | - | Event tracker params | **Initializers:** The following constructors are available:
public HitTimerEvent(@NonNull String label)
public HitTimerEvent(@NonNull String label, @Nullable TrackerParams params)
**Methods:** There are no methods. --- --- ### SearchedEvent Class model for _client searched_ event. **Declared In:** `com.synerise.sdk.event.model.interaction.SearchedEvent` **Declaration:**
```Java public class SearchedEvent extends Event ```
```Kotlin class SearchedEvent : Event ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hubs. It isn't shown on a Profile card. | | **params** | TrackerParams | yes | - | Event tracker params | **Initializers:** The following constructors are available:
public SearchedEvent(@NonNull String label)
public SearchedEvent(@NonNull String label, @Nullable TrackerParams params)
**Methods:** There are no methods. --- --- ### SharedEvent Class model for _client shared_ event. **Declared In:** `com.synerise.sdk.event.model.interaction.SharedEvent` **Declaration:**
```Java public class SharedEvent extends Event ```
```Kotlin class SharedEvent : Event ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hubs. It isn't shown on a Profile card. | | **params** | TrackerParams | yes | - | Event tracker params | **Initializers:** The following constructors are available:
public SharedEvent(@NonNull String label)
public SharedEvent(@NonNull String label, @Nullable TrackerParams params)
**Methods:** There are no methods. --- --- ### AppearedInLocationEvent Class model for _appeared in location_ event. **Declared In:** `com.synerise.sdk.event.model.interaction.AppearedInLocationEvent` **Declaration:**
```Java public class AppearedInLocationEvent extends Event ```
```Kotlin class AppearedInLocationEvent : Event ```
This event will be transformed into `client.location` in the database.
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hub. It isn't shown on a Profile card. | | **params** | TrackerParams | yes | - | Event tracker params | | **lon** | Double | no | - | Longitude | | **lat** | Double | no | - | Latitude |
The `"lat"` and `"lon"` keys are reserved by Synerise in params.
**Initializers:** The following constructors are available:
public AppearedInLocationEvent(@NonNull String label, double lat, double lon)
public AppearedInLocationEvent(@NonNull String label, double lat, double lon, @Nullable TrackerParams params)
**Methods:** There are no methods. --- --- ### CrashEvent Class model for _crash_ event. **Declared In:** `com.synerise.sdk.event.model.crash.CrashEvent` **Declaration:**
```Java public class CrashEvent extends Event ```
```Kotlin class CrashEvent : Event ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **label** | String | no | - | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hub. It isn't shown on a Profile card. | | **params** | TrackerParams | yes | - | Event tracker params | **Initializers:** There is a constructor.
public CrashEvent(@NonNull String label, @NonNull TrackerParams params)
**Methods:** There are no methods. # Customer authentication ## Set Client State Change listener --- Set your own ClientStateChangeListener to get optional callbacks. **Method name:** Client.setOnClientStateChangeListener(listener); **Declaration:**
```Java public static void setOnClientStateChangeListener(OnClientStateChangeListener listener) ```
```Kotlin fun setOnClientStateChangeListener(listener:OnClientStateChangeListener) ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **listener** | OnClientStateChangeListener | yes | - | interface to handle client state change | **Return Value:** No value is returned. **Example:**
```Java Client.setOnClientStateChangeListener(listener); ```
```Kotlin Client.setOnClientStateChangeListener(listener) ```
## Remove Client State Change listener --- Remove your own ClientStateChangeListener. **Method name:** Client.removeClientStateChangeListener(); **Declaration:**
```Java public static void removeClientStateChangeListener() ```
```Kotlin fun removeClientStateChangeListener() ```
**Parameters:** No parameters required. **Return Value:** No value is returned. **Example:**
```Java Client.removeClientStateChangeListener(); ```
```Kotlin Client.removeClientStateChangeListener() ```
## Register customer account --- This method registers a new customer with an email, password, and optional data. This method requires the context object with a customer’s email, password, and optional data. Omitted fields are not modified. Depending on the backend configuration, the account may require activation. For details, see [customer registration](/developers/mobile-sdk/user-identification-and-authorization/overview). Do not allow signing in again (or signing up) when a customer is already signed in. Sign the customer out first. Do not create multiple instances nor call this method multiple times before execution. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_REGISTER_CLIENT_CREATE` permission from the **Client** group.
**Method name:** Client.registerAccount(registerClient) **Declaration:**
```Java public static IApiCall registerAccount(@NonNull RegisterClient registerClient) ```
```Kotlin fun registerAccount(registerClient: RegisterClient): IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | | --- | --- | --- | --- | | **registerClient** | [RegisterClient](/developers/mobile-sdk/class-reference/android/client#registerclient) | yes | - | **Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```Java private IApiCall signUpCall; private void signUp(RegisterClient registerClient) { if (signUpCall != null) signUpCall.cancel(); signUpCall = Client.registerAccount(registerClient); signUpCall.onSubscribe(() -> toggleLoading(true)) .doFinally(() -> toggleLoading(false)) .execute(this::onSignUpSuccessful, this::onSignUpFailure); } ```
```Kotlin private var signUpCall: IApiCall private fun signUp(registerClient: RegisterClient) { signUpCall!!.cancel() signUpCall = Client.registerAccount(registerClient) signUpCall!!.onSubscribe({ toggleLoading(true) }) .doFinally({ toggleLoading(false) }) .execute(({ this.onSignUpSuccessful() }), ({ this.onSignUpFailure() })) } ```
## Request customer account activation --- This method requests sending an email with a URL that confirms the registration and activates the account. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_CONFIRMATION_CLIENT_CREATE` permission from the **Client** group.
**Method name:** Client.requestAccountActivation(email) **Declaration:**
```java public static IApiCall requestAccountActivation(String email) ```
```kotlin fun requestAccountActivation(email: String): IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | String | yes | - |Customer's email| **Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```java private IApiCall call; if (call != null) call.cancel(); call = Client.requestAccountActivation(email); call.execute(this::onSuccess, this::onError); ```
```kotlin private val call: IApiCall? = null call.cancel(); call = Client.requestAccountActivation(email); call.execute(this::onSuccess, this::onError); ```
## Confirm customer account activation --- This method confirms a customer account with the confirmation token. This method is a global operation and doesn't require customer authentication.
Returns the HTTP 400 status code if the account is already confirmed or 404 if the account does not exist.
The API key must have the `SAUTH_CONFIRMATION_CLIENT_CREATE` permission from the **Client** group.
**Method name:** Client.confirmAccountActivation(token) **Declaration:**
```java public static IApiCall confirmAccountActivation(String token) ```
```kotlin fun confirmAccountActivation(token: String): IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **token** | String | yes | - | Customer's token | **Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```java private IApiCall call; if (call != null) call.cancel(); call = Client.confirmAccountActivation(token); call.execute(this::onSuccess, this::onError); ```
```kotlin private val call: IApiCall? = null call.cancel(); call = Client.confirmAccountActivation(token); call.execute(this::onSuccess, this::onError); ```
## Request customer account activation by pin --- This method requests a customer's account registration process with the PIN code. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_PIN_CODE_RESEND_CLIENT_CREATE` permission from the **Client** group.
**Method name:** Client.requestAccountActivationByPin(email) **Declaration:**
```Java public static IApiCall requestAccountActivationByPin(String email) ```
```Kotlin fun requestAccountActivationByPin(email:String):IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | String | yes | - | Email to which the pinCode will be sent | **Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```Java IApiCall apiCall; apiCall = Client.requestAccountActivationByPin(email); apiCall.execute(this::onSuccess, this::onFailure); ```
```Kotlin val apiCall:IApiCall apiCall = Client.requestAccountActivationByPin(email) apiCall.execute(({ this.onSuccess() }), ({ this.onFailure() })) ```
## Confirm customer account activation by pin --- This method confirms a customer's account registration process with the PIN code. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_PIN_CODE_RESEND_CLIENT_CREATE` permission from the **Client** group.
**Method name:** Client.confirmAccountActivationByPin(pinCode, email) **Declaration:**
```Java public static IApiCall confirmAccountActivationByPin(String pinCode, String email) ```
```Kotlin fun confirmAccountActivationByPin(pinCode: String, email:String):IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **pinCode** | String | yes | - | Code sent to the customer's email | | **email** | String | yes | - | Email used in the registration process | **Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```Java IApiCall apiCall; apiCall = Client.confirmAccountActivationByPin(pinCode, email); apiCall.execute(this::onSuccess, this::onFailure); ```
```Kotlin val apiCall:IApiCall apiCall = Client.confirmAccountActivationByPin(pinCode, email) apiCall.execute(({ this.onSuccess() }), ({ this.onFailure() })) ```
## Sign in a customer --- This method signs a customer in to obtain a JSON Web Token (JWT) which can be used in subsequent requests. The SDK will refresh the token before each call if it is about to expire (but not expired). Do NOT allow signing in again (or signing up) when a customer is already signed in. First, sign the customer out. Do NOT create multiple instances nor call this method multiple times before execution. **Method name:** Client.signIn(email, password) **Declaration:**
```Java public static IApiCall signIn(@NonNull String email, @NonNull String password) ```
```Kotlin fun signIn(email: String, password: String): IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | String | yes | - | Customer's email | | **password** | String | yes | - | Customer's password | **Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```Java private IApiCall signInCall; private void signIn(String login, String password) { if (signInCall != null) signInCall.cancel(); signInCall = Client.signIn(login, password); signInCall.onSubscribe(() -> toggleLoading(true)) .execute(() -> onSignInSuccessful(login), () -> onSignInFailure()); } ```
```Kotlin private var signInCall: IApiCall private fun signIn(login: String, password: String) { signInCall!!.cancel() signInCall = Client.signIn(login, password) signInCall!!.onSubscribe({ toggleLoading(true) }) .execute({ onSignInSuccessful(login) }, { onSignInFailure() }) } ```
## Sign in a customer conditionally --- This method signs a customer in to obtain a JSON Web Token (JWT) which can be used in subsequent requests. The SDK will refresh the token before each call if it is about to expire (but not expired). Do NOT allow signing in again (or signing up) when a customer is already signed in. First, sign the customer out. Do NOT create multiple instances nor call this method multiple times before execution. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | **Method name:** Client.signInConditionally(email, password) **Declaration:**
```java public static IDataApiCall signInConditionally(@NonNull String email, @NonNull String password) ```
```kotlin fun signInConditionally( email: String, password: String, ): IDataApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | String | yes | - | Client's email | | **password** | String | yes | - | Client's password | **Return Value:** IDataApiCall<[AuthConditions](/developers/mobile-sdk/class-reference/android/client#authconditions)> object to execute the request. **Example:**
```java private IDataApiCall call; if (call != null) call.cancel(); call = Client.signInConditionally(email, password)); call.execute(this::onSuccess, this::onFailure); ```
```kotlin val call:IDataApiCall call.cancel() call = Client.signInConditionally(email, password) call.execute(({ this.onSuccess() }), ({ this.onFailure() })) ```
## Authenticate customer by IdentityProvider --- This method authenticates a customer with OAuth, Facebook, Google, Apple, or Synerise. If an account for the customer does not exist and the identity provider is different than Synerise, this request creates an account. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.7.6 | 3.8.0 | 0.9.19 | 0.3.0 | **Method name:** Client.authenticate(token, clientIdentityProvider, agreements, attributes, authId) **Declaration:**
```java public static IApiCall authenticate(String token, ClientIdentityProvider provider, Agreements agreements, Attributes attributes, String authId) ```
```kotlin fun authenticate( token: String, provider: ClientIdentityProvider, agreements: Agreements?, attributes: Attributes?, authId: String? ): IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **token** | String | yes | - | Token retrieved from provider | | **provider** | [ClientIdentityProvider](/developers/mobile-sdk/class-reference/android/client#clientidentityprovider) | yes | - | Provider of your token | | **agreements** | [Agreements](/developers/mobile-sdk/class-reference/android/client#agreements) | no | - | Optional agreements | | **attributes** | [Attributes](/developers/mobile-sdk/class-reference/android/client#attributes) | no | - | Optional attributes | | **authId** | String | no | - | Optional identifier of authorization |
**authId** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```java private IApiCall call; if (call != null) call.cancel(); call = Client.authenticate(token, provider, null, null, null); call.execute(this::onSuccess, this::onFailure); ```
```kotlin val call:IApiCall call.cancel() call = Client.authenticate(token, provider, null, null, null) call.execute(({ this.onSuccess() }), ({ this.onFailure() })) ```
## Authenticate customer conditionally by IdentityProvider --- This method authenticates a customer with OAuth, Facebook, Google, Apple, or Synerise. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | **Method name:** Client.authenticateConditionally(token, clientIdentityProvider, agreements, attributes, authId) **Declaration:**
```java public static IDataApiCall authenticateConditionally(@NonNull String token, @NonNull ClientIdentityProvider provider, @Nullable Agreements agreements, @Nullable Attributes attributes, @Nullable String authId) ```
```kotlin fun authenticateConditionally( token: String, provider: ClientIdentityProvider, agreements: Agreements?, attributes: Attributes?, authId: String? ): IDataApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **token** | String | yes | - | Token retrieved from provider | | **provider** | [ClientIdentityProvider](/developers/mobile-sdk/class-reference/android/client#clientidentityprovider) | yes | - | Provider of your token | | **agreements** | [Agreements](/developers/mobile-sdk/class-reference/android/client#agreements) | no | - | Optional agreements | | **attributes** | [Attributes](/developers/mobile-sdk/class-reference/android/client#attributes) | no | - | Optional attributes | | **authId** | String | no | - | Optional identifier of authorization |
**authId** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** IDataApiCall<[AuthConditions](/developers/mobile-sdk/class-reference/android/client#authconditions)> object to execute the request. **Example:**
```java private IDataApiCall call; if (call != null) call.cancel(); call = Client.authenticateConditionally(token, clientIdentityProvider, agreements, attributes, authId)); call.execute(this::onSuccess, this::onFailure); ```
```kotlin val call:IDataApiCall call.cancel() call = Client.authenticateConditionally(token, clientIdentityProvider, agreements, attributes, authId) call.execute(({ this.onSuccess() }), ({ this.onFailure() })) ```
## Authenticate customer with token payload --- This method signs in a customer in with the provided token payload. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.15.0 | 5.15.0 | n/a | n/a | **Method name:** Client.authenticateWithTokenPayload() **Declaration:**
```Java public static IApiCall authenticateWithTokenPayload(TokenPayload tokenPayload, @NonNull String authId) ```
```Kotlin fun authenticateWithTokenPayload( tokenPayload: TokenPayload, authId: String ): IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **tokenPayload** | [TokenPayload](/developers/mobile-sdk/class-reference/android/client#tokenpayload) | yes | - | Object which contains a token's payload | | **authId** | String | yes | - | Required customer's identifier of authorization |
**authId** parameter is used for decreasion the number of UUID refreshes so it must be unique for every customer.
**Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```java private IApiCall call; if (call != null) call.cancel(); call = Client.authenticateWithTokenPayload(tokenPayload, authId); call.execute(this::onSuccess, this::onFailure); ```
```kotlin val call:IApiCall call.cancel() call = Client.authenticateWithTokenPayload(tokenPayload, authId) call.execute(({ this.onSuccess() }), ({ this.onFailure() })) ```
## Authenticate customer via Simple Profile Authentication --- This method authenticates a customer with Simple Profile Authentication. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.14.0 | 5.7.1 | 0.15.0 | 0.7.0 |
When you use this method, you must set a request validation salt by using the `Synerise.setRequestValidationSalt(_:)` method (if salt is enabled for Simple Profile Authentication).
The API key must have the `SAUTH_SIMPLE_AUTH_CREATE` from the **Auth** group.
**Method name:** Client.simpleAuthentication(clientData, authId) **Declaration:**
```java public static IApiCall simpleAuthentication(ClientData clientData, String authId) ```
```kotlin fun simpleAuthentication( clientData: ClientData, authId: String ): IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **clientData** | [ClientData](/developers/mobile-sdk/class-reference/android/client#clientdata) | yes | - | Object which contains customer data | | **authId** | String | yes | - | Required identifier of authorization |
**authId** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. ## Check if a customer is signed in (via RaaS, OAuth, Facebook, Apple) --- This method checks if a customer is signed in (via Synerise Authentication - RaaS, OAuth, Facebook, Apple). **Method name:** Client.isSignedIn() **Declaration:**
```Java public static boolean isSignedIn() ```
```Kotlin fun isSignedIn():Boolean ```
**Parameters:** No parameters. **Return Value:** Boolean defining whether a customer is signed in or not. **Example:**
```Java boolean isSignedIn = Client.isSignedIn() ```
```Kotlin var isSignedIn = Client.isSignedIn() ```
## Check if a customer is signed in (via Simple Profile Authentication) --- This method checks if a customer is signed in (via Simple Profile Authentication). | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.14.0 | 5.7.1 | 0.15.0 | 0.7.0 | **Method name:** Client.isSignedIn() **Declaration:**
```Java public static boolean isSignedInViaSimpleAuthentication() ```
```Kotlin fun isSignedInViaSimpleAuthentication():Boolean ```
**Parameters:** No parameters. **Return Value:** **true** if the customer is signed in (via Simple Profile Authentication), otherwise returns **false**. **Example:**
```Java boolean isSignedInViaSimpleAuthentication = Client.isSignedInViaSimpleAuthentication() ```
```Kotlin var isSignedInViaSimpleAuthentication = Client.isSignedInViaSimpleAuthentication() ```
## Sign out customer --- This method signs out a customer out.
This method works with every authentication type (via Synerise, External Provider, OAuth or Simple Profile Authentication).
**Method name:** Client.signOut() **Declaration:**
```Java public static void signOut() ```
```Kotlin fun signOut() ```
**Parameters:** No parameters. **Return Value:** Nothing is returned. **Example:**
```Java Client.signOut(); ```
```Kotlin Client.signOut(); ```
## Sign out customer with mode or from all devices --- This method signs out a customer out with a chosen mode and Determines if the method should sign out all devices. Available modes: - `.signOut` mode signs out the customer. - `.signOutWithSessionDestroy` mode signs out the customer and additionally, clears the anonymous session and regenerates the customer UUID. The `fromAllDevices` parameter determines whether the method should notify the backend to sign out all devices. **IMPORTANT: It is an asynchronous method.** | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.11.0 | 5.1.0 | 0.14.0 | 1.0.0 |
This method works with every authentication type (via Synerise, External Provider, OAuth or Simple Profile Authentication).
**Class:** [Client](/developers/mobile-sdk/class-reference/android/modules#client) **Declaration:**
```java public static IApiCall signOut(ClientSignOutMode mode, Boolean signOutFromAllDevices) ```
```kotlin fun signOut(mode: ClientSignOutMode, signOutFromAllDevices: Boolean): IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **mode** | [ClientSignOutMode](/developers/mobile-sdk/class-reference/android/client#clientsignoutmode) | yes | - | Client sign out mode | | **signOutFromAllDevices** | Boolean | yes | - | Determines if the method should sign out all devices | **Return Value:** Nothing is returned. **Example:**
```java private IApiCall signOutCall; private void signOut() { if (signOutCall != null) signOutCall.cancel(); signOutCall = Client.signOut(ClientSignOutMode.SIGN_OUT_WITH_SESSION_CLEARING, true); signOutCall.onSubscribe(() -> toggleLoading(true)) .execute(() -> onSignOutSuccessful(login), () -> onSignOutFailure()); } ```
```kotlin private var signOutCall: IApiCall private fun signOut(login: String, password: String) { signOutCall!!.cancel() signOutCall = Client.signOut(.SIGN_OUT_WITH_SESSION_CLEARING, true) signOutCall!!.onSubscribe({ toggleLoading(true) }) .execute({ onSignOutSuccessful(login) }, { onSignOutFailure() }) } ```
## Removed methods ### Authenticate customer by OAuth with registration {#authenticate-customer-by-oauth-with-registration} --- This method authenticates a customer with OAuth. If an account for the customer does not exist, this request creates an account. | Available on | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.11 | 3.6.13 | 0.9.12 | n/a | | Deprecated in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | n/a |
Returns the HTTP 401 status code if the provided access token and/or API Key is invalid.
**Method name:** Client.authenticateByOAuth(accessToken, agreements, attributes, authId) **Declaration:**
```java public static IApiCall authenticateByOAuth(@NonNull String accessToken, @Nullable Agreements agreements, @Nullable Attributes attributes, @Nullable String authId) ```
```kotlin fun authenticateByOAuth( accessToken: String, agreements: Agreements?, attributes: Attributes?, authId: String? ): IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **accessToken** | String | yes | - | OAuth Access Token | | **agreements** | [Agreements](/developers/mobile-sdk/class-reference/android/client#agreements) | no | --- | Optional agreements | | **attributes** | [Attributes](/developers/mobile-sdk/class-reference/android/client#attributes) | no | --- | Optional attributes | | **authId** | String | no | --- | Optional identifier of authorization |
**authId** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```java private IApiCall call; if (call != null) call.cancel(); call = Client.authenticateByOAuth(token, null, null, null); call.execute(this::onSuccess, this::onFailure); ```
```kotlin val call:IApiCall call.cancel() call = Client.authenticateByOAuth(token, null, null, null) call.execute(({ this.onSuccess() }), ({ this.onFailure() })) ```
### Authenticate customer by OAuth without registration {#authenticate-customer-by-oauth-without-registration} --- This method authenticates a customer with OAuth. | Available on | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.11 | 3.6.13 | 0.9.12 | n/a | | Deprecated in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | n/a |
Returns the HTTP 401 status code if the provided access token and/or API Key is invalid.
**Method name:** Client.authenticateByOAuthIfRegistered(accessToken, authId) **Declaration:**
```java public static IApiCall authenticateByOAuthIfRegistered(@NonNull String accessToken, @Nullable String authId) ```
```kotlin fun authenticateByOAuthIfRegistered( accessToken: String, authId: String? ): IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **accessToken** | String | yes | - | OAuth Access Token | | **authId** | String | no | --- | Optional identifier of authorization |
**authId** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```java private IApiCall call; if (call != null) call.cancel(); call = Client.authenticateByOAuthIfRegistered(token, null); call.execute(this::onSuccess, this::onFailure); ```
```kotlin val call:IApiCall call.cancel() call = Client.authenticateByOAuthIfRegistered(token, null) call.execute(({ this.onSuccess() }), ({ this.onFailure() })) ```
### Authenticate customer by Facebook with registration {#authenticate-customer-by-facebook-with-registration} --- This method authenticates a customer with Facebook. If an account for the customer does not exist, this request creates an account. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.3.8 | 3.3.0 | 0.9.7 | n/a | | Deprecated in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | n/a |
Returns the HTTP 401 status code if the provided Facebook token and/or API Key is invalid.
**Method name:** Client.authenticateByFacebook(facebookToken, agreements, attributes, authId) **Declaration:**
```java public static IApiCall authenticateByFacebook(@NonNull String facebookToken, @Nullable Agreements agreements, @Nullable Attributes attributes, @Nullable String authId) ```
```kotlin fun authenticateByFacebook( facebookToken: String, agreements: Agreements?, attributes: Attributes?, authId: String? ): IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **facebookToken** | String | yes | - | Facebook Access Token | | **agreements** | [Agreements](/developers/mobile-sdk/class-reference/android/client#agreements)| no | --- | Marketing agreements | | **attributes** | [Attributes](/developers/mobile-sdk/class-reference/android/client#attributes) | no | --- | Additional attributes | | **authId** | String | no | --- | Optional identifier of authorization |
**authId** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```Java private IApiCall signInFacebookCall; private void signInFacebook(String facebookToken) { if (signInFacebookCall != null) signInFacebookCall.cancel(); signInFacebookCall = Client.authenticateByFacebook(facebookToken, null, null, null); signInFacebookCall.onSubscribe(() -> toggleFacebookLoading(true)) .execute(this::onSignInFacebookSuccess, this::onSignInFacebookError); } ```
```Kotlin private var signInFacebookCall: IApiCall? = null private fun signInFacebook(facebookToken: String) { if (signInFacebookCall != null) signInFacebookCall!!.cancel() signInFacebookCall = Client.authenticateByFacebook(facebookToken, null, null, null) signInFacebookCall!!.onSubscribe({ toggleFacebookLoading(true) }) .execute(({ this.onSignInFacebookSuccess() }), ({ this.onSignInFacebookError() })) } ```
### Authenticate customer by Facebook without registration {#authenticate-customer-by-facebook-without-registration} --- This method authenticates a customer with Facebook. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.3.8 | 3.3.0 | 0.9.7 | n/a | | Deprecated in: | 3.7.6 | 3.8.0 | 0.9.19 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | n/a |
Returns the HTTP 401 status code if the provided Facebook token and/or API Key is invalid.
**Method name:** Client.authenticateByFacebookRegistered(facebookToken, authId) **Declaration:**
```java public static IApiCall authenticateByFacebookRegistered(@NonNull String facebookToken, @Nullable String authId) ```
```kotlin fun authenticateByFacebookRegistered(facebookToken: String, authId: String?): IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **facebookToken** | String | yes | - | Facebook Access Token| | **authId** | String | no | --- | Optional identifier of authorization |
**authId** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```java private IApiCall signInFacebookRegisteredCall; private void signInFacebookRegistered(String facebookToken) { if (signInFacebookRegisteredCall != null) signInFacebookRegisteredCall.cancel(); signInFacebookRegisteredCall = Client.authenticateByFacebookRegistered(facebookToken, null); signInFacebookRegisteredCall.onSubscribe(() -> toggleFacebookLoading(true)) .execute(this::onSignInFacebookSuccess, this::onSignInFacebookError); } ```
```kotlin private var signInFacebookRegisteredCall: IApiCall? = null private fun signInFacebook(facebookToken: String) { signInFacebookRegisteredCall!!.cancel() signInFacebookRegisteredCall = Client.authenticateByFacebookRegistered(facebookToken, null) signInFacebookRegisteredCall!!.onSubscribe({ toggleFacebookLoading(true) }) .execute(({ this.onSignInFacebookSuccess() }), ({ this.onSignInFacebookError() })) } ```
### Sign out customer with mode {#sign-out-customer-with-mode} --- This method signs out a customer out with a chosen mode: - `.signOut` mode notifies the backend that the customer is signed out. - `.signOutWithSessionDestroy` mode notifies the backend that the customer is signed out and additionally, clears the anonymous session and regenerates the customer UUID. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.4.0 | 4.6.0 | 0.12.0 | 0.7.0 | | Deprecated in: | 4.11.0 | 5.1.0 | - | - | | Removed in: | 5.0.0 | 6.0.0 | 0.14.0 | 1.0.0 |
This method works with every authentication type (via Synerise, External Provider, OAuth or Simple Profile Authentication).
**Class:** [Client](/developers/mobile-sdk/class-reference/android/modules#client) **Declaration:**
```java public static void signOut(ClientSignOutMode mode) ```
```kotlin fun signOut() ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **mode** | [ClientSignOutMode](/developers/mobile-sdk/class-reference/android/client#clientsignoutmode) | yes | - | Client sign out mode | **Return Value:** Nothing is returned. **Example:**
```Java Client.signOut(mode); ```
```Kotlin Client.signOut(mode); ```
# React Native ## Configuring push notifications (React Native) ### Configuring Firebase --- Google Firebase Cloud Messaging is necessary to handle [push notifications](/docs/campaign/Mobile) sent from Synerise. 1. Follow the instructions in [this article](https://firebase.google.com/docs/storage/ios/start). 2. Integrate the Firebase project with Synerise. See [this article](/docs/settings/tool/firebase). ### Setting up - Android {id=setting-up-android} --- #### Requirements {id=android-requirements} After configuring Firebase, add the `google-services.json` file to your project/android/app catalog. #### Firebase Cloud Messaging integration {id=android-firebase-cloud-messaging-integration} 1. Add the google-services dependency to your project's `build.gradle` file.
dependencies {
             ...
             classpath 'com.google.gms:google-services:4.3.3'
             ...
         }
2. Configure the application's `build.gradle` as follows:
dependencies {
         implementation fileTree(dir: "libs", include: ["*.jar"])
         implementation "com.facebook.react:react-native:+"  // from node_modules

         // FCM
         implementation "com.google.firebase:firebase-messaging:20.0.1"
         implementation "com.google.android.gms:play-services-base:17.1.0"
         implementation "com.google.firebase:firebase-core:17.2.1"
         implementation "com.google.firebase:firebase-analytics:17.2.1"
             ...
         }
1. Make sure that at the end of the application gradle file, you add plugin: 'com.google.gms.google-services' 1. In your MainApplication class, include `setPushListener` to listen for the changes of the Firebase token.
```Java @Override public void onCreate() { super.onCreate(); SoLoader.init(this, /* native exopackage */ false); getReactNativeHost().getReactInstanceManager().createReactContextInBackground(); RNNotifications.setPushListener(new OnRegisterPushListener() { @Override public void onRegisterPushRequired() { FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener(instanceIdResult -> { String refreshedToken = instanceIdResult.getToken(); Log.d(TAG, "Refreshed token: " + refreshedToken); RNNotifications.setRegistrationToken(refreshedToken); }); } }); } ```
```Kotlin fun onCreate() { super.onCreate() SoLoader.init(this, /* native exopackage */ false) getReactNativeHost().getReactInstanceManager().createReactContextInBackground() RNNotifications.setPushListener(object:OnRegisterPushListener() { fun onRegisterPushRequired() { FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener({ instanceIdResult-> val refreshedToken = instanceIdResult.getToken() Log.d(TAG, "Refreshed token: " + refreshedToken) RNNotifications.setRegistrationToken(refreshedToken) }) } }) } ```
#### Receiving push notifications {id=android-receiving-push-notifications} In order to handle Synerise push notifications, you must pass the incoming push payload to the Synerise SDK. 1. Create a class extending `FirebaseMessagingService`:
```Java public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = MyFirebaseMessagingService.class.getSimpleName(); @Override public void onMessageReceived(@NonNull RemoteMessage remoteMessage) { super.onMessageReceived(remoteMessage); Map data = remoteMessage.getData(); RNNotifications.onNotificationReceive(data); } @Override public void onNewToken(String refreshedToken) { super.onNewToken(refreshedToken); Log.d(TAG, "Refreshed token: " + refreshedToken); if (refreshedToken != null) { RNNotifications.setRegistrationToken(refreshedToken); } } } ```
```Kotlin class MyFirebaseMessagingService:FirebaseMessagingService() { fun onMessageReceived(@NonNull remoteMessage:RemoteMessage) { super.onMessageReceived(remoteMessage) val data = remoteMessage.getData() RNNotifications.onNotificationReceive(data) } fun onNewToken(refreshedToken:String) { super.onNewToken(refreshedToken) Log.d(TAG, "Refreshed token: " + refreshedToken) if (refreshedToken != null) { RNNotifications.setRegistrationToken(refreshedToken) } } } ```
1. To enable banners, handle the intent when the app starts. You can do it in your `MainActivity` by calling `RNNotifications.onNotificationReceive` in your `onCreate` and `onNewIntent`.
```Java @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); RNNotifications.onNotificationReceive(getIntent().getExtras()); } @Override public void onNewIntent(Intent intent) { super.onNewIntent(intent); RNNotifications.onNotificationReceive(intent.getExtras()); } ```
```Kotlin protected fun onCreate(savedInstanceState:Bundle) { super.onCreate(savedInstanceState) RNNotifications.onNotificationReceive(getIntent().getExtras()) } fun onNewIntent(intent:Intent) { super.onNewIntent(intent) RNNotifications.onNotificationReceive(intent.getExtras()) } ```
### Setting up - iOS {id=setting-up-ios} --- #### Requirements {id=ios-requirements} Configure handling Push Notifications in your application. See [Apple Notifications](https://developer.apple.com/notifications/). #### Firebase Cloud Messaging integration {id=ios-firebase-cloud-messaging-integration} 1. Import `RNNotifications.h`
```Swift import react-native-synerise-sdk ```
```Objective-C #import ```
2. Extend the Firebase Messaging Delegate so our SDK can receive the Firebase token that is required to deliver push notifications from Synerise.
```Swift func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { FirebaseApp.configure() Messaging.messaging().delegate = self if #available(iOS 10, *) { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in } } else { let settings = UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil) application.registerUserNotificationSettings(settings) } application.registerForRemoteNotifications() } // MARK: - MessagingDelegate func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) { RNNotifications.didChangeRegistrationToken(fcmToken) } ```
```Objective-C - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [FIRApp configure]; [FIRMessaging messaging].delegate = self; if (@available(iOS 10, *)) { [UNUserNotificationCenter currentNotificationCenter].delegate = self; UNAuthorizationOptions authOptions = (UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge); [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:authOptions completionHandler:^(BOOL granted, NSError *error) { }]; } else { UIUserNotificationType allNotificationTypes = (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge); UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil]; [[UIApplication sharedApplication] registerUserNotificationSettings:settings]; } [[UIApplication sharedApplication] registerForRemoteNotifications]; } #pragma mark - FIRMessagingDelegate - (void)messaging:(FIRMessaging *)messaging didReceiveRegistrationToken:(NSString *)fcmToken { [RNNotifications didChangeRegistrationToken:fcmToken]; } ```
Make sure that the Firebase token is always up-to-date. When it changes, use `RNNotifications.didChangeRegistrationToken(registrationToken:)` again.
#### Receiving push notifications {id=ios-receiving-push-notifications} The following code shows how to receive push notifications in the `AppDelegate.h` and pass these to the React Native part of the application:
To properly receive notifications, all of these methods must be implemented.
```Swift // iOS 9 // Push Notifications // Silent Push Notifications func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { RNNotifications.didReceiveNotification(userInfo) completionHandler(.noData) } func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [AnyHashable : Any], completionHandler: @escaping () -> Void) { RNNotifications.didReceiveNotification(userInfo, actionIdentifier:identifier) completionHandler() } // iOS 10 and above // Push Notifications // MARK: - UNUserNotificationCenterDelegate @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { RNNotifications.didReceiveNotification(response.notification.request.content.userInfo, actionIdentifier:response.actionIdentifier) completionHandler() } @available(iOS 10.0, *) func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { RNNotifications.didReceiveNotification(notification.request.content.userInfo) completionHandler(UNNotificationPresentationOptions.init(rawValue: 0)) } ```
```Objective-C // iOS 9 // Push Notifications // Silent Push Notifications - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { [RNNotifications didReceiveNotification:userInfo]; completionHandler(UIBackgroundFetchResultNoData); } - (void)application:(UIApplication *)application handleActionWithIdentifier:(nullable NSString *)identifier forRemoteNotification:(NSDictionary *)userInfo completionHandler:(void(^)())completionHandler { [RNNotifications didReceiveNotification:userInfo actionIdentifier:identifier]; completionHandler(); } // iOS 10 and above // Push Notifications #pragma mark - UNUserNotificationCenterDelegate - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler NS_AVAILABLE_IOS(10) { [RNotifications didReceiveNotification:response.notification.request.content.userInfo actionIdentifier:response.actionIdentifier]; completionHandler(); } - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler NS_AVAILABLE_IOS(10) { [RNNotifications didReceiveNotification:notification.request.content.userInfo]; completionHandler(UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound); } ```
#### Extensions for push notifications {id=ios-extensions-for-push-notifications} ##### Notification Service Extension {id=synerise-notification-service-extension-for-ios} **Synerise Notification Service Extension** is an object that adds the notification functionality to the SDK. It implements the following operations: - Decrypting **Simple Push** communication data (if encryption is enabled). - Tracking events from **Simple Push** communication. - Adding action buttons to **Simple Push** communication (if the communication contains any). - Improving the appearance of **Simple Push** communication (Rich Media - Single Image) with an image thumbnail. **Notification Service Extension** should be implemented in the native part of the application. Follow the instructions in [this article](/developers/mobile-sdk/configuring-push-notifications/ios#synerise-notification-service-extension-configuration). ##### Rich Media Notification Content Extensions {id=synerise-notification-content-extension-for-ios} **Synerise Rich Media Notification Content Extension** is an object that allows rendering your own appearance of a push notification when the notification is expanded (by tapping the notification). **Synerise Rich Media Notification Content Extensions** should be implemented in the native part of the application. Follow the instructions in [this article](/developers/mobile-sdk/configuring-push-notifications/ios#rich-media-in-push-notifications). ### Set up Firebase FCM token registration for Synerise SDK --- Get Firebase FCM token from the native part of the application so our SDK can receive the Firebase token that is required to deliver push notifications from Synerise. Make sure that the Firebase FCM token is always up-to-date by implementing the [onRegistrationRequired()](/developers/mobile-sdk/listeners-and-delegates/react-native-listeners#notifications-listener) method.
```JavaScript Synerise.Notifications.setListener({ onRegistrationToken: function(token) { Synerise.Notifications.registerForNotifications(token, true, function() { // success }, function(error) { // failure }); }, onRegistrationRequired: function() { let registrationToken = getLastPushRegistrationToken(); let mobilePushAgreement = true; // true or false, should depend on device permissions and customer's agreement in the application Synerise.Notifications.registerForNotifications(registrationToken, mobilePushAgreement, function() { // success }, function(error) { // failure }); } //... }); ```
The second parameter of the registration method is the agreement for mobile push campaigns. In the Profile's card in Synerise, you can find it in the **Subscriptions** section (if you have the required access permission). Learn more about the [Synerise.Notifications.registerForNotifications(registrationToken:mobilePushAgreement:onSuccess:onError:) method in the method reference](/developers/mobile-sdk/method-reference/react-native/campaigns#register-for-push-notifications).
You must always keep the Firebase token updated. In many cases in the application lifecycle, such as authorization, destroy session, user context change, and so on, the registration needs to be updated. In these situations, the SDK invokes the [onRegistrationRequired()](/developers/mobile-sdk/listeners-and-delegates/react-native-listeners#notifications-listener) method (see code snippet above).
### Configure Notification Encryption --- #### Android {id=android-notification-encryption-configuration} See [Configure Notification Encryption](/developers/mobile-sdk/configuring-push-notifications/android#configure-notification-encryption). #### iOS {id=ios-notification-encryption-configuration} See [Synerise Notification Service Extension](#synerise-notification-service-extension-for-ios) and [Configure Notification Encryption](/developers/mobile-sdk/configuring-push-notifications/ios#configure-notification-encryption). #### Application implementation {id=application-notification-encryption-configuration} In the application, you must set `encryption` to `true` in the SDK initializer or in the SDK settings.
```JavaScript // The first way // WARNING: This option must be configured before Synerise SDK is initialized! Synerise.Settings.notifications.encryption = true; // The second way Synerise.Initializer() .withApiKey('XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX') .withBaseUrl(null) .withDebugModeEnabled(true) .withCrashHandlingEnabled(true) .withSettings({ notifications: { enabled: true, encryption: true } //... }) .init() ```
### Handling incoming push notifications ---
You may disable handling push notifications in the SDK at any time. See [Enable/disable notifications](/developers/mobile-sdk/settings#enabledisable-notifications).
#### Synerise payload The following code shows how to handle push notifications:
```JavaScript Synerise.Notifications.setListener({ //... onNotification: function(payload, actionIdentifier) { if (Synerise.Notifications.isSyneriseNotification(payload)) { Synerise.Notifications.handleNotification(payload, actionIdentifier); } } //... }); ```
#### Custom payload You may send both custom push notifications and custom campaigns in [Synerise](https://app.synerise.com). The code below of one sample delegate method checks the notification origin and then handles it.
```JavaScript Synerise.Notifications.setListener({ //... onNotification: function(payload, actionIdentifier) { if (Synerise.Notifications.isSyneriseNotification(payload)) { Synerise.Notifications.handleNotification(payload, actionIdentifier); } else { // Handle other notification in your own way } } //... }); ```
#### Encrypted payloads If you handle the Synerise notification, you do not have to do anything. The SDK decrypts Synerise notification's payload: - In [Notification Service Extension](#synerise-notification-service-extension-for-ios) for push notifications - In the SDK, after invoking [`Synerise.Notifications.handleNotification(payload, actionIdentifier)`](/developers/mobile-sdk/method-reference/react-native/campaigns#handle-synerise-push-notification) for silent push notifications Otherwise, if it is a custom encrypted push notification sent by Synerise, or you need decrypt data from the push notification, there are two methods for dealing with it: - [`Synerise.Notifications.isNotificationEncrypted(payload)`](/developers/mobile-sdk/method-reference/react-native/campaigns#check-if-push-notification-is-encrypted) - checks if the notification payload is encrypted by Synerise. - [`Synerise.Notifications.decryptNotification(payload)`](/developers/mobile-sdk/method-reference/react-native/campaigns#decrypt-push-notification) - decrypts a notification payload.
```JavaScript Synerise.onReady(function() { //... onNotification: function(payload, actionIdentifier) { if (Synerise.Notifications.isSyneriseNotification(payload)) { let isNotificationEncrypted = Synerise.Notifications.isNotificationEncrypted(payload) var decryptedPayload if (isNotificationEncrypted) { decryptedPayload = Synerise.Notifications.decryptNotification(payload) } else { decryptedPayload = payload } Synerise.Notifications.handleNotification(decryptedPayload, actionIdentifier) } } //... }) }) ```
The `Synerise.Notifications.decryptNotification(payload)` method returns raw data when the payload is not encrypted. If the operation fails, the method returns null.
### Handling actions from push notifications --- - [Read more about types of actions in campaigns](/developers/mobile-sdk/campaigns/action-handling#types-of-actions-in-campaigns) - [Read more about handling actions from push notifications](/developers/mobile-sdk/campaigns/action-handling#handling-actions-from-campaigns-in-react-native) ### Additional in-app alert from push notifications --- The React Native SDK on iOS devices can display an additional alert in the application after a push notification is received. See [this article](/developers/mobile-sdk/campaigns/simple-push#additional-in-app-alert-when-simple-push-is-received) to read more about this feature.
Simple Push campaign with in-app alert
Simple Push campaign with in-app alert
### Limitations compared to native platforms --- Due to platform limitations, not all notification functionalities may work as in native SDKs. # Client ### ClientIdentityProvider **Declared In:** lib/enums/client/identity_provider.dart **Declaration:**
enum IdentityProvider {
  synerise('SYNERISE'),
  facebook('FACEBOOK'),
  google('GOOGLE'),
  oauth('OAUTH'),
  apple('APPLE'),
  unknown('UNKNOWN');
  }
--- --- ### ClientAuthContext **Declared In:** lib/model/client/client_auth_context.dart **Related To:** [ClientAgreements](/developers/mobile-sdk/class-reference/flutter/client#clientagreements) **Declaration:**
class ClientAuthContext
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **authId** | String | yes | null | Optional identifier of authorization | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/flutter/client#clientagreements) | yes | null | Object that stores all agreements of a customer | | **attributes** | HashMap | yes | null | Additional custom attributes of a customer |
**authId** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Initializers:**
ClientAuthContext({this.authId, this.agreements, this.attributes})
**Example:**
```Dart ClientAuthContext clientAuthContext = ClientAuthContext( authId: 'AUTH_ID', agreements: agreements, attributes: attributes ); ```
--- --- ### ClientConditionalAuthContext **Declared In:** lib/model/client/client_conditional_auth_context.dart **Related To:** [ClientAgreements](/developers/mobile-sdk/class-reference/flutter/client#clientagreements) **Declaration:**
class ClientCondtitionalAuthContext {
**Properties:** Property | Type | Optional | Description | | --- | --- | --- | --- | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/flutter/client#clientagreements) | yes | Object that stores all agreements of a customer | | **attributes** | Map | yes | Additional custom attributes of a customer | **Initializers:**
ClientCondtitionalAuthContext({this.agreements, this.attributes});
--- --- ### ClientAccountInformation Model representating the customer information.
This is a read-only class and it is not meant to be instantiated directly.
**Declared In:** lib/model/client/client_account_information.dart **Related To:** [ClientSex](/developers/mobile-sdk/class-reference/flutter/client#clientsex) [ClientAgreements](/developers/mobile-sdk/class-reference/flutter/client#clientagreements) **Declaration:**
class ClientAccountInformation
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **clientId** | int | no | Customer's ID | | **email** | String | no | Customer's email | | **phone** | String | yes | Customer's phone | | **customId** | String | yes | Customer's custom ID | | **uuid** | String | no | Customer's UUID | | **firstName** | String | yes | Customer's first name | | **lastName** | String | yes | Customer's last name | | **displayName** | String | yes | Customer's display name | | **sex** | [ClientSex](/developers/mobile-sdk/class-reference/flutter/client#clientsex) | no | Customer's sex | | **company** | String | yes | Customer's company | | **address** | String | yes | Customer's address | | **city** | String | yes | Customer's city | | **province** | String | yes | Customer's province | | **zipCode** | String | yes | Customer's ZIP code | | **countryCode** | String | yes | Customer's country code | | **birthDate** | String | yes | Customer's birthdate | | **lastActivityDate** | Date | no | Customer's last activity date | | **avatarUrl** | String | yes | Customer's avatar URL | | **anonymous** | bool | no | Customer's anonymous flag | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/flutter/client#clientagreements) | no | Customer's agreements | | **attributes** | HashMap | yes | Customer's attributes | | **tags** | List | yes | Customer's tags | --- --- ### ClientAccountUpdateBasicInformationContext **Declared In:** lib/model/client/client_account_update_basic_information_context.dart **Related To:** [ClientSex](/developers/mobile-sdk/class-reference/flutter/client#clientsex) [ClientAgreements](/developers/mobile-sdk/class-reference/flutter/client#clientagreements) **Declaration:**
class ClientAccountUpdateBasicInformationContext
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **firstName** | String | yes | Customer's first name | | **lastName** | String | yes | Customer's last name | | **displayName** | String | yes | Customer's display name | | **sex** | [ClientSex](/developers/mobile-sdk/class-reference/flutter/client#clientsex) | yes | Customer's sex | | **phone** | String | yes | Customer's phone number | | **company** | String | yes | Customer's company | | **address** | String | yes | Customer's address | | **city** | String | yes | Customer's city | | **province** | String | yes | Customer's province | | **zipCode** | String | yes | Customer's ZIP code | | **countryCode** | String | yes | Customer's country code | | **birthDate** | String | yes | Customer's birthdate | | **avatarUrl** | String | yes | Customer's avatar URL | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/flutter/client#clientagreements) | yes | Customer's agreements | | **attributes** | HashMap | yes | Customer's attributes | **Initializers:**
ClientAccountUpdateBasicInformationContext({
  this.firstName,
  this.lastName,
  this.displayName,
  this.sex,
  this.phone,
  this.company,
  this.address,
  this.city,
  this.province,
  this.zipcode,
  this.countrycode,
  this.agreements,
  this.attributes
});
**Example:**
```Dart ClientAccountUpdateBasicInformationContext context = ClientAccountUpdateBasicInformationContext( firstName: firstName, lastName: lastName, sex: sex, phone: phone, company: company, address: address, city: city, province: province, zipcode: zipcode, countrycode: countrycode); ```
--- --- ### ClientAccountUpdateContext **Declared In:** lib/model/client/client_account_update_context.dart **Related To:** [ClientSex](/developers/mobile-sdk/class-reference/flutter/client#clientsex) [ClientAgreements](/developers/mobile-sdk/class-reference/flutter/client#clientagreements) **Declaration:**
class ClientAccountUpdateContext
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **email** | String | yes | Customer's email | | **customId** | String | yes | Customer's custom ID | | **uuid** | String | yes | Customer's UUID | | **firstName** | String | yes | Customer's first name | | **lastName** | String | yes | Customer's last name | | **displayName** | String | yes | Customer's display name | | **sex** | [ClientSex](/developers/mobile-sdk/class-reference/flutter/client#clientsex) | yes | Customer's sex | | **phone** | String | yes | Customer's phone number | | **company** | String | yes | Customer's company | | **address** | String | yes | Customer's address | | **city** | String | yes | Customer's city | | **province** | String | yes | Customer's province | | **zipCode** | String | yes | Customer's ZIP code | | **countryCode** | String | yes | Customer's country code | | **birthDate** | String | yes | Customer's birthdate | | **avatarUrl** | String | yes | Customer's avatar URL | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/flutter/client#clientagreements) | yes | Customer's agreements | | **attributes** | HashMap | yes | Customer's attributes | **Initializers:**
ClientAccountUpdateContext({
  this.email,
  this.customId,
  this.uuid,
  this.firstName,
  this.lastName,
  this.sex,
  this.phone,
  this.company,
  this.address,
  this.city,
  this.province,
  this.zipcode,
  this.countrycode,
  this.agreements,
  this.attributes
});
**Example:**
```Dart ClientAccountUpdateContext clientAccountUpdateContext = ClientAccountUpdateContext( email: email, firstName: firstName, lastName: lastName, sex: sex, phone: phone, company: company, address: address, city: city, zipcode: zipcode, countrycode: countrycode, province: province); ```
--- --- ### ClientAccountRegisterContext **Declared In:** lib/model/client/client_account_register_context.dart **Related To:** [ClientSex](/developers/mobile-sdk/class-reference/flutter/client#clientsex) [ClientAgreements](/developers/mobile-sdk/class-reference/flutter/client#clientagreements) **Declaration:**
class ClientAccountRegisterContext
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **email** | String | no | Customer's email | | **password** | String | no | Customer's password | | **firstName** | String | yes | Customer's first name | | **lastName** | String | yes | Customer's last name | | **customId** | String | yes | Customer's custom ID | | **sex** | [ClientSex](/developers/mobile-sdk/class-reference/flutter/client#clientsex) | yes | Customer's sex | | **phone** | String | yes | Customer's phone | | **company** | String | yes | Customer's company | | **address** | String | yes | Customer's address | | **city** | String | yes | Customer's city | | **province** | String | yes | Customer's province code | | **zipCode** | String | yes | Customer's ZIP code | | **countryCode** | String | yes | Customer's country code | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/flutter/client#clientagreements) | yes | Customer's agreements | | **attributes** | HashMap | yes | Customer's attributes | **Initializers:**
ClientAccountRegisterContext({
  required this.email,
  required this.password,
  this.firstName,
  this.lastName,
  this.sex,
  this.phone,
  this.company,
  this.address,
  this.city,
  this.zipcode,
  this.countrycode,
  this.province,
  this.uuid,
  this.customId,
  this.agreements,
  this.attributes
})
**Example:**
```Dart ClientAccountRegisterContext clientAccountRegisterContext = ClientAccountRegisterContext(email: "EMAIL", password: "PASSWORD"); ```
--- --- ### ClientSimpleAuthenticationData **Declared In:** lib/model/client/client_simple_authentication_data.dart **Related To:** [ClientSex](/developers/mobile-sdk/class-reference/flutter/client#clientsex) [ClientAgreements](/developers/mobile-sdk/class-reference/flutter/client#clientagreements) **Declaration:**
class ClientSimpleAuthenticationData
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **email** | String | yes | Customer's email | | **phone** | String | yes | Customer's phone | | **customId** | String | yes | Customer's custom ID | | **uuid** | String | yes | Customer's UUID | | **firstName** | String | yes | Customer's first name | | **lastName** | String | yes | Customer's last name | | **displayName** | String | yes | Customer's display name | | **sex** | [ClientSex](/developers/mobile-sdk/class-reference/flutter/client#clientsex) | yes | Customer's sex | | **company** | String | yes | Customer's company | | **address** | String | yes | Customer's address | | **city** | String | yes | Customer's city | | **province** | String | yes | Customer's province | | **zipCode** | String | yes | Customer's ZIP code | | **countryCode** | String | yes | Customer's country code | | **birthDate** | String | yes | Customer's birthdate | | **avatarUrl** | String | yes | Customer's avatar URL | | **agreements** | [ClientAgreements](/developers/mobile-sdk/class-reference/flutter/client#clientagreements) | yes | Customer's agreements | | **attributes** | Map | yes | Customer's attributes | **Initializers:**
ClientAccountUpdateContext({
  this.email,
  this.password,
  this.firstName,
  this.lastName,
  this.sex,
  this.phone,
  this.company,
  this.address,
  this.city,
  this.zipcode,
  this.countrycode,
  this.province,
  this.uuid,
  this.customId,
  this.agreements,
  this.attributes
});
--- --- ### ClientSex **Declared In:** lib/enums/client/client_sex.dart **Declaration:**
enum ClientSex {
  notSpecified('NOT_SPECIFIED'),
  male('MALE'),
  female('FEMALE'),
  other('OTHER');
}
--- --- ### ClientAgreements **Declared In:** lib/model/client/client_agreements.dart **Declaration:**
class ClientAgreements
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **email** | bool | no | Email agreement | | **sms** | bool | no | SMS agreement | | **push** | bool | no | Push notifications agreement | | **bluetooth** | bool | no | Bluetooth agreement | | **rfid** | bool | no | RFID agreement | | **wifi** | bool | no | WIFI agreement | **Initializers:**
ClientAgreements({this.email, this.sms, this.push, this.bluetooth, this.rfid, this.wifi})
--- --- ### Token **Declared In:** lib/model/client/token.dart **Related To:** [TokenOrigin](/developers/mobile-sdk/class-reference/flutter/client#tokenorigin) **Declaration:**
class Token
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **tokenString** | String | no | Token as a raw string | | **origin** | [TokenOrigin](/developers/mobile-sdk/class-reference/flutter/client#tokenorigin) | no | Token's origin | | **expirationDate** | DateTime | no | Token's expiration time | --- --- ### TokenOrigin **Declared In:** lib/enums/client/token_origin.dart **Declaration:**
enum TokenOrigin {
  synerise('SYNERISE'),
  facebook('FACEBOOK'),
  google('GOOGLE'),
  oauth('OAUTH'),
  apple('APPLE'),
  simpleAuth('SIMPLE_AUTH'),
  anonymous('ANONYMOUS'),
  unknown('UNKNOWN');
}
--- --- ### ClientConditionalAuthResult **Declared In:** lib/model/client/client_conditional_auth_result.dart **Declaration:**
class ClientConditionalAuthResult
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **status** | [ClientConditionalAuthStatus](/developers/mobile-sdk/class-reference/flutter/client#clientconditionalauthstatus) | no | Status of the authentication | | **conditions** | List | yes | Authentication conditions |
All properties are read-only.
--- --- ### ClientConditionalAuthStatus **Declared In:** lib/enums/client/client_conditional_auth_status.dart **Declaration:**
enum ClientConditionalAuthStatus {
  success('SUCCESS'),
  unauthorized('UNAUTHORIZED'),
  activationRequired('ACTIVATION_REQUIRED'),
  registrationRequired('REGISTRATION_REQUIRED'),
  approvalRequired('APPROVAL_REQUIRED'),
  termsAcceptanceRequired('TERMS_ACCEPTANCE_REQUIRED'),
  mfaRequired('MFA_REQUIRED');
  }
**Functions:** Converts from **ClientConditionalAuthStatus** to **String**.
```Dart String getClientConditionalAuthStatusAsString() { ```
--- Converts from **String** to **ClientConditionalAuthStatus**.
```Dart static ClientConditionalAuthStatus? getClientConditionalAuthStatusFromString(String string) { ```
--- --- ### ClientSignOutMode **Declared In:** lib/enums/client/client_sign_out_mode.dart **Declaration:**
enum ClientSignOutMode {
  signOut('SIGN_OUT'),
  signOutWithSessionDestroy('SIGN_OUT_WITH_SESSION_DESTROY');
**Functions:** Converts from **ClientSignOutMode** to **String**.
```Dart String clientSignOutModeAsString() { ```
--- Converts from **String** to **ClientSignOutMode**.
```Dart static ClientSignOutMode? getClientSignOutModeFromString(String string) { ```
# React Native ## Installation and configuration (React Native) In this article, you will find out how to install and initialize the Synerise SDK in a React Native mobile application. While performing the actions from this guide, keep the presented order presented.
The [Settings](/developers/mobile-sdk/settings#pre-initialization-settings) article contains additional information about SDK behaviors you may need prior to configuration.
### Requirements --- You need: * Access to a [workspace](/docs/settings/workspace) * A Profile [API Key](/docs/settings/tool/api#adding-api-keys) When creating the API key, use allowlisting or denylisting to only allow the events you intend to use. #### Android {id=requirements-android} * Recommended environment: - Minimum Android SDK version - 24 - Supported targetSDKVersion - 34 #### iOS {id=requirements-ios} * Recommended environment: - Xcode 16 - iOS SDK 18 * Target deployment: - **iOS 13.0+** for SDK versions 1.0.0 and higher - **iOS 9.0+** for SDK versions lower than 1.0.0
Bitcode is not supported in SDK version 1.0.0 and higher. Xcode ignores bitcode.
### Setting up Android --- 1. Install the module with npm:
npm install react-native-synerise-sdk --save
2. Install dependencies: - **React Native 0.60 or lower:** In your `android` build.gradle top-level build file, add:
...
          allprojects {
              repositories {
                  google()
                  jcenter()
                  maven { url 'https://pkgs.dev.azure.com/Synerise/AndroidSDK/_packaging/prod/maven/v1' }
              }
          }
- **React Native newer than 0.60**: Link the native dependency:
react-native link react-native-synerise-sdk
1. **If you DON'T use autolinking**: In your app's `build.gradle` file, add the following dependency: `implementation 'com.synerise.sdk.react:react-native-synerise-sdk:RN_SDK_VERSION'` where `RN_SDK_VERSION` is the SDK version. You can check the latest version in our [Github repository](https://github.com/Synerise/react-native-synerise-sdk/blob/master/CHANGELOG.md). Doing this together with autolinking causes a build error. 2. In the app's main class, to your list of packages, add `RNSyneriseSdkPackage`
```Java @Override protected List getPackages() { @SuppressWarnings("UnnecessaryLocalVariable") List packages = new PackageList(this).getPackages(); packages.add(new RNSyneriseSdkPackage());; return packages; } ```
### Setting up iOS ---
Starting from React Native 0.60, CocoaPods is the default integration approach for React Native iOS projects.
1. Install the module with npm:
npm install react-native-synerise-sdk --save
2. Install dependencies: - **React Native 0.60 or lower**: Install the native dependencies by using CocoaPods from your `ios` directory:
pod install
- **React Native newer than 0.60**: 1. Link the native dependency.
react-native link react-native-synerise-sdk
1. Install from your iOS:
pod install --repo-update
1. In your `ios/Podfile`, add the following dependency: `pod 'react-native-synerise-sdk', :path => '../node_modules/react-native-synerise-sdk'` **Result**: Your Podfile looks as follows:
target 'YourTarget' do

       # Pods for your target
       pod 'React', :path => '../node_modules/react-native/'
       pod 'React-Core', :path => '../node_modules/react-native/React'
       # ... other React dependencies

       # Add react-native-synerise-sdk
       pod 'react-native-synerise-sdk', :path => '../node_modules/react-native-synerise-sdk'

       use_native_modules!

       end
3. From your `ios` directory, run `pod install`
If you prefer linking manually, check [React Native - Linking Libraries](https://reactnative.dev/docs/linking-libraries-ios/#manual-linking) to link your libraries that contain native code.
### Initialization --- When you use the **react-native-synerise-sdk** module, use the following native **Synerise SDK** frameworks: - [Android](/developers/mobile-sdk/installation-and-configuration/android) - [iOS](/developers/mobile-sdk/installation-and-configuration/ios) #### Importing Synerise SDK You will need to import the **Synerise** object from the **react-native-synerise-sdk** module.
```JavaScript import { Synerise } from 'react-native-synerise-sdk'; ```
You must always import suitable objects from the **react-native-synerise-sdk** module into the files that contain the code that relates to the Synerise SDK.
#### Basic initialization Initialize the Synerise SDK and provide the [Profile API Key](/docs/settings/tool/api). You may initialize it wherever you want and when you need.
```JavaScript Synerise.Initializer() .withApiKey('YOUR_PROFILE_API_KEY') // 1 .withRequestValidationSalt('YOUR_REQUEST_VALIDATION_SALT') // 2 .withDebugModeEnabled(false) // 3 .withCrashHandlingEnabled(true) // 4 .init(); ```
1. `.withApiKey('YOUR_PROFILE_API_KEY')` - Sets Profile API Key for Synerise SDK initialization. 2. `.withRequestValidationSalt('YOUR_REQUEST_VALIDATION_SALT')` - Sets salt string for request validation. 3. `.withDebugModeEnabled(false)` - Enables debug mode. See [Debug mode](/developers/mobile-sdk/installation-and-configuration/react-native#debug-mode) section for more information. 4. `.withCrashHandlingEnabled(true)` - Enables crash handling. Synerise SDK sends a crash event automatically when an uncaught exception occurs. #### Initialization with custom API environment You can change the base URL of the API for on-premise installations. Use the following initialization method:
```JavaScript Synerise.Initializer() .withApiKey('YOUR_PROFILE_API_KEY') .withBaseUrl("YOUR_API_BASE_URL") .init(); ```
#### Advanced initialization This is an example of advanced initialization with: - custom API base URL for on-premise installations - request validation salt configured - debug mode enabled - crash handling enabled - most settings options available - initialization listeners set
Secure sensitive keys (for example, `clientApiKey` and `requestValidationSalt`) with mechanisms like string obfuscation or encryption.
```JavaScript Synerise.Initializer() .withBaseUrl("YOUR_API_BASE_URL") .withApiKey('YOUR_PROFILE_API_KEY') .withRequestValidationSalt('YOUR_REQUEST_VALIDATION_SALT') .withDebugModeEnabled(true) .withCrashHandlingEnabled(true) .withSettings({ sdk: { enabled: true, minTokenRefreshInterval: 5000, shouldDestroySessionOnApiKeyChange: true }, notifications: { enabled: true, encryption: false, }, injector: { automatic: true, }, tracker: { isBackendTimeSyncRequired: true, minBatchSize: 20, maxBatchSize: 30, autoFlushTimeout: 60 } }) .init(); Synerise.onReady(function() { // This function is called when Synerise is fully initialized and ready. }); Synerise.onError(function(error) { // This function is called when an error occurs during Synerise initialization. }); ```
### Debug mode --- You can enable debug logs for Synerise SDK by using the `.withDebugModeEnabled(true)` method in `Synerise.Initializer` when you initialize the SDK.
Do not use debug mode in a release version of your application.
You can receive logs about: - **Core**: push notifications - **Tracker**: auto-tracked events, declarative events, sending process - **Client**: customer state, authorization - **Injector**: campaigns - **Promotions**: promotions, vouchers - **Content**: content widget, documents, recommendations ### Main Synerise listeners --- You can handle Synerise SDK initialization result by two listener methods: - `Synerise.onReady()` - This method is called when Synerise is initialized. - `Synerise.onError(error: Error)` - This method is called when an error occurs during Synerise initialization. You can specify your custom action when a customer clicks a simple push, banner or walkthrough. Synerise SDK implements two main actions that a customer may invoke - open URL and Deeplink: - `IInjectorListener.onOpenUrl(url: string)` - This method is called when Synerise handles the open URL action from campaign activities. - `IInjectorListener.onDeepLink(deepLink: string)` - This method is called when Synerise handles the deeplink action from campaign activities.
For more information about handling actions from the Synerise SDK, see the [Campaigns](/developers/mobile-sdk/campaigns/action-handling#handling-actions-from-campaigns-in-react-native) section.
When you want to deal with Push Notifications: - `INotificationsListener.onRegistrationToken?(token: string)` - This method is called when a native part of the application passes a registration token. - `INotificationsListener.onRegistrationRequired?()` - This method is called when Synerise needs registration for Push Notifications. - `INotificationsListener.onNotification(payload: object)` - This method is called when a native part of the application passes a notification payload.
- For more information about notifications in Android SDK, see [Configuring push notifications](/developers/mobile-sdk/configuring-push-notifications/android) section. - For more information about notifications in iOS SDK, see [Configuring push notifications](/developers/mobile-sdk/configuring-push-notifications/ios) section. - For more information about SDK listeners and delegates, see [Listeners and delegates](/developers/mobile-sdk/listeners-and-delegates/react-native-listeners) section.
# Flutter ## Installation and configuration (Flutter) In this article you will find out how to install and initialize SDK in a Flutter mobile application. While performing the actions from this guide, keep the order presented in this article.
The [Settings](/developers/mobile-sdk/settings#pre-initialization-settings) article contains additional information about SDK behaviors you may need prior to configuration.
### Requirements You need: * Access to [workspace](/docs/settings/workspace) * A Profile [API Key](/docs/settings/tool/api#adding-api-keys) When creating the API key, use allowlisting or denylisting to only allow the events you intend to use. * Flutter configured on your machine - [Getting Started](https://docs.flutter.dev) * VS Code / Android Studio / Xcode ### Android{id=requirements-android} For the **Android** platform it uses the [Synerise Android SDK](https://github.com/Synerise/android-sdk). The development and debugging can be done with Android Studio. * Recommended environment: - Minimum Android SDK version - 24 - Supported targetSDKVersion - 34 ### iOS {id=requirements-ios} For the **iOS** platform it uses the [Synerise iOS SDK](https://github.com/Synerise/synerise-ios-sdk). The development and debugging can be done with Xcode. * Recommended environment: - Xcode 16 - iOS SDK 18 * Target deployment: * iOS 13.0+ for SDK versions 2.0.0 and higher * iOS 9.0+ for SDK versions lower than 2.0.0 --- ### Installation #### CLI ```shell $ flutter pub add synerise_flutter_sdk ``` This will add a line similar to this to your package's `pubspec.yaml` and run an implicit `flutter pub get`: ```yaml dependencies: synerise_flutter_sdk: ^0.7.4 ``` Alternatively, your editor might support `flutter pub get`. Check the docs for your editor to learn more. #### Path dependency First you will need to add the Synerise Flutter SDK to your mobile application. To do that you can use the path dependency method in your `pubspec.yaml` as follows: via ssh: ```yaml synerise_flutter_sdk: git: url: git@github.com:Synerise/synerise-flutter-sdk.git ``` or via https: ```yaml synerise_flutter_sdk: git: url: https://github.com/Synerise/synerise-flutter-sdk.git ``` After that you can run `flutter pub get` to resolve the new dependency. --- #### Importing Synerise SDK You will need to import **Synerise.dart** from the **synerise_flutter_sdk** plugin.
```Dart import 'package:synerise_flutter_sdk/synerise.dart'; ```
### Android gradle & configuration 1. In the Android part of your application, add ``maven { url 'https://pkgs.dev.azure.com/Synerise/AndroidSDK/_packaging/prod/maven/v1' }`` to the `android/build.gradle`: 2. Make sure you included the following repositories: `` google() mavenCentral() `` The whole build.gradle snippet must look as follows: ```groovy repositories { google() mavenCentral() maven { url 'https://pkgs.dev.azure.com/Synerise/AndroidSDK/_packaging/prod/maven/v1' } } ``` then in your MainActivity file add:
```Dart public class MainActivity extends FlutterActivity { @Override public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) { super.configureFlutterEngine(flutterEngine); SyneriseMethodChannel.configureChannel(flutterEngine); }} ```
### iOS configuration In iOS portion of your application (/ios) you will need to run `pod update` ### Initialization --- #### Basic initialization Initialize the Synerise SDK and provide the [Profile API Key](/docs/settings/tool/api).
Initialize Synerise SDK in the application workflow as early as possible.
```Dart Synerise.initializer() .withApiKey("YOUR_PROFILE_API_KEY") // 1 .setRequestValidationSalt("YOUR_REQUEST_VALIDATION_SALT") // 2 .withDebugModeEnabled(false) // 3 .withCrashHandlingEnabled(true) // 4 .setMessagingServiceType(MessagingServiceType.SERVICE_TYPE) // 5 .init(); ```
1. `.withApiKey('YOUR_PROFILE_API_KEY')` - Sets Profile API Key for Synerise SDK initialization. 2. `.withRequestValidationSalt('YOUR_REQUEST_VALIDATION_SALT')` - Sets salt string for request validation. 3. `.withDebugModeEnabled(false)` - Enables debug mode. See [Debug mode](/developers/mobile-sdk/installation-and-configuration/react-native#debug-mode) section for more information. 4. `.withCrashHandlingEnabled(true)` - Enables crash handling. Synerise SDK sends a crash event automatically when an uncaught exception occurs. 5. `.setMessagingServiceType(MessagingServiceType.SERVICE_TYPE)` - defines the messaging services your app uses: - `gms` for Google Mobile Services. This is the default option. - `hms` for Huawei Mobile Services. This can only be used on Huawei devices.
Secure sensitive keys (for example, `apiKey` and `requestValidationSalt`) with mechanisms like string obfuscation or encryption.
#### Initialization with custom API environment You can change the base URL of the API for on-premise installations. Use the following initialization method:
```Dart Synerise.initializer() .withApiKey('YOUR_PROFILE_API_KEY') .withBaseUrl("YOUR_API_BASE_URL") .init(); ```
### Running example app - Open project folder in selected IDE - `flutter pub get` in the terminal (dependencies pull) - select the device/emulator in your IDE (for ios part it is required to run `pod update` in example/ios directory) - `cd example` and `flutter run` ### Debug mode --- You can enable debug logs for Synerise SDK by using the `.withDebugModeEnabled(true)` method in `Synerise.initializer` when you initialize the SDK.
Do not use debug mode in a release version of your application.
You can receive logs about: - **Core**: push notifications - **Tracker**: declarative events, sending process - **Client**: customer state, authorization - **Injector**: campaigns - **Content**: content widget, documents, recommendations ### Main Synerise listeners --- #### Injector Listeners You can specify your custom action when a customer clicks on simple push, banner or walkthrough. Synerise SDK implements two main actions that a customer may invoke - open URL and Deeplink: - listener.onOpenUrl = (url) - This method is called when Synerise handles URL action from campaign activities. - listener.onDeepLink = (deepLink) - This method is called when Synerise handles deeplink action from campaign activities. Note: For more information about handling actions from the Synerise SDK, see the Campaigns section.
```Dart Synerise.injector.listener((listener) { listener.onOpenUrl = (url) { ... }; listener.onDeepLink = (deepLink) { ... }; }); ### Notifications Listeners When you want to deal with Push Notifications: - listener.onRegistrationRequired - This method is called when Synerise needs registration for Push Notifications. Synerise.notifications.listener((listener) { listener.onRegistrationRequired = () { FirebaseMessaging.instance.getToken().then((value) { if (value != null) { Synerise.notifications.registerForNotifications(value, true); } }); }; }); ```
# Campaigns ### SyneriseSource This enum contains values which describe the source of campaign. **Declared In:** `com.synerise.sdk.injector.callback.SyneriseSource` **Declaration:**
```Java public enum SyneriseSource ```
```Kotlin public enum SyneriseSource ```
**Values:** | Property | Description | | --- | --- | | **SIMPLE_PUSH** | Simple push campaign | | **IN_APP_MESSAGE** | In-app message campaign | --- --- ### Campaign Class model for campaigns. **Declared In:** `com.synerise.sdk.injector.net.model.Campaign` **Declaration:**
```Java public class Campaign implements Serializable ```
```Kotlin class Campaign : Serializable ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **hashId** | String | no | - | Campaign hash ID | | **variantId** | int | no | - | Campaign variant's ID | | **title** | String | no | - | Campaign title | | **type** | String | no | - | Campaign type |
All the properties above are accessible by using getters.
**Initializers:** There are no initializers. **Methods:** This method retrieves a value for the `hashId` parameter.
public String getHashId()
--- This method retrieves a value for the `variantId` parameter.
public int getVariantId()
--- This method retrieves a value for the `title` parameter.
public String getTitle()
--- This method retrieves a value for the `type` parameter.
public String getType()
--- --- --- ### SynerisePushResponse Class model for SynerisePushResponse. **Declared In:** `com.synerise.sdk.injector.net.model.push.notification.SynerisePushResponse` **Declaration:**
```Java public class SynerisePushResponse ```
```Kotlin class SynerisePushResponse ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **contentAvailable** | Boolean | no | - | Informs if content is available | | **data** | SynerisePush | no | - | Synerise push data | | **notification** | [SimpleNotification](/developers/mobile-sdk/class-reference/android/campaigns#simplenotification) | no | - | Synerise simple notification |
All the properties above are accessible by using getters.
**Initializers:** There are no initializers. **Methods:** This method checks if content is available.
public boolean isContentAvailable()
--- This method retrieves a value for the `data` parameter.
public SyneriseData getData()
--- This method retrieves a value for the `notification` parameter.
public SimpleNotification getNotification()
--- This method checks if the push is a simple push.
public boolean isSimplePush()
--- --- --- ### SimpleNotification Class model for simple notification. **Declared In:** `com.synerise.sdk.injector.net.model.push.notification.SimpleNotification` **Declaration:**
```Java public class SimpleNotification implements Serializable ```
```Kotlin class SimpleNotification : Serializable ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **title** | String | no | - | Notification title | | **body** | String | no | - | Notification body |
All the properties above are accessible by using getters.
**Initializers:** There are no initializers. **Methods:** This method checks if the notification has a title.
public boolean hasTitle()
--- This method retrieves a value for the `title` parameter (notification title).
public String getTitle()
--- This method checks if the notification has a body.
public boolean hasBody()
--- This method retrieves a value for the `body` parameter (notification body).
public String getBody()
--- --- --- ### NotificationInfo This enum contains values for a voucher code status. **Declared In:** `com.synerise.sdk.injector.callback.model` **Declaration:**
```Java public class NotificationInfo ```
```Kotlin public class NotificationInfo ```
#### Values | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **campaignHashId** | String | no | - | Identifier of the notification campaign. | | **campaignTitle** | String | no | - | Identifier of the notification title. | | **payload** | HashMap | no | - | Payload of the notification. | **Methods:** This method retrieves the value of the `campaignHashId` parameter.
public String getCampaignHashId()
--- This method defines the value of the `campaignHashId` parameter.
public void setCampaignHashId(String campaignHashId)
--- This method retrieves the value of the `CampaignTitle` parameter.
public String getCampaignTitle()
--- This method defines the value of the `CampaignTitle` parameter.
public void setCampaignTitle(String campaignTitle)
--- This method retrieves the contents of the `payload` parameter.
public HashMap<String, String> getPayload()
--- This method defines the contents of the `payload` parameter.
public void setPayload(HashMap<String, String> payload)
--- --- --- ### PushRegistrationOrigin This enum contains values for the `origin` parameter of push registration listener methods. **Declared In:** `com.synerise.sdk.core.types.enums` **Declaration:**
```Java public enum PushRegistrationOrigin ```
```Kotlin public enum PushRegistrationOrigin ```
**Values:** | Property | Value | Description | | --- | --- | --- | | **APP_STARTED** | "APP_STARTED" | After a `client.applicationStarted` event is sent. | | **CLIENT_CONTEXT_CHANGE** | "CLIENT_CONTEXT_CHANGE" | After the client context changes. | | **PERIODIC_JOB** | "PERIODIC_JOB" | After a periodic job of a background task starts. | | **SECURITY_REASON** | "SECURITY_REASON" | After a security threat | **Methods:** There are no methods. --- --- --- ### TemplateBanner Class model for banners. **Declared In:** `com.synerise.sdk.injector.net.model.push.banner.TemplateBanner` **Declaration:**
```Java public class TemplateBanner extends BasePageMapper implements Parcelable, Validable ```
```Kotlin class TemplateBanner : BasePageMapper(), Parcelable, Validable ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **campaign** | [Campaign](/developers/mobile-sdk/class-reference/android/campaigns#campaign) | no | - | Campaign class | | **trigger** | String | yes | - | Banner trigger | | **notification** | [SimpleNotification](/developers/mobile-sdk/class-reference/android/campaigns#simplenotification) | no | - | Notification class | | **autoDisappear** | [AutoDisappear](/developers/mobile-sdk/class-reference/android/campaigns#autodisappear) | no | - | Auto disappear | | **page** | NetGenericPageData | yes | - | Page data |
All the properties above are accessible by using getters.
**Initializers:** There are no initializers. **Methods:** This method retrieves the value of the `campaign` parameter.
public Campaign getCampaign()
--- This method retrieves the value of the `value` object.
public Object getValue()
--- This method checks if a banner has a trigger.
public boolean hasTrigger()
--- This method retrieves the `trigger` parameter from a banner.
public String getTrigger()
--- This method retrieves the value of the `notification` parameter.
public SimpleNotification getNotification()
--- This method retrieves the value of the `page` parameter.
public PageItem getPage()
--- This method retrieves the value of the `autodisappear` parameter.
public AutoDisappear getAutoDisappear()
--- --- --- ### SilentCommand Class model for silent command. **Declared In:** `com.synerise.sdk.injector.SilentCommand` **Declaration:**
```Java public class SilentCommand implements Validable ```
```Kotlin class SilentCommand : Validable ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **className** | String | no | - | Class name | | **methodName** | String | no | - | Method name | | **methodParameterList** | List<[MethodParameter](/developers/mobile-sdk/class-reference/android/campaigns#methodparameter)> | no | - | Method parameters |
All the properties above are accessible by using getters.
**Initializers:** There are no initializers. **Methods:** This method retrieves a value of the `className` parameter.
public String getClassName()
--- This method retrieves a value of the `methodName` parameter.
public String getMethodName()
--- This method retrieves a list of values of the `methodParameters` parameter.
public List<MethodParameter> getMethodParameterList()
--- --- --- ### MethodParameter Class model for method parameter. **Declared In:** `com.synerise.sdk.injector.MethodParameter` **Declaration:**
```Java public class MethodParameter implements Validable ```
```Kotlin class MethodParameter : Validable ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **className** | String | no | - | Class name | | **value** | Object | no | - | Parameter value | | **position** | int | no | - | Parameter position |
All the properties above are accessible by using getters.
**Initializers:** There are no initializers. **Methods:** This method retrieves a value of the `className` parameter.
public String getClassName()
--- This method retrieves a value of the `value` parameter.
public Object getValue()
--- This method retrieves a value of the `position` parameter.
public int getPosition()
--- --- --- ### AutoDisappear Class model for AutoDisappear. **Declared In:** `com.synerise.sdk.injector.net.model.push.model.banner.AutoDisappear` **Declaration:**
```Java public class AutoDisappear implements Serializable ```
```Kotlin class AutoDisappear : Serializable ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **isEnabled** | Boolean | no | - | Informs if auto disappear is enabled | | **timeout** | int | no | - | Disappear timeout |
All the properties above are accessible by using getters.
**Initializers:** There are no initializers. **Methods:** This method checks if auto disappear is enabled.
public boolean isEnabled()
--- This method retrieves the value of the `timeout` parameter.
public int getTimeout()
--- --- --- ### InAppMessageData Model for in-app messaging communication. **Declared In:** com.synerise.sdk.injector.inapp.InAppMessageData **Declaration:**
```Java public InAppMessageData(String campaignHash, String variantId, HashMap additionalParameters, Boolean isTest) ```
```Kotlin public InAppMessageData(campaignHash: String, variantId: String, additionalParameters: HashMap , isTest: Boolean) ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **campaignHash** | String | no | Identifier of the in-app message campaign. | | **variantId** | String | no | Identifier of the in-app message campaign variant. | | **additionalParameters** | HashMap | yes | Parameters additionally provided by the campaign. | | **url** | URL | yes | URL value from the action of the activity. | | **deeplink** | String | yes | Deep link value from the action of the activity. | | **isTest** | Bool | no | Specifies if the object is from a test campaign. |
All the properties above are accessible by using getters.
**Methods:** There are only getters for the above properties. --- --- ### SyneriseMethod Enum with a list of SDK methods that can be called from JavaScript in an in-app. See [Using in-app template builder](/docs/campaign/in-app-messages/creating-inapp-templates/creating-inapp-template#use-a-mobile-sdk-method) # Customer session --- ## Refresh customer token --- This method refreshes the customer’s current token.
Returns an error if the token has expired and cannot be refreshed.
**Declared In:** lib/modules/client/client_impl.dart **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> refreshToken({required void Function() onSuccess, required void Function(SyneriseError) onError}) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **onSuccess** | Function() | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
await Synerise.client.refreshToken(onSuccess: () {
  //onSuccess handling
}, onError: (SyneriseError error) {
  //onError handling
});
**Declaration:**
Future<bool> refreshToken() async
**Return Value:** **true** if the operation is success, otherwise it throws an error. **Example:**
await  Synerise.client.refreshToken().catchError((error)
## Retrieve customer token --- This method retrieves the customer’s current, active token.
Returns an error if the token has expired and cannot be retrieved.
**Declared In:** lib/modules/client/client_impl.dart **Related To:** [Token](/developers/mobile-sdk/class-reference/flutter/client#token) **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> retrieveToken({required void Function(Token) onSuccess, required void Function(SyneriseError) onError}) async
**Parameters:** | Parameter | Type | Mandatory | Description | | --- | --- | --- | --- | | **onSuccess** | Function([Token](/developers/mobile-sdk/class-reference/flutter/client#token) token) | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
await Synerise.client.retrieveToken(onSuccess: (Token token) {
  //onSuccess handling
}, onError: (SyneriseError error) {
  //onError handling
});
**Declaration:**
Future<Token> retrieveToken() async
**Return Value:** [Token](/developers/mobile-sdk/class-reference/flutter/client#token) **Example:**
Token token = await  Synerise.client.retrieveToken().catchError((error)
## Get current customer UUID --- This method retrieves the customer’s current UUID. **Declared In:** lib/modules/client/client_impl.dart **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<String> getUUID() async
**Return Value:** String **Example:**
await Synerise.client
        .getUUID()
        .then((result) => {
        //result handling
        });
**Declaration:**
Future<String> getUUID() async
**Return Value:** String **Example:**
String uuid = await  Synerise.client.getUUID().catchError((error)
## Regenerate customer --- This method regenerates the UUID and clears the authentication token, login session, custom email, and custom identifier. This operation works only if the customer is anonymous. This operation clears the authentication token, login (if applicable), custom email, and custom identifier. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.3.10 | 3.3.5 | 0.9.0 | 0.7.0 | **Declared In:** lib/modules/client/client_impl.dart **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client) **Declaration:**
Future<void> regenerateUUID() async
**Return Value:** No value is returned. **Example:**
await Synerise.client
        .regenerateUUID()
        .then((result) => {
        //result handling
        });
## Regenerate customer with identifier --- This method regenerates the UUID and clears the authentication token, login session, custom email, and custom identifier. This operation works only if the customer is anonymous. This operation clears the authentication token, login (if applicable), custom email, and custom identifier The optional `clientIdentifier` parameter is a seed for UUID generation. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.5 | 3.6.4 | 0.9.10 | 0.7.2 | **Declared In:** lib/modules/client/client_impl.dart **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client) **Declaration:**
Future<void> regenerateUUIDWithClientIdentifier(String clientIdentifier) async
**Parameters:** | Parameter | Type | Mandatory | Description | | --- | --- | --- | --- | | **clientIdentifier** | String | no | Seed for UUID generation |
The **clientIdentifier** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** No value is returned. **Example:**
await Synerise.client
        .regenerateUUIDWithClientIdentifier(clientIdentifier)
        .then((result) => {
        //result handling
        });
## Destroy current session --- This method destroys the session completely. This method clears all session data (both client and anonymous) and removes cached data. Then, it regenerates the UUID and creates the new anonymous session. **Declared In:** lib/modules/client/client_impl.dart **Class:** [ClientImpl](/developers/mobile-sdk/class-reference/flutter/modules#client)
**Declaration:**
Future<void> destroySession({required void Function() onSuccess, required void Function(SyneriseError) onError}) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **onSuccess** | Function() | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
await Synerise.client.destroySession(onSuccess: () {
  //onSuccess handling
}, onError: (SyneriseError error) {
  //onError handling
});
**Declaration:**
Future<void> destroySession() async
**Return Value:** No value is returned. **Example:**
await  Synerise.client.destroySession().catchError((error)
# Customer session --- ## Refresh customer token --- This method refreshes the customer’s current token.
Returns an error if the token has expired and cannot be refreshed.
**Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public refreshToken(onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Client.refreshToken(function(token) { // success }, function(error) { // failure }); ```
## Retrieve customer token --- This method retrieves the customer’s current, active token.
Returns an error if the token has expired and cannot be retrieved.
**Declared In:** lib/main/modules/ClientModule.js **Related To:** [Token](/developers/mobile-sdk/class-reference/react-native/client#token) **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public retrieveToken(onSuccess: (token: Token) => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Client.retrieveToken(function(token) { // success }, function(error) { // failure }); ```
## Get current customer UUID --- This method retrieves the customer’s current UUID. **Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public getUUID(): string
**Return Value:** The method returns the customer's UUID as string. **Example:**
```JavaScript let uuid = Synerise.Client.getUUID(); ```
## Regenerate customer --- This method regenerates the UUID and clears the authentication token, login session, custom email, and custom identifier. This operation works only if the customer is anonymous. This operation clears the authentication token, login (if applicable), custom email, and custom identifier. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.3.10 | 3.3.5 | 0.9.0 | 0.7.0 | **Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public regenerateUUID()
**Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Client.regenerateUUID(); ```
## Regenerate customer with identifier --- This method regenerates the UUID and clears the authentication token, login session, custom email, and custom identifier. This operation works only if the customer is anonymous. This operation clears the authentication token, login (if applicable), custom email, and custom identifier The optional `clientIdentifier` parameter is a seed for UUID generation. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.5 | 3.6.4 | 0.9.10 | 0.7.2 | **Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public regenerateUUIDWithClientIdentifier(clientIdentifier: string)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **clientIdentifier** | string | no | - | Seed for UUID generation |
The **clientIdentifier** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** No value is returned. ## Destroy current session --- This method destroys the session completely. This method clears all session data (both client and anonymous) and removes cached data. Then, it regenerates the UUID and creates the new anonymous session. **Declared In:** lib/main/modules/ClientModule.js **Class:** [ClientModule](/developers/mobile-sdk/class-reference/react-native/modules#client) **Declaration:**
public destroySession()
**Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Client.destroySession(); ```
# Campaigns ### SyneriseSource **Declared In:** lib/classes/models/Misc/SyneriseSource.js **Declaration:**
enum SyneriseSource {
  NotSpecified = 'NOT_SPECIFIED',
  SimplePush = 'SIMPLE_PUSH',
  Banner = 'BANNER',
  Walkthrough = 'WALKTHROUGH',
  InAppMessage = 'IN_APP_MESSAGE'
}
**Functions:** Converts from **SyneriseSource** to **string**.
function SyneriseSourceToString(source: SyneriseSourceToString): string
--- Converts from **string** to **SyneriseSource**.
function SyneriseSourceFromString(string: string): SyneriseSource
--- --- ### InAppMessageData Model representing an in-app message data.
This is a read-only class and it is not meant to be instantiated directly.
**Declared In:** lib/classes/models/Misc/InAppMessageData.js **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
class InAppMessageData extends BaseModel
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **campaignHash** | string | no | Identifier of the in-app message campaign. | | **variantIdentifier** | string | no | Identifier of the in-app message campaign variant. | | **additionalParameters** | Object | yes | Parameters additionally provided by the campaign. | | **isTest** | boolean | no | Specifies if the object is from a test campaign. | # Flutter ## Method reference - Flutter # Configuring push notifications In this section, you will learn how to implement push notifications in your mobile application. # Flutter ## Flutter listeners #### NotificationsListener {id=notifications-listener} A listener to handle actions from the notifications module.
```Dart Synerise.notifications.listener((listener) { // The following method is called when registration for Push Notifications is needed. listener.onRegistrationRequired = () { ... }; }); ```
After invoking **onRegistrationRequired()** function, you must invoke the [Synerise.notifications.registerForNotifications(registrationToken, mobileAgreement)](/developers/mobile-sdk/method-reference/flutter/campaigns#register-for-push-notifications) method again.
--- --- #### InjectorListener {id=injector-listener} A listener to handle URL and deeplink actions from the injector module.
```Dart Synerise.injector.listener((listener) { // The following method is called when Synerise handles URL action from campaign activities // It is required function listener.onOpenUrl = (url) { ... }; // The following method is called when Synerise handles deep link action from campaign activities // It is required function listener.onDeepLink = (deepLink) { ... }; }); ```
--- --- #### InjectorInAppMessageListener {id=injector-in-app-message-listener} A listener to handle the states of [in-app messages](/developers/mobile-sdk/campaigns/in-app-message).
```Dart Synerise.injector.inAppMessageListener((listener) { // The following method is called after an in-app message appears listener.onPresent = (data) { ... }; // The following method is called after an in-app message disappears listener.onHide = (data) { ... }; // This method is called when the SRInApp.openUrl(url) method is used in an in-app message. listener.onOpenUrl = (data, url) { ... }; // This method is called when the SRInApp.openDeeplink(url) method is used in an in-app message. listener.onDeepLink = (data, deepLink) { ... }; // This method is called when the // SRInApp.handleCustomAction(name, params) method is used in an in-app message. listener.onCustomAction = (data, name, parameters) { ... }; }) ```
--- --- ### InjectorWalkthroughListener {id=injector-walkthrough-listener}
**InjectorWalkthroughListener** was removed in SDK version 2.0.0.
--- --- ### InjectorBannerListener {id=injector-banner-listener}
**InjectorBannerListener** was removed in SDK version 2.0.0.
# Flutter ## Configuring push notifications (Flutter) ### Prerequisites --- #### Firebase Cloud Messaging Google Firebase Cloud Messaging is necessary to handle [push notifications](/docs/campaign/Mobile) sent from Synerise. 1. Follow the instructions in [this article](https://firebase.google.com/docs/flutter/setup) and integrate the Firebase plugin with your application. 2. Follow the instructions in [this article](https://firebase.flutter.dev/docs/messaging/overview/) and integrate cloud messaging in your application. 3. Integrate Firebase with Synerise. See [Integration](/docs/settings/tool/firebase) section.
It's important that the Firebase plugin is initialized as early as possible in the application lifecycle and also after the Synerise SDK. Late initialization may cause compilation problems.
### Setting up - Android {id=setting-up-android} --- #### Requirements {id=android-requirements} 1. After configuring Firebase, add the `google-services.json` file to your project. 2. Add the google-services dependency to your project's `build.gradle` file.
dependencies {
       ...
       classpath 'com.google.gms:google-services:4.3.3'
       ...
     }
### Setting up - iOS {id=setting-up-ios} --- #### Requirements {id=ios-requirements} 1. Configure handling Push Notifications in your application. See [Apple Notifications](https://developer.apple.com/notifications/). 2. After configuring Firebase, add the `GoogleService-Info.plist` file to your project. 3. Make sure your `Info.plist` file contains the following snippet: ```xml FirebaseAppDelegateProxyEnabled ``` #### Extensions for push notifications {id=ios-extensions-for-push-notifications} ##### Notification Service Extension {id=synerise-notification-service-extension-for-ios} **Synerise Notification Service Extension** is an object that adds the notification functionality to the SDK. It implements the following operations: - Decrypting **Simple Push** communication data (if encryption is enabled). - Tracking events from **Simple Push** communication. - Adding action buttons to **Simple Push** communication (if the communication contains any). - Improving the appearance of **Simple Push** communication (Rich Media - Single Image) with an image thumbnail. **Notification Service Extension** should be implemented in the native part of the application. Follow the instructions in [this article](/developers/mobile-sdk/configuring-push-notifications/ios#synerise-notification-service-extension-configuration). ##### Rich Media Notification Content Extensions {id=synerise-notification-content-extension-for-ios} **Synerise Rich Media Notification Content Extension** is an object that allows rendering your own appearance of a push notification when the notification is expanded (by tapping the notification). **Synerise Rich Media Notification Content Extensions** should be implemented in the native part of the application. Follow the instructions in [this article](/developers/mobile-sdk/configuring-push-notifications/ios#rich-media-in-push-notifications). ### Set up Firebase Cloud Messaging for Synerise SDK --- The following code example explains how to implement Firebase Cloud Messaging integration with Synerise: 1. Define a top-level function for handling notifications when the app is in the terminated state. 2. Request permissions from the user. 3. Set presentation options for foreground state. 4. Get Firebase FCM token and set it to deliver push notifications from Synerise. 5. Make sure that the Firebase FCM token is always up-to-date. 6. Set Firebase listener method for handling notifications when the app is in the foreground. 7. Set Firebase listener method for handling notification clicks when the app is in the background. 8. Invoke method for handling notification clicks when a user opens a notification in the app’s closed state.
```Dart class InitialViewState extends State { @override void initState() { // Initialize Synerise SDK initializeSynerise(); // Setup notifications with Firebase setupNotifications(); // 8. Invoke method for handling notification clicks when a user opens a notification in the app’s closed state (see below for definition of the method). checkForInitialNotificationMessage(); super.initState(); } Future initializeSynerise() async { Synerise.initializer() .withApiKey('YOUR_PROFILE_API_KEY') .withBaseUrl("YOUR_API_BASE_URL") .withDebugModeEnabled(true) .init(); } Future setupNotifications() async { await Firebase.initializeApp(); // 1. Define a top-level function for handling notifications when the app is in the terminated state (see below for definition of the method). FirebaseMessaging.onBackgroundMessage(backgroundHandlerForFCM); // 2. Request permissions from the user await FirebaseMessaging.instance.requestPermission( alert: true, announcement: false, badge: true, carPlay: false, criticalAlert: false, provisional: false, sound: true, ); // 3. Set presentation options for the foreground state await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions( alert: true, badge: true, sound: true, ); // 4. Get Firebase FCM token and set it to deliver push notifications from Synerise FirebaseMessaging.instance.getToken().then((token) { if (token != null) { Synerise.notifications.registerForNotifications(token, true); } }); // 5. Make sure that the Firebase FCM token is always up-to-date FirebaseMessaging.instance.onTokenRefresh.listen((event) { FirebaseMessaging.instance.getToken().then((token) { if (token != null) { Synerise.notifications.registerForNotifications( firebaseToken!, mobileAgreement: true, // true or false, should depend on device permissions and customer's agreement in the application onSuccess: () {}, onError: (error) {}, ); } }); }); Synerise.notifications.listener((listener) { listener.onRegistrationRequired = () { FirebaseMessaging.instance.getToken().then((token) { if (token != null) { Synerise.notifications.registerForNotifications( firebaseToken!, mobileAgreement: true, // true or false, should depend on device permissions and customer's agreement in the application onSuccess: () {}, onError: (error) {}, ); } }); }; }); // 6. Set Firebase listener method for handling notifications when the app is in the foreground FirebaseMessaging.onMessage.listen((RemoteMessage message) async { Map messageMap = message.toMap(); bool isSyneriseNotification = await Synerise.notifications.isSyneriseNotification(messageMap); if (isSyneriseNotification == true) { Synerise.notifications.handleNotification(messageMap); } }); // 7. Set Firebase listener method for handling notification clicks when the app is in the background FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) async { Map messageMap = message.toMap(); bool isSyneriseNotification = await Synerise.notifications.isSyneriseNotification(messageMap); if (isSyneriseNotification == true) { Synerise.notifications.handleNotificationClick(messageMap); } }); } @pragma('vm:entry-point') Future backgroundHandlerForFCM(RemoteMessage message) async { await Firebase.initializeApp(); await initializeSynerise(); Map messageMap = message.toMap(); bool isSyneriseNotification = await Synerise.notifications.isSyneriseNotification(messageMap); if (isSyneriseNotification) { Synerise.notifications.handleNotification(remoteMessageMap); } } Future checkForInitialNotificationMessage() async { await Firebase.initializeApp(); RemoteMessage? message = await FirebaseMessaging.instance.getInitialMessage(); if (message != null) { Map messageMap = message.toMap(); bool isSyneriseNotification = await Synerise.notifications.isSyneriseNotification(messageMap); if (isSyneriseNotification == true) { Synerise.notifications.handleNotificationClick(messageMap); } } } //... } ```
The second parameter of the registration method is the agreement for mobile push campaigns. In the Profile's card in Synerise, you can find it in the **Subscriptions** section (if you have the required access permission). Learn more about the [Synerise.notifications.registerForNotifications(registrationToken, mobileAgreement) method in the method reference](/developers/mobile-sdk/method-reference/flutter/campaigns#register-for-push-notifications).
You must always keep the Firebase token updated. In many cases in the application lifecycle, such as authorization, destroy session, user context change, and so on, the registration needs to be updated. In these situations, the SDK invokes the [onRegistrationRequired()](/developers/mobile-sdk/listeners-and-delegates/flutter-listeners#notifications-listener) method (see code snippet above).
### Configure Notification Encryption --- #### Android {id=android-notification-encryption-configuration} See [Configure Notification Encryption](/developers/mobile-sdk/configuring-push-notifications/android#configure-notification-encryption). #### iOS {id=ios-notification-encryption-configuration} See [Synerise Notification Service Extension](#synerise-notification-service-extension-for-ios) and [Configure Notification Encryption](/developers/mobile-sdk/configuring-push-notifications/ios#configure-notification-encryption). #### Application implementation {id=application-notification-encryption-configuration} In the application, you must set `encryption` to `true` in the SDK initializer or in the SDK settings.
```JavaScript // WARNING: This option must be configured before Synerise SDK is initialized! Synerise.settings.notifications.encryption = true; ```
### Handling incoming push notifications ---
You may disable handling push notifications in the SDK at any time. See [Enable/disable notifications](/developers/mobile-sdk/settings#enabledisable-notifications).
#### Synerise payload The following sample code shows how to handle notifications and check if they are from Synerise:
```Dart //... FirebaseMessaging.onMessage.listen((RemoteMessage message) { Map messageMap = message.toMap(); bool isSyneriseNotification = await Synerise.notifications.isSyneriseNotification(messageMap); if (isSyneriseNotification == true) { Synerise.notifications.handleNotification(messageMap); } }); FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) { Map messageMap = message.toMap(); bool isSyneriseNotification = await Synerise.notifications.isSyneriseNotification(messageMap); if (isSyneriseNotification == true) { Synerise.notifications.handleNotificationClick(messageMap); } }); //... ```
#### Custom payload You may send both custom push notifications and custom campaigns in [Synerise](https://app.synerise.com). The code below of one sample Firebase listener method checks the notification origin and then handles it:
```Dart //... FirebaseMessaging.onMessage.listen((RemoteMessage message) { Map messageMap = message.toMap(); bool isSyneriseNotification = await Synerise.notifications.isSyneriseNotification(messageMap); if (isSyneriseNotification == true) { Synerise.notifications.handleNotification(messageMap); } else { // Handle other notifications in your own way } }); //... ```
### Handling actions from push notifications --- - [Read more about types of actions in campaigns](/developers/mobile-sdk/campaigns/action-handling#types-of-actions-in-campaigns) - [Read more about handling actions from push notifications](/developers/mobile-sdk/campaigns/action-handling#handling-actions-from-campaigns-in-flutter) ### Additional in-app alert from push notifications --- The Flutter SDK on iOS devices can display an additional alert in the application after a push notification is received. See [this article](/developers/mobile-sdk/campaigns/simple-push#additional-in-app-alert-when-simple-push-is-received) to read more about this feature.
Simple Push campaign with in-app alert
Simple Push campaign with in-app alert
### Limitations compared to native platforms --- Due to platform limitations, not all notification functionalities may work as in native SDKs. - **iOS only**: Native-configured button from a Simple Push campaign always invokes the default action (if configured) or displays an in-app alert with buttons to choose. # External providers This article contains instruction to implement third parties approaches to authenticating a customer in a mobile application. ## Facebook Login --- For those Applications that rely on Facebook Login as authentication, Synerise has a separate method that provides you with a Synerise JWT token based on Facebook login. Currently, there are no dedicated settings related to Facebook authentication on the user interface in the Synerise platform. You just have to implement RESTful API or SDK methods to authenticate through Facebook. To authenticate a customer using Facebook, implement the following methods: | OS | Method | |--------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | Android | - [Client.authenticate()](/developers/mobile-sdk/method-reference/android/client-authentication#authenticate-customer-by-identityprovider) | | iOS | - [Client.authenticate(token:clientIdentityProvider:authID:context:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-authentication#authenticate-customer-by-identityprovider)
- [Client.authenticateConditionally(token:clientIdentityProvider:authID:context:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-authentication#authenticate-customer-conditionally-by-identityprovider) | | React Native | - [Synerise.Client.authenticate(token, clientIdentityProvider, authID, context, onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/client-authentication#authenticate-customer-by-identityprovider)
- [Synerise.Client.authenticateConditionally(token, clientIdentityProvider, authID context, onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/client-authentication#authenticate-customer-conditionally-by-identityprovider) | | Flutter | - [Synerise.client.authenticate(clientAuthContext, clientIdentityProvider, token)](/developers/mobile-sdk/method-reference/flutter/client-authentication#authenticate-customer-by-identityprovider)) |
**authId/authID** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
Additionally, in the Synerise platform (`app.synerise.com`) you can define the following settings: - [Assignment of loyalty card](/docs/settings/tool/iam-for-apps/general#loyalty-card-assignment) - [JWT longevity](/docs/settings/tool/iam-for-apps/general#jwt-lifetime) - [Custom ID overwriting](/docs/settings/tool/iam-for-apps/general#custom-id-overwriting) - [External ID overwriting](/docs/settings/tool/iam-for-apps/general#external-id-overwriting) ## Sign in with Apple --- For integrating with the Apple platform, Synerise has a separate method that returns a Synerise JWT token based on Sign in with Apple credentials. You can read more about the configuration of the Sign in with Apple option in the Synerise platform [here](/docs/settings/tool/iam-for-apps/third-party#apple). In this case, the authentication process works in the following way: 1. A customer authenticates by Sign in with Apple. 2. Apple provides authentication credentials. 3. Your app uses these credentials and creates `ClientAppleSignInAuthenticationContext`. 4. The context is passed to Synerise by using: | OS | Method | |--------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | iOS | - [Client.authenticate(token:clientIdentityProvider:authID:context:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-authentication#authenticate-customer-conditionally-by-identityprovider)
- [Client.authenticateConditionally(token:clientIdentityProvider:authID:context:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-authentication#authenticate-customer-conditionally-by-identityprovider) | | React Native | - [Synerise.Client.authenticate(token, clientIdentityProvider, authID, context, onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/client-authentication#authenticate-customer-by-identityprovider)
- [Synerise.Client.authenticateConditionally(token, clientIdentityProvider, authID context, onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/client-authentication#authenticate-customer-conditionally-by-identityprovider) | | Flutter | - [Synerise.client.authenticate(clientAuthContext, clientIdentityProvider, token)](/developers/mobile-sdk/method-reference/flutter/client-authentication#authenticate-customer-by-identityprovider)) |
**authId/authID** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
5. If the authentication was successful, Synerise provides your application with our JWT access token for the customer. Additionally, in the Synerise platform (`app.synerise.com`) you can define the following settings: - [Assignment of loyalty card](/docs/settings/tool/iam-for-apps/general#loyalty-card-assignment) - [JWT longevity](/docs/settings/tool/iam-for-apps/general#jwt-lifetime) - [Custom ID overwriting](/docs/settings/tool/iam-for-apps/general#custom-id-overwriting) - [External ID overwriting](/docs/settings/tool/iam-for-apps/general#external-id-overwriting) ## The list of methods --- ### Check if a customer is signed in This method checks if a customer is signed in through oAuth, Facebook, Sign in with Apple, or RaaS.
This method returns `false` if a customer is authenticated through [Simple Profile Authentication](/developers/mobile-sdk/user-identification-and-authorization/simple-authentication).
| OS | Method | |--------------|-------------------------------------------------------------------------------------------------------------------------------------------| | Android | [Client.isSignedIn()](/developers/mobile-sdk/method-reference/android/client-authentication#check-if-a-customer-is-signed-in-via-raas-oauth-facebook-apple) | | iOS | [Client.isSignedIn()](/developers/mobile-sdk/method-reference/ios/client-authentication#check-if-a-customer-is-signed-in-via-raas-oauth-facebook-apple) | | React Native | [Synerise.Client.isSignedIn()](/developers/mobile-sdk/method-reference/react-native/client-authentication#check-if-a-customer-is-signed-in-via-raas-oauth-facebook-apple) | | Flutter | [Synerise.client.isSignedIn()](/developers/mobile-sdk/method-reference/flutter/client-authentication#check-if-a-customer-is-signed-in-via-raas-oauth-facebook-apple) | ### Customer sign out This method signs out the customer. The method terminates the JWT token and ends the customer session. | OS | Method | |--------------|-----------------------------------------------------------------------------------------------------------------------| | Android | - [Client.signOut()](/developers/mobile-sdk/method-reference/android/client-authentication#sign-out-customer)
- [Client.signOut(mode, signOutFromAllDevices)](/developers/mobile-sdk/method-reference/android/client-authentication#sign-out-customer-with-mode-or-from-all-devices) | | iOS | - [Client.signOut()](/developers/mobile-sdk/method-reference/ios/client-authentication#sign-out-customer)
- [Client.signOut(mode:fromAllDevices:success:failure:)](/developers/mobile-sdk/method-reference/ios/client-authentication#sign-out-customer-with-mode-or-from-all-devices) | | React Native | - [Synerise.Client.signOut()](/developers/mobile-sdk/method-reference/react-native/client-authentication#sign-out-a-customer)
- [Synerise.Client.signOutWithMode(mode, fromAllDevices, onSuccess, onError)](/developers/mobile-sdk/method-reference/react-native/client-authentication#sign-out-customer-with-mode-or-from-all-devices) | | Flutter | [Synerise.client.signOut()](/developers/mobile-sdk/method-reference/flutter/client-authentication#sign-out-a-customer) | ## What's next --- When the customer's is signed in, you can implement [profile management methods](/developers/mobile-sdk/user-identification-and-authorization/identification-and-user-management#profile-management-methods) and [session management methods](/developers/mobile-sdk/user-identification-and-authorization/session-management). # Huawei integration in Flutter SDK ## Enable integration in the Synerise platform Before you start integrating Huawei services in your app, you must configure the integration in Synerise platform. For instructions, see ["Huawei integration"](/docs/settings/tool/huawei-integration). ## Configuration In order to integrate Huawei Mobile Services (HMS) with Synerise, you must add `.setMesaggingServiceType(MessagingServiceType.hms)` to your `Synerise.initializer`. We recommend passing `MessagingServiceType.hms` as an argument when you build the app for AppGallery.
More information about `Synerise.initializer` is available in ["Initialization"](/developers/mobile-sdk/installation-and-configuration/flutter#initialization).
## Implementing Huawei notifications in applications 1. Add the Huawei push library as a dependency and integrate it: [https://pub.dev/packages/huawei_push](https://pub.dev/packages/huawei_push). 2. Add an `onTokenEvent` callback to receive the HMS token. In the callback, send the token to Synerise by using [`Synerise.notifications.registerForNotifications`](/developers/mobile-sdk/method-reference/flutter/campaigns#register-for-push-notifications) method:
void _onTokenEvent(String event) {
       // Requested tokens can be obtained here
       setState(() {
         _token = event;
       });
       if (event != null && event.isNotEmpty) {
         Synerise.notifications.registerForNotifications(
           event,
           mobileAgreement: true,
           onSuccess: () {},
           onError: (error) {},
         );
         print("TokenEvent: " + _token);
       }
     }
3. Add a listener to trigger `getToken()` from the Huawei push library whenever the [`onRegistrationRequired`](/developers/mobile-sdk/listeners-and-delegates/flutter-listeners#notifications-listener) callback is called:
Synerise.notifications.listener((listener) {
         listener.onRegistrationRequired = () {
           getToken();
         };
       });
4. Add the `onMessageReceived` callback from the Huawei push library and pass the data to Synerise SDK:
Future<void> _onMessageReceived(RemoteMessage remoteMessage) async {
       // Called when a data message is received
       Map<String, String>? data = remoteMessage.getDataOfMap;
       if (data != null) {
         bool isSyneriseNotification =
         await Synerise.notifications.isSyneriseNotification(data);
         if (isSyneriseNotification == true) {
           Synerise.notifications.handleNotification(data);
           bool isSyneriseNotificationEncrypted = await Synerise.notifications
               .isNotificationEncrypted(data);
           if (isSyneriseNotificationEncrypted) {
             Map decryptedPayload =
             await Synerise.notifications.decryptNotification(data);
             developer.log(decryptedPayload.toString());
           }
         }
       }
     }
5. To make sure your callbacks work, use streams:
Future<void> initTokenStream() async {
       if (!mounted) return;
       Push.getTokenStream.listen(_onTokenEvent, onError: _onTokenError);
     }

     void getToken() {
       // Call this method to request for a token
       Push.getToken("");
     }

     Future<void> initMessageStream() async {
       if (!mounted) return;
       Push.onMessageReceivedStream
           .listen(_onMessageReceived, onError: _onMessageReceiveError);
     }
## Links and Deep Links In order to implement links and deep links, refer to [this](/developers/mobile-sdk/campaigns/action-handling#handling-actions-from-campaigns-in-android) instruction. ## Configuring notification encryption Instructions for encrypting push notifications are available [here](/developers/mobile-sdk/configuring-push-notifications/flutter#configure-notification-encryption). # Flutter ## Class reference - Flutter # Customer account management ## Get customer account information --- This method gets a customer’s account information. This method requires customer authentication.
The API key must have the `API_PERSONAL_INFORMATION_CLIENT_READ` permission from the **Client** group.
**Method name:** Client.getAccount() **Declaration:**
```Java public static IDataApiCall getAccount() ```
```Kotlin fun getAccount():IDataApiCall ```
**Parameters:** No parameters required. **Return Value:** [IDataApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#idataapicall)<[GetAccountInformation](/developers/mobile-sdk/class-reference/android/client#getaccountinformation)> object to execute the request. **Example:**
```Java private IDataApiCall getAccountCall; private void getAccount(boolean isFacebook) { if (getAccountCall != null) getAccountCall.cancel(); getAccountCall = Client.getAccount(); getAccountCall.execute(({ this.onGetAccountSuccessful() }), ({ this.onGetAccountFailure() }); } ```
```Kotlin private val getAccountCall:IDataApiCall private fun getAccount(isFacebook:Boolean) { if (getAccountCall != null) getAccountCall.cancel() getAccountCall = Client.getAccount() getAccountCall.execute(({ this.onGetAccountSuccessful() }), ({ this.onGetAccountFailure() }) } ```
## Get customer's events --- This method retrieves events for an authenticated customer. This method requires customer authentication. **Method name:** Client.getEvents(clientEventsQuery) **Declaration:**
```Java public static IDataApiCall> getEvents(ClientEventsQuery clientEventsQuery) ```
```Kotlin fun getEvents(clientEventsQuery:ClientEventsQuery):IDataApiCall> ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **clientEventsQuery** | ClientEventsQuery | yes | - | Object to create clientEvent query | **Return Value:** [IDataApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#idataapicall)> object to execute the request. **Example:**
```Java private IDataApiCall> getEventClientsCall; if (getEventClientsCall != null) getEventClientsCall.cancel(); getEventClientsCall = Client.getEvents(clientEventsQuery); getEventClientsCall.execute(({ this.onSuccess() }), ({ this.onFailure() }); ```
```Kotlin private val getEventClientsCall:IDataApiCall> if (getEventClientsCall != null) getEventClientsCall.cancel() getEventClientsCall = Client.getEvents(clientEventsQuery) getEventClientsCall.execute(({ this.onSuccess() }), ({ this.onFailure() }) ```
## Update customer account basic information --- This method updates a customer’s account’s basic information (without identification data: uuid, customId, email). This method requires the context object with the customer’s account information. Omitted fields are not modified. This method does not require customer authentication and can be used by anonymous profiles. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.22.0 | 5.21.0 | 0.24.0 | 1.4.0 |
The API key must have the `API_BASIC_INFORMATION_CLIENT_UPDATE` permission from the **Client** group.
**Method name:** Client.updateAccountBasicInformation(accountInformation) **Declaration:**
```Java public static IApiCall updateAccountBasicInformation(@NonNull UpdateAccountBasicInformation accountInformation) ```
```Kotlin fun updateAccountBasicInformation(@NonNull accountInformation:UpdateAccountBasicInformation):IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **accountInformation** | [UpdateAccountBasicInformation](/developers/mobile-sdk/class-reference/android/client#updateaccountbasicinformation) | yes | - | Builder Pattern object with the Customer's basic account information | **Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```Java if (apiCall != null) apiCall.cancel(); apiCall = Client.updateAccountBasicInformation(accountInformation); apiCall.execute(this::onSuccess, this::onFailure); ```
```Kotlin if (apiCall != null) apiCall.cancel() apiCall = Client.updateAccountBasicInformation(accountInformation) apiCall.execute(({ this.onSuccess() }), ({ this.onFailure() })) ```
## Update customer account information --- This method updates a customer’s account information. This method requires the context object with the customer’s account information. Omitted fields are not modified. This method requires customer authentication.
The API key must have the `API_PERSONAL_INFORMATION_CLIENT_UPDATE` permission from the **Client** group.
**Method name:** Client.updateAccount(accountInformation) **Declaration:**
```Java public static IApiCall updateAccount(@NonNull UpdateAccountInformation accountInformation) ```
```Kotlin fun updateAccount(@NonNull accountInformation:UpdateAccountInformation):IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **accountInformation** | [UpdateAccountInformation](/developers/mobile-sdk/class-reference/android/client#updateaccountinformation) | yes | - | Builder Pattern object with the Customer's account information | **Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```Java if (apiCall != null) apiCall.cancel(); apiCall = Client.updateAccount(accountInformation); apiCall.execute(this::onSuccess, this::onFailure); ```
```Kotlin if (apiCall != null) apiCall.cancel() apiCall = Client.updateAccount(accountInformation) apiCall.execute(({ this.onSuccess() }), ({ this.onFailure() })) ```
## Change customer's account password --- This method changes a customer’s password. This method requires customer authentication.
Returns the HTTP 403 status code if the provided old password is invalid.
The API key must have the `SAUTH_CHANGE_PASSWORD_CLIENT_UPDATE` permission from the **Client** group.
**Method name:** Client.changePassword(oldPassword, password) **Declaration:**
```java public static IApiCall changePassword(@NonNull String oldPassword, @NonNull String password) ```
```kotlin fun changePassword(@NonNull oldPassword:String, @NonNull password:String):IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **oldPassword** | String | yes | - | Client's old password | | **password** | String | yes | --- | Client's new password | **Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```java private IApiCall apiCall; if (apiCall != null) apiCall.cancel(); apiCall = Client.changePassword(oldPassword, password); apiCall.execute(this::onSuccess, this::onFailure); ```
```kotlin val apiCall:IApiCall if (apiCall != null) apiCall.cancel() apiCall = Client.changePassword(oldPassword, password) apiCall.execute(({ this.onSuccess() }), ({ this.onFailure() })) ```
## Request password reset for customer account --- This method requests a customer’s password reset with email. The customer will receive a token to the provided email address. That token is then used for the confirmation of password reset. This method requires the customer’s email. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_PASSWORD_RESET_CLIENT_CREATE` permission from the **Client** group.
**Method name:** Client.requestPasswordReset(resetRequest) **Declaration:**
```Java public static IApiCall requestPasswordReset(@NonNull PasswordResetRequest resetRequest) ```
```Kotlin fun requestPasswordReset(@NonNull resetRequest:PasswordResetRequest):IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **resetRequest** | PasswordResetRequest | yes | - | PasswordResetRequest object with the Client's email. | **Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```Java if (call != null) call.cancel(); call = Client.requestPasswordReset(new PasswordResetRequest(email)); EspressoTestingIdlingResource.increment(); call.execute(this::onSuccess, this::onFailure); ```
```Kotlin if (call != null) call.cancel() call = Client.requestPasswordReset(PasswordResetRequest(email)) call.execute(({ this.onSuccess() }), ({ this.onFailure() })) ```
## Confirm password reset for customer account --- This method confirm a customer’s password reset with the new password and token provided by password reset request. This method requires the customer’s new password and the confirmation token received by e-mail. This method is a global operation and doesn't require customer authentication.
The API key must have the `SAUTH_PASSWORD_RESET_CLIENT_CREATE` permission from the **Client** group.
**Method name:** Client.confirmPasswordReset(resetConfirmation) **Declaration:**
```java public static IApiCall confirmPasswordReset(@NonNull PasswordResetConfirmation resetConfirmation) ```
```kotlin fun confirmPasswordReset(@NonNull resetConfirmation:PasswordResetConfirmation):IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **resetConfirmation** | PasswordResetConfirmation | yes | - | PasswordResetConfirmation object with the Client's new password and confirmation token. | **Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```Java private IApiCall call; if (call != null) call.cancel(); call = Client.confirmPasswordReset(confirmation); call.execute(this::onSuccess, this::onFailure); ```
```Kotlin val call:IApiCall if (call != null) call.cancel() call = Client.confirmPasswordReset(confirmation) call.execute(({ this.onSuccess() }), ({ this.onFailure() })) ```
## Request email change for customer account --- This method requests a customer's email change. This method is a global operation and doesn't require customer authentication.
Returns the HTTP 403 status code if the provided token or the password is invalid.
The API key must have the `SAUTH_CHANGE_EMAIL_CLIENT_UPDATE` permission from the **Client** group.
**Method name:** Client.requestEmailChange(email, password, externalToken, authId) **Declaration:**
```Java public static IApiCall requestEmailChange(String email, String password, @Nullable String externalToken, @Nullable String authId) ```
```Kotlin fun requestEmailChange(email:String, password:String, @Nullable externalToken:String, @Nullable authId: String):IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | String | yes | - | Customer's email | | **password** | String | yes | -| Customer's password | | **externalToken** | String | no | - | ExternalToken should be used for Facebook, Oauth. For Synerise account, pass null | | **authId** | String | no | - | Optional identifier of authorization. For Synerise account, pass null. | **Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```Java IApiCall apiCall; apiCall = Client.requestEmailChange(email, password, null, null); apiCall.execute(this::onSuccess, this::onFailure); ```
```Kotlin val apiCall:IApiCall apiCall = Client.requestEmailChange(email, password, null, null) apiCall.execute(({ this.onSuccess() }), ({ this.onFailure() })) ```
## Confirm email change for customer account --- This method confirms an email change. This method is a global operation and doesn't require customer authentication.
Returns the HTTP 403 status code if the provided token is invalid.
The API key must have the `SAUTH_CHANGE_EMAIL_CLIENT_UPDATE` permission from the **Client** group.
**Method name:** Client.confirmEmailChange(token, newsletterAgreement) **Declaration:**
```java public static IApiCall confirmEmailChange(String token, boolean newsletterAgreement) ```
```kotlin fun confirmEmailChange(token:String, newsletterAgreement:Boolean):IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **token** | String | yes | - | Token from customer's email | | **newsletterAgreement** | boolean | yes | - | Newsletter agreement | **Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```java IApiCall apiCall; apiCall = Client.confirmEmailChange(token, newsletterAgreement.isChecked()); apiCall.execute(this::onSuccess, this::onFailure); ```
```kotlin val apiCall:IApiCall apiCall = Client.confirmEmailChange(token, newsletterAgreement.isChecked()) apiCall.execute(({ this.onSuccess() }), ({ this.onFailure() })) ```
## Request phone update on customer account --- This method requests a customer's phone update. A confirmation code is sent to the phone number. This method is a global operation and doesn't require customer authentication.
The API key must have the `API_PERSONAL_PHONE_CLIENT_CREATE` permission from the **Client** group.
**Method name:** Client.requestPhoneUpdate(phone) **Declaration:**
```Java public static IApiCall requestPhoneUpdate(String phone) ```
```Kotlin fun requestPhoneUpdate(phone:String):IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **phone** | String | yes | - | Customer's phone number. | **Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```Java IApiCall apiCall; apiCall = Client.requestPhoneUpdate(phone); apiCall.execute(this::onSuccess, this::onFailure); ```
```Kotlin val apiCall:IApiCall apiCall = Client.requestPhoneUpdate(phone) apiCall.execute(({ this.onSuccess() }), ({ this.onFailure() })) ```
## Confirm phone update on customer account --- This method confirms a phone number update. This action requires the new phone number and confirmation code as parameters. This method is a global operation and doesn't require customer authentication.
Returns the HTTP 403 status code if the provided UUID does not exist or the password is invalid.
The API key must have the `API_PERSONAL_PHONE_CLIENT_CREATE` permission from the **Client** group.
**Method name:** Client.confirmPhoneUpdate(phone, confirmationCode, smsAgreement) **Declaration:**
```Java public static IApiCall confirmPhoneUpdate(String phone, String confirmationCode, @Nullable Boolean smsAgreement) ```
```Kotlin fun confirmPhoneUpdate(phone:String, confirmationCode:String, @Nullable smsAgreement:Boolean):IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **phone** | String | yes | - | Phone number that will be confirmed | | **confirmationCode** | String | yes | - | Code received in SMS | | **smsAgreement** | Boolean | no | - | Optional SMS marketing agreement | **Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```Java IApiCall apiCall; apiCall = Client.confirmPhoneUpdate(phone, code, enableAgreement.isChecked() ? null : smsAgreement.isChecked()); apiCall.execute(this::onSuccess, this::onFailure); ```
```Kotlin val apiCall:IApiCall apiCall = Client.confirmPhoneUpdate(phone, code, if (enableAgreement.isChecked()) null else smsAgreement.isChecked()) apiCall.execute(({ this.onSuccess() }), ({ this.onFailure() })) ```
## Delete customer account by Identity Provider --- This method deletes a customer's account. This method requires customer authentication.
HTTP 403 status code is returned if the provided password or token is invalid.
The API key must have the `SAUTH_CLIENT_DELETE`, `SAUTH_OAUTH_CLIENT_DELETE`, `SAUTH_FACEBOOK_CLIENT_DELETE`, `SAUTH_APPLE_CLIENT_DELETE` permissions from the **Client** group.
**Method name:** Client.deleteAccount(clientAuthFactor, clientIdentityProvider, authId) **Declaration:**
```Java public static IApiCall deleteAccount(String clientAuthFactor, ClientIdentityProvider clientIdentityProvider, @Nullable String authId) ```
```Kotlin fun deleteAccount(clientAuthFactor:String, clientIdentityProvider:ClientIdentityProvider, authId:String):IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **clientAuthFactor** | String | yes | - | In case of oauth, fb, or google this is token. If you have synerise account this is password. | | **clientIdentityProvider** | [ClientIdentityProvider](/developers/mobile-sdk/class-reference/android/client#clientidentityprovider) | yes | - | Provider of your account. Example: FACEBOOK, OAUTH, SYNERISE, GOOGLE | | **authId** | String | no | - | Customer's optional unique identifier | **Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```Java IApiCall deleteCall = Client.deleteAccount(password, ClientIdentityProvider.SYNERISE, null); deleteCall.execute(this::onSuccess, this::onFailure); ```
```Kotlin val deleteCall = Client.deleteAccount(password, ClientIdentityProvider.SYNERISE, null) deleteCall.execute(({ this.onSuccess() }), ({ this.onFailure() })) ```
## Removed methods ### Delete customer account {#delete-customer-account} --- This method deletes a customer's account. This method requires customer authentication. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.11 | 3.6.13 | 0.9.12 | n/a | | Deprecated in: | 3.6.19 | 3.6.19 | 0.14.0 | n/a | | Removed in: | 5.0.0 | 6.0.0 | n/a | n/a |
Returns the HTTP 403 status code is returned if the provided password is invalid.
The API key must have the `SAUTH_CLIENT_DELETE` permission from the **Client** group.
**Replaced By:** [Delete customer account by Identity Provider](/developers/mobile-sdk/method-reference/android/client-account#delete-customer-account-by-identity-provider) **Method name:** Client.deleteAccount(password) **Declaration:**
```Java public static IApiCall deleteAccount(String password) ```
```Kotlin fun deleteAccount(password:String):IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **password** | String | yes | - | Customer's current password. | **Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```Java IApiCall deleteCall = Client.deleteAccount(password); deleteCall.execute(this::onSuccess, this::onFailure); ```
```Kotlin val deleteCall = Client.deleteAccount(password) deleteCall.execute(({ this.onSuccess() }), ({ this.onFailure() })) ```
### Delete customer account by OAuth {#delete-customer-account-by-oauth} --- This method deletes a customer's account by OAuth. This method requires customer authentication. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.11 | 3.6.13 | 0.9.12 | n/a | | Deprecated in: | 3.6.19 | 3.6.19 | 0.14.0 | n/a | | Removed in: | 5.0.0 | 6.0.0 | n/a | n/a |
The API key must have the `SAUTH_CLIENT_DELETE` and `SAUTH_OAUTH_CLIENT_DELETE` permissions from the **Client** group.
**Replaced By:** [Delete customer account by Identity Provider](/developers/mobile-sdk/method-reference/android/client-account#delete-customer-account-by-identity-provider) **Method name:** Client.deleteAccountByOAuth(accessToken, uuid) **Declaration:**
```Java public static IApiCall deleteAccountByOAuth(String accessToken, @Nullable String uuid) ```
```Kotlin fun deleteAccountByOAuth(accessToken:String, @Nullable uuid:String):IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **accessToken** | String | yes | - | user's token | | **uuid** | String | no | --- | Optional Customer UUID, internal UUID is used if this parameter is null | **Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```Java IApiCall deleteCall = Client.deleteAccountByOAuth(accessToken, uuid) deleteCall.execute(this::onSuccess, this::onFailure); ```
```Kotlin val deleteCall = Client.deleteAccountByOAuth(accessToken, uuid) deleteCall.execute(({ this.onSuccess() }), ({ this.onFailure() })) ```
### Delete customer account by Facebook {#delete-customer-account-by-facebook} --- This method deletes a customer's account by Facebook. This method requires customer authentication. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.3.8 | 3.3.0 | 0.9.12 | n/a | | Deprecated in: | 3.6.19 | 3.6.19 | 0.14.0 | n/a | | Removed in: | 5.0.0 | 6.0.0 | n/a | n/a |
The API key must have the `SAUTH_CLIENT_DELETE` and `SAUTH_FACEBOOK_CLIENT_DELETE` permissions from the **Client** group.
**Replaced By:** [Delete customer account by Identity Provider](/developers/mobile-sdk/method-reference/android/client-account#delete-customer-account-by-identity-provider) **Method name:** Client.deleteAccountByFacebook(facebookToken, uuid) **Declaration:**
```Java public static IApiCall deleteAccountByFacebook(String facebookToken, @Nullable String uuid) ```
```Kotlin fun deleteAccountByFacebook(facebookToken:String, @Nullable uuid:String):IApiCall ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **facebookToken** | String | yes | - | Customer's facebook token | | **uuid** | String | no | --- | Optional Customer UUID, internal UUID is used if this parameter is null | **Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```Java IApiCall deleteCall = Client.deleteAccountByFacebook(facebookToken, uuid) deleteCall.execute(this::onSuccess, this::onFailure); ```
```Kotlin val deleteCall = Client.deleteAccountByFacebook(facebookToken, uuid) deleteCall.execute(({ this.onSuccess() }), ({ this.onFailure() })) ```
# Campaigns ### SyneriseSource **Declared In:** lib/enums/injector/synerise_source.dart **Declaration:**
enum SyneriseSource {
  notSpecified('NOT_SPECIFIED'),
  simplePush('SIMPLE_PUSH'),
  banner('BANNER'),
  walkthrough('WALKTHROUGH'),
  inAppMessage('IN_APP_MESSAGE');
**Functions:** Converts from **String** to **SyneriseSource**.
```Dart static SyneriseSource getSyneriseSourceFromString(String string) ```
--- --- ### InAppMessageData Model representing an in-app message data.
This is a read-only class and it is not meant to be instantiated directly.
**Declared In:** lib/model/in_app/in_app_message_data.dart **Declaration:**
class InAppMessageData
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **campaignHash** | String | no | Identifier of the in-app message campaign. | | **variantIdentifier** | String | no | Identifier of the in-app message campaign variant. | | **additionalParameters** | Map | yes | Parameters additionally provided by the campaign. | | **isTest** | bool | no | Specifies if the object is from a test campaign. | # Customer session ## Refresh customer token --- This method refreshes the customer’s current token.
Returns an error if the token has expired and cannot be refreshed.
**Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func refreshToken(success: (() -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)refreshTokenWithSuccess:(nonnull void (^)(void))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **success** | (() -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```Swift Client.refreshToken(success: { _ in Client.retrieveToken(success: { (token) in // success let tokenString: String = token.tokenString let tokenOrigin: TokenOrigin = token.tokenOrigin }, failure: { (error) in // failure }) }, failure: { (error) in // failure }) ```
```Objective-C [SNRClient refreshTokenWithSuccess:^() { [SNRClient retrieveTokenWithSuccess:^(SNRToken *token) { // success NSString *tokenString = token.tokenString; SNRTokenOrigin tokenOrigin = token.tokenOrigin; } failure:^(SNRApiError *error) { // failure }]; } failure:^(SNRApiError *error) { // failure }]; ```
## Retrieve customer token --- This method retrieves the customer’s current, active token.
Returns an error if the token has expired and cannot be retrieved.
**Declared In:** Headers/SNRClient.h **Related To:** [Token](/developers/mobile-sdk/class-reference/ios/client#token) **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func retrieveToken(success: ((Token) -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)retrieveTokenWithSuccess:(nonnull void (^)(SNRToken *token))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | **success** | ((Token) -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```Swift Client.retrieveToken(success: { (token) in // success let tokenString: String = token.tokenString let tokenOrigin: TokenOrigin = token.tokenOrigin }, failure: { (error) in // failure }) ```
```Objective-C [SNRClient retrieveTokenWithSuccess:^(SNRToken *token) { // success NSString *tokenString = token.tokenString; SNRTokenOrigin tokenOrigin = token.tokenOrigin; } failure:^(SNRApiError *error) { // failure }]; ```
## Get current customer UUID --- This method retrieves the customer’s current UUID. **Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func getUUID() -> String ```
```Objective-C + (NSString *)getUUID; ```
**Return Value:** The method returns the customer's UUID as string. **Example:**
```Swift let clientUUID: String = Client.getUUID() ```
```Objective-C NSString *clientUUID = [SNRClient getUUID]; ```
## Get customer UUID for use in authentication --- This method retrieves the current UUID or generates a new one from a seed. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.15.0 | 5.15.0 | n/a | n/a |
This operation doesn't affect the customer session in the SDK.
**Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func getUUIDForAuthentication(authID: String) -> String ```
```Objective-C + (NSString *)getUUIDForAuthenticationWithAuthID:(NSString *)authID ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **authID** | String | yes | - | Seed for UUID generation | **Return Value:** The method returns the UUID for use in authentication as a string. **Example:**
```Swift let clientUUID: String = Client.getUUIDForAuthentication(authID: "AUTH_ID") ```
```Objective-C NSString *clientUUID = [SNRClient getUUIDForAuthenticationWithAuthID:@"AUTH_ID"]; ```
## Regenerate customer --- This method regenerates the UUID and clears the authentication token, login session, custom email, and custom identifier. This operation works only if the customer is anonymous. This operation clears the authentication token, login (if applicable), custom email, and custom identifier. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.3.10 | 3.3.5 | 0.9.0 | 0.7.0 | **Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func regenerateUUID() -> Void ```
```Objective-C + (void)regenerateUUID; ```
**Return Value:** No value is returned. ## Regenerate customer with identifier --- This method regenerates the UUID and clears the authentication token, login session, custom email, and custom identifier. This operation works only if the customer is anonymous. This operation clears the authentication token, login (if applicable), custom email, and custom identifier The optional `clientIdentifier` parameter is a seed for UUID generation. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.5 | 3.6.4 | 0.9.10 | 0.7.2 | **Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func regenerateUUID(clientIdentifier: String?) -> Void ```
```Objective-C + (void)regenerateUUIDWithClientIdentifier:(NSString *)clientIdentifier; ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **clientIdentifier** | String | no | - | Seed for UUID generation |
The **clientIdentifier** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** No value is returned. ## Destroy current session --- This method destroys the session completely. This method clears all session data (both client and anonymous) and removes cached data. Then, it regenerates the UUID and creates the new anonymous session. **Declared In:** Headers/SNRClient.h **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func destroySession() ```
```Objective-C + (void)destroySession ```
**Return Value:** No value is returned. **Example:**
```Swift Client.destroySession() ```
```Objective-C [SNRClient destroySession]; ```
# Campaigns ## SyneriseSource | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 5.0.0 | 6.0.0 | 0.18.0 | 0.8.0 | **Declared In:** Headers/SNRSyneriseSource.h **Declaration:**
```Swift enum SyneriseSource: Int { simplePush, inAppMessage } ```
```Objective-C typedef NS_ENUM(NSInteger, SNRSyneriseSource) { SNRSyneriseActivitySimplePush, SNRSyneriseActivityInAppMessage } ```
--- --- ## NotificationInfo **Declared In:** Headers/SNRNotificationInfo.h **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class NotificationInfo: BaseModel ```
```Objective-C @interface SNRNotificationInfo : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **campaignHashId** | String | no | Identifier of the notification campaign. | | **campaignTitle** | String | no | Identifier of the notification title. | | **payload** | [AnyHashable: Any] | yes | Payload of the notification. |
All properties are read-only.
--- --- ## PushNotificationsRegistrationOrigin **Declared In:** Headers/SNRSynerise.h **Declaration:**
```Swift enum PushNotificationsRegistrationOrigin: Int { .appStarted, .clientContextChange, .securityReason, .periodicJob } ```
```Objective-C typedef NS_ENUM(NSUInteger, SNRPushNotificationsRegistrationOrigin) { SNRPushNotificationsRegistrationOriginAppStarted, SNRPushNotificationsRegistrationOriginClientContextChange, SNRPushNotificationsRegistrationOriginSecurityReason, SNRPushNotificationsRegistrationOriginPeriodicJob } ```
--- --- ## InAppMessageData Model representing an in-app message data.
This is a read-only class and it is not meant to be instantiated directly.
**Declared In:** Headers/SNRInAppMessageData.h **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class InAppMessageData: BaseModel ```
```Objective-C @interface SNRInAppMessageData : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **campaignHash** | String | no | Identifier of the in-app message campaign. | | **variantIdentifier** | String | no | Identifier of the in-app message campaign variant. | | **additionalParameters** | [AnyHashable: Any] | yes | Parameters additionally provided by the campaign. | | **isTest** | Bool | no | Specifies if the object is from a test campaign. |
All properties are read-only.
--- --- ### SyneriseMethod Enum with a list of SDK methods that can be called from JavaScript in an in-app. See [Using in-app template builder](/docs/campaign/in-app-messages/creating-inapp-templates/creating-inapp-template#use-a-mobile-sdk-method) ## Deprecated symbols ### *SyneriseActivity* | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Deprecated in: | 5.0.0 | n/a | n/a | n/a | **Declared In:** Headers/SNRSyneriseActivity.h **Declaration:**
```Swift enum SyneriseActivity: Int { simplePush, banner, walkthrough, inAppMessage } ```
```Objective-C typedef NS_ENUM(NSInteger, SNRSyneriseActivity) { SNRSyneriseActivitySimplePush, SNRSyneriseActivityBanner, SNRSyneriseActivityWalkthrough, SNRSyneriseActivityInAppMessage } ```
--- --- ### *SyneriseActivityAction* | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Deprecated in: | 5.0.0 | n/a | n/a | n/a | **Declared In:** Headers/SNRSynerise.h **Declaration:**
```Swift enum SyneriseActivityAction: Int { none, hide } ```
```Objective-C typedef NS_ENUM(NSInteger, SNRSyneriseActivityAction) { SNRSyneriseActivityActionNone, SNRSyneriseActivityActionHide } ```
# Events ### Event Main event abstract class for inheriting classes.
This is an abstract class and it is not meant to be instantiated directly. You should use concrete subclasses instead.
**Declared In:** lib/model/tracker/event.dart **Declaration:**
abstract class Event
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **type** | String | no | Event type | | **label** | String | no | Can't be empty. This value isn't saved in persistent storage and can't be used in Decision or Automation Hubs. It isn't shown on a Profile card. | | **action** | String | no | Event action | | **parameters** | bool | no | Event parameters | --- --- ### CustomEvent
DO NOT send `transaction.charge` events as custom events.
Transactions must be tracked with these endpoints: - [`/v4/transactions`](https://hub.synerise.com/api-reference/data-management#operation/CreateATransaction) (single transaction) - [`/v4/transactions/batch`](https://hub.synerise.com/api-reference/data-management#operation/BatchAddOrUpdateTransactions) (multiple transactions)
Represents a custom client event. **Declared In:** lib/model/tracker/custom_event.dart **Inherits From:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) **Declaration:**
class CustomEvent extends Event
**Initializers:**
CustomEvent(String label, String action, Map<String, Object> parameters)
**Example:**
```Dart final paramMap = { "firstKeyCustomParam": "TEST_1", "secondKeyCustomParam": "TEST_2", }; CustomEvent event = CustomEvent("LABEL", "ACTION", paramMap); ```
--- --- ### PushViewedEvent Represents a 'client viewed push' event. This event is used for push message interaction tracking. **Declared In:** lib/events/push/push_viewed_event.dart **Inherits From:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/flutter/events#customevent) **Declaration:**
class PushViewedEvent extends CustomEvent
**Initializers:**
PushViewedEvent(
    String label,
    Map<String, Object>? parameters,
  )
--- --- ### PushClickedEvent Represents a 'client clicked push' event. This event is used for push message interaction tracking. **Declared In:** lib/events/push/push_clicked_event.dart **Inherits From:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/flutter/events#customevent) **Declaration:**
class PushClickedEvent extends CustomEvent
**Initializers:**
PushClickedEvent(
    String label,
    Map<String, Object>? parameters,
  )
--- --- ### PushCancelledEvent Represents a 'client dismissed push' event. This event is used for push message interaction tracking. **Declared In:** lib/events/push/push_cancelled_event.dart **Inherits From:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/flutter/events#customevent) **Declaration:**
class PushCancelledEvent extends CustomEvent
**Initializers:**
PushCancelledEvent(
    String label,
    Map<String, Object>? parameters,
  )
--- --- ### CartEvent Main cart action abstract class for inheriting classes.
This is an abstract class and it is not meant to be instantiated directly. You should use concrete `CartEvent` subclasses instead.
**Declared In:** lib/events/cart/cart_event.dart **Inherits From:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/flutter/events#customevent) **Declaration:**
class CartEvent extends CustomEvent
**Initializers:**
CartEvent(String label, String action, String sku, UnitPrice finalPrice, int quantity, Map<String, Object>? parameters)
**Methods:** This method sets a value for the `name` parameter.
void setName(String name)
--- This method sets a value for the `category` parameter.
void setCategory(String category)
--- This method sets values for the `categories` parameter.
void setCategories(List<String> categories)
--- This method sets a value for the `offline` parameter.
void setOffline(bool offline)
--- This method sets the value of the `regularPrice` parameter.
void setRegularPrice(UnitPrice regularPrice)
--- This method sets the value of the `discountedPrice` parameter.
void setDiscountedPrice(UnitPrice discountedPrice)
--- This method sets the value of the `url` parameter.
void setUrl(String url)
--- This method sets the value of the `producer` parameter (producer can signify a brand of the item).
void setProducer(String producer)
--- --- ### UnitPrice **Declared In:** lib/model/tracker/unit_price.dart **Declaration:**
class UnitPrice
**Initializers:**
UnitPrice(
   int amount,
   String currency)
--- --- ### ProductAddedToCartEvent Represents a 'client added product to cart' event. **Declared In:** lib/events/cart/product_added_to_cart_event.dart **Inherits From:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/flutter/events#customevent) **Declaration:**
class ProductAddedToCartEvent extends CartEvent
**Initializers:**
ProductAddedToCartEvent(String label, String sku, UnitPrice finalPrice, int quantity, Map<String, Object>? parameters)
--- --- ### ProductRemovedFromCartEvent Represents a 'client removed product from cart' event. **Declared In:** lib/events/cart/product_removed_from_cart_event.dart **Inherits From:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/flutter/events#customevent) **Declaration:**
class ProductRemovedFromCartEvent extends CartEvent
**Initializers:**
ProductRemovedFromCartEvent(String label, String sku, UnitPrice finalPrice, int quantity, Map<String, Object>? parameters)
--- --- ### ProductViewedEvent Represents a 'client viewed product' event. **Declared In:** lib/events/product/product_viewed_event.dart **Inherits From:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/flutter/events#customevent) **Declaration:**
class ProductViewedEvent extends CustomEvent
**Initializers:**
ProductViewedEvent(
    String label,
    String productId,
    String name,
    Map<String, Object>? parameters,
  )
**Methods:** This method sets a value for the `category` parameter.
void setCategory(String category)
--- This method sets the value of the `url` parameter.
void setUrl(String url)
--- --- ### ProductAddedToFavoritesEvent Represents a 'client added product to favorites' event. **Declared In:** lib/events/product/product_added_to_favorites_event.dart **Inherits From:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/flutter/events#customevent) **Declaration:**
class ProductAddedToFavouritesEvent extends CustomEvent
**Initializers:**
ProductAddedToFavoritesEvent(
    String label,
    Map<String, Object>? parameters,
  )
--- --- ### LoggedInEvent Represents a 'client logged in' event. **Declared In:** lib/events/auth/logged_in_event.dart **Inherits From:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/flutter/events#customevent) **Declaration:**
class LoggedInEvent extends CustomEvent
**Initializers:**
LoggedInEvent(
    String label,
    Map<String, Object>? parameters,
  )
--- --- ### LoggedOutEvent Represents a 'client logged out' event. **Declared In:** lib/events/auth/logged_out_event.dart **Inherits From:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/flutter/events#customevent) **Declaration:**
class LoggedOutEvent extends CustomEvent
**Initializers:**
LoggedOutEvent(String label, Map<String, Object>? parameters)
--- --- ### RegisteredEvent Represents a 'client registered' event. **Declared In:** lib/events/auth/registered_event.dart **Inherits From:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/flutter/events#customevent) **Declaration:**
class RegisteredEvent extends CustomEvent
**Initializers:**
RegisteredEvent(String label, Map<String, Object>? parameters)
--- --- ### RecommendationEvent Main recommendation abstract class for inheriting classes.
This is an abstract class and it is not meant to be instantiated directly. You should use concrete `RecommendationEvent` subclasses instead.
**Declared In:** lib/events/recommendation/recommendation_event.dart **Inherits From:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/flutter/events#customevent) **Declaration:**
class RecommendationEvent extends CustomEvent
**Initializers:**
RecommendationEvent(String label, String action, Map<String, Object>? parameters)
--- --- ### RecommendationSeenEvent Represents a 'client saw a recommendation' event. **Declared In:** lib/events/recommendation/recommendation_seen_event.dart **Inherits From:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/flutter/events#customevent) **Declaration:**
class RecommendationSeenEvent extends RecommendationEvent
**Initializers:**
RecommendationSeenEvent(String label, String action, String productId, String productName, String campaignId, String campaignHash, Map<String, Object>? parameters)
--- --- ### RecommendationViewEvent Represents a 'client viewed a recommendation' event. **Declared In:** lib/events/recommendation/recommendation_view_event.dart **Inherits From:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/flutter/events#customevent) **Declaration:**
class RecommendationViewEvent extends RecommendationEvent
**Initializers:**
RecommendationViewEvent(String label, String action, List<String>? items, String campaignId, String campaignHash, String correlationId, Map<String, Object>? parameters)
--- --- ### RecommendationClickEvent Represents a 'client clicked a recommendation' event. **Declared In:** lib/events/recommendation/recommendation_click_event.dart **Inherits From:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/flutter/events#customevent) [RecommendationEvent](/developers/mobile-sdk/class-reference/flutter/events#recommendationevent) **Declaration:**
class RecommendationClickEvent extends RecommendationEvent
**Initializers:**
RecommendationClickEvent(String label, String action, String productId, String productName, String campaignId, String campaignHash,
      Map<String, Object>? parameters)
--- --- ### VisitedScreenEvent Represents a 'client visited screen' event. This can be used for mobile screen usage tracking. **Declared In:** lib/events/other/visited_screen_event.dart **Inherits From:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/flutter/events#customevent) **Declaration:**
class VisitedScreenEvent extends CustomEvent
**Initializers:**
VisitedScreenEvent(
    String label,
    Map<String, Object>? parameters,
  )
--- --- ### HitTimerEvent Represents a 'client hit timer' event. This could be used for profiling or activity time monitoring - you can send a `HitTimerEvent` when your client starts doing something and send it once again when they finish, but this time with the different time signature. Then you can use our analytics engine to measure, for example, average activity time. **Declared In:** lib/events/other/hit_timer_event.dart **Inherits From:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/flutter/events#customevent) **Declaration:**
class HitTimerEvent extends CustomEvent
**Initializers:**
HitTimerEvent(
    String label,
    Map<String, Object>? parameters,
  )
--- --- ### SearchedEvent Represents a 'client searched' event. **Declared In:** lib/events/other/searched_event.dart **Inherits From:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/flutter/events#customevent) **Declaration:**
class SearchedEvent extends CustomEvent
**Initializers:**
SearchedEvent(
    String label,
    Map<String, Object>? parameters,
  )
--- --- ### SharedEvent Represents a 'client shared' event. **Declared In:** lib/events/other/shared_event.dart **Inherits From:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/flutter/events#customevent) **Declaration:**
class SharedEvent extends CustomEvent
**Initializers:**
SharedEvent(
    String label,
    Map<String, Object>? parameters,
  )
--- --- ### AppearedInLocationEvent Represents a 'client appeared in location' event. **Declared In:** lib/events/other/appeared_in_location_event.dart **Inherits From:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/flutter/events#customevent) **Declaration:**
class AppearedInLocationEvent extends CustomEvent
**Initializers:**
AppearedInLocationEvent(
    String label,
    double lat,
    double lon,
    Map<String, Object>? parameters,
  )
# Promotions and Vouchers ## Promotions --- ### PromotionResponse **Declared In:** lib/classes/models/Promotions/PromotionResponse.js **Related To:** [Promotion](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotion) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
class PromotionResponse extends BaseModel
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **totalCount** | number | no | Total count of promotions | | **totalPages** | number | no | Total count of pages | | **page** | number | no | Current page | | **limit** | number | no | Limit of promotions per page | | **code** | number | no | HTTP code of the response | | **items** | [Array](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotion) | no | List of promotion items | --- --- ### Promotion **Declared In:** lib/classes/models/Promotions/Promotion.js **Related To:** [PromotionResponse](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotionresponse) [PromotionStatus](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotionstatus) [PromotionType](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotiontype) [PromotionDetails](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotiondetails) [PromotionItemScope](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotionitemscope) [PromotionDiscountType](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotiondiscounttype) [PromotionDiscountMode](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotiondiscountmode) [PromotionDiscountModeDetails](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotiondiscountmodedetails) [PromotionImage](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotionimage) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
class Promotion extends BaseModel
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **uuid** | string | no | Promotion's UUID | | **code** | string | no | Promotion's code | | **status** | [PromotionStatus](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotionstatus) | yes | Promotion's status | | **type** | [PromotionType](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotiontype) | yes | Promotion's type | | **details** | [PromotionDetails](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotiondetails) | yes | Promotion's details | | **redeemLimitPerClient** | number | yes | Redemption limit per customer | | **redeemQuantityPerActivation** | number | yes | Redemption quantity per activation | | **currentRedeemedQuantity** | number | no | Current redemption quantity | | **currentRedeemLimit** | number | no | Current redemption limit | | **activationCounter** | number | no | Promotion's activation counter | | **possibleRedeems** | number | no | Maximum number of promotion redemptions | | **requireRedeemedPoints** | number | yes | Required redeemed points | | **discountType** | [PromotionDiscountType](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotiondiscounttype) | yes | Discount type | | **discountValue** | number | no | Discount value | | **discountMode** | [PromotionDiscountMode](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotiondiscountmode) | no | Discount mode | | **discountModeDetails** | [PromotionDiscountModeDetails](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotiondiscountmodedetails) | yes | Discount mode details | | **priority** | number | no | Promotion's priority | | **price** | number | no | Item price | | **itemScope** | [PromotionItemScope](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotionitemscope) | no | Promotion's item scope | | **minBasketValue** | number | yes | Minimum basket value | | **maxBasketValue** | number | yes | Maximum basket value | | **name** | string | no | Promotion's name | | **headline** | string | yes | Promotion's headline | | **descriptionText** | string | yes | Promotion's description | | **images** | [Array<[PromotionImage](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotionimage)> | yes | List of promotion images | | **startAt** | Date | yes | Start time of a promotion | | **expireAt** | Date | yes | Expiration time of the promotion | | **lastingAt** | Date | yes | Date when the promotion expires for the current profile | | **lastingTime** | number | yes | Duration of the promotion in seconds | | **displayFrom** | string | yes | Date as a string when the promotion starts being displayed | | **displayTo** | string | yes | Date as a string when the promotions ends being displayed | | **catalogIndexItems** | Array | yes | List of item indexes | | **params** | object | yes | Promotion's custom parameters | | **tags** | Array | yes | Promotion's custom tags | --- --- ### PromotionStatus **Declared In:** lib/classes/models/Promotions/PromotionStatus.js **Related To:** [Promotion](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotion) **Declaration:**
enum PromotionStatus {
  None = 'NONE',
  Active = 'ACTIVE',
  Assigned = 'ASSIGNED',
  Redeemed = 'REDEEMED',
}
**Functions:** Converts from **PromotionStatus** to **string**.
function PromotionStatusToString(promotionStatus: PromotionStatus): string
--- Converts from **string** to **PromotionStatus**.
function PromotionStatusFromString(string: string): PromotionStatus
--- --- ### PromotionType **Declared In:** lib/classes/models/Promotions/PromotionType.js **Related To:** [Promotion](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotion) **Declaration:**
enum PromotionType {
  Unknown = 'UNKNOWN',
  MembersOnly = 'MEMBERS_ONLY',
  Custom = 'CUSTOM',
  General = 'GENERAL',
}
**Functions:** Converts from **PromotionType** to **string**.
function PromotionTypeToString(promotionType: PromotionType): string
--- Converts from **string** to **PromotionType**.
function PromotionTypeFromString(string: string): PromotionType
--- --- ### PromotionItemScope **Declared In:** lib/classes/models/Promotions/PromotionItemScope.js **Related To:** [Promotion](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotion) **Declaration:**
enum PromotionItemScope {
    LineItem = 'LINE_ITEM',
    Basket = 'BASKET'
}
**Functions:** Converts from **PromotionItemScope** to **string**.
function PromotionItemScopeToString(promotionItemScope: PromotionItemScope): string
--- Converts from **string** to **PromotionItemScope**.
function PromotionItemScopeFromString(string: string): PromotionItemScope
--- --- ### PromotionDetails **Declared In:** lib/classes/models/Promotions/PromotionDetails.js **Related To:** [PromotionDiscountTypeDetails](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotiondiscounttypedetails) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
class PromotionDetails extends BaseModel {
  discountType: PromotionDiscountTypeDetails;
}
**Properties:** Property | Type | Optional | Description | | --- | --- | --- | --- | | **discountType** | [PromotionDiscountTypeDetails](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotiondiscounttypedetails) | yes | Discount details | --- --- ### PromotionDiscountTypeDetails **Declared In:** lib/classes/models/Promotions/PromotionDiscountTypeDetails.js **Related To:** [PromotionDetails](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotiondetails) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
class PromotionDiscountTypeDetails extends BaseModel {
  name: string;
  outerScope: boolean;
  requiredItemsCount: number;
  discountedItemsCount: number;
}
**Properties:** Property | Type | Optional | Description | | --- | --- | --- | --- | | **name** | string | no | Discount’s name | | **outerScope** | boolean | no | When `true`, the items required to trigger the promotion are different than the items included in that promotion. | | **requiredItemsCount** | number | no | Number of items required to qualify for the discount | | **discountedItemsCount** | number | no | Number of discounted items | --- --- ### PromotionDiscountMode **Declared In:** lib/classes/models/Promotions/PromotionDiscountMode.js **Related To:** [Promotion](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotion) **Declaration:**
enum PromotionDiscountMode {
    Static = 'STATIC',
    Step = 'STEP'
}
**Functions:** Converts from **PromotionDiscountMode** to **string**.
function PromotionDiscountModeToString(promotionDiscountMode: PromotionDiscountMode): string
--- Converts from **string** to **PromotionDiscountMode**.
function PromotionDiscountModeFromString(string: string): PromotionDiscountMode
--- --- ### PromotionDiscountModeDetails **Declared In:** lib/classes/models/Promotions/PromotionDiscountModeDetails.js **Related To:** [PromotionDiscountStep](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotiondiscountstep) [PromotionDiscountUsageTrigger](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotiondiscountusagetrigger) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
class PromotionDiscountModeDetails extends BaseModel {
  discountSteps: Array<PromotionDiscountStep>;
  discountUsageTrigger: PromotionDiscountUsageTrigger;
}
**Properties:** Property | Type | Optional | Description | | --- | --- | --- | --- | | **discountSteps** | Array<[PromotionDiscountStep](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotiondiscountstep)> | no | List of discount steps | | **discountUsageTrigger** | [PromotionDiscountUsageTrigger](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotiondiscountusagetrigger) | no | Usage trigger for the discount | --- --- ### PromotionDiscountStep **Declared In:** lib/classes/models/Promotions/PromotionDiscountStep.js **Related To:** [PromotionDiscountModeDetails](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotiondiscountmodedetails) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
class PromotionDiscountStep extends BaseModel {
  discountValue: number;
  usageThreshold: number;
}
**Properties:** Property | Type | Optional | Description | | --- | --- | --- | --- | | **discountValue** | number | no | Value of the discount | | **usageThreshold** | number | no | Usage threshold | --- --- ### PromotionDiscountUsageTrigger **Declared In:** lib/classes/models/Promotions/PromotionDiscountUsageTrigger.js **Related To:** [Promotion](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotion) **Declaration:**
enum PromotionDiscountUsageTrigger {
    Transaction = 'TRANSACTION',
    Redeem = 'REDEEM'
}
**Functions:** Converts from **PromotionDiscountUsageTrigger** to **string**.
function PromotionDiscountUsageTriggerToString(promotionDiscountUsageTrigger: PromotionDiscountUsageTrigger): string
--- Converts from **string** to **PromotionDiscountUsageTrigger**.
function PromotionDiscountUsageTriggerFromString(string: string): PromotionDiscountUsageTrigger
--- --- ### PromotionImage **Declared In:** lib/classes/models/Promotions/PromotionImage.js **Related To:** [Promotion](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotion) [PromotionImageType](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotionimagetype) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
class PromotionImage extends BaseModel {
  url: string;
  type: PromotionImageType;
}
**Properties:** Property | Type | Optional | Description | | --- | --- | --- | --- | | **url** | string | no | URL of the image | | **type** | [PromotionImageType](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotionimagetype) | no | Image type | --- --- ### PromotionImageType **Declared In:** lib/classes/models/Promotions/PromotionImageType.js **Related To:** [PromotionImage](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotionimage) **Declaration:**
enum PromotionImageType {
  Image = 'image',
  Thumbnail = 'thumbnail'
}
**Functions:** Converts from **PromotionImageType** to **string**.
function PromotionImageTypeToString(promotionImageType: PromotionImageType): string
--- Converts from **string** to **PromotionImageType**.
function PromotionImageTypeFromString(string: string): PromotionImageType
--- --- ### PromotionDiscountType **Declared In:** lib/classes/models/Promotions/PromotionDiscountType.js **Related To:** [Promotion](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotion) **Declaration:**
enum PromotionDiscountType {
  None = 'NONE',
  Percent = 'PERCENT',
  Amount = 'AMOUNT',
  TwoForOne = '2_FOR_1',
  Points = 'POINTS',
  Multibuy = 'MULTIBUY',
}
**Functions:** Converts from **PromotionDiscountType** to **string**.
function PromotionDiscountTypeToString(promotionDiscountType: PromotionDiscountType): string
--- Converts from **string** to **PromotionDiscountType**.
function PromotionDiscountTypeFromString(string: string): PromotionDiscountType
--- --- ### PromotionIdentifier **Declared In:** lib/classes/models/Promotions/PromotionIdentifier.js **Declaration:**
class PromotionIdentifier {
  key: string;
  value: string;
}
**Properties:** Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **key** | string | yes | | Promotion identifier type (see [PromotionIdentifierKey enum](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotionidentifierkey))| | **value** | string | yes | | Promotion identifier value | **Initializers:**
constructor(key: PromotionIdentifierKey, value: string)
--- --- ### PromotionIdentifierKey **Declared In:** lib/classes/models/Promotions/PromotionIdentifierKey.js **Declaration:**
enum PromotionIdentifierKey {
  Uuid = 'UUID',
  Code = 'CODE',
}
--- --- ### PromotionsApiQuery Object for setting parameters to facilitate fetching promotions from the API. **Declared In:** lib/classes/models/api_queries/PromotionsApiQuery.js **Related To:** [PromotionResponse](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotionresponse) [Promotion](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotion) **Inherits From:** [BaseApiQuery](/developers/mobile-sdk/class-reference/react-native/miscellaneous#baseapiquery) **Declaration:**
class PromotionsApiQuery extends BaseApiQuery
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **statuses** | [Array](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotionstatus) | no | [] | List of promotion statuses for query | | **types** | [Array](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#promotiontype) | no | [] | List of promotion types for query |
- Check the list of promotion sorting keys available in [Loyalty - Promotion sorting options](/developers/mobile-sdk/loyalty#promotion-sorting-options) section. - See [ApiQuerySortingOrderString](/developers/mobile-sdk/class-reference/react-native/miscellaneous#apiquerysortingorder) to check ordering options.
**Initializers:**
constructor()
--- --- ## Vouchers --- ### AssignVoucherResponse **Declared In:** lib/classes/models/Vouchers/AssignVoucherResponse.js **Related To:** [AssignVoucherData](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#assignvoucherdata) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
class AssignVoucherResponse extends BaseModel
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **message** | string | no | Message from the Voucher assignment response | | **assignVoucherData** | [AssignVoucherData](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#assignvoucherdata) | yes | List of vouchers in a pool | --- --- ### VoucherCodesResponse **Declared In:** lib/classes/models/Vouchers/VoucherCodesResponse.js **Related To:** [VoucherCodesData](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#vouchercodesdata) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
class VoucherCodesResponse extends BaseModel
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **items** | Array<[VoucherCodesData](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#vouchercodesdata)> | no | List of voucher items | --- --- ### AssignVoucherData **Declared In:** lib/classes/models/Vouchers/AssignVoucherData.js **Related To:** [AssignVoucherResponse](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#assignvoucherresponse) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
class AssignVoucherData extends BaseModel
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **code** | string | no | Voucher's code | | **expireIn** | Date | yes | Voucher's expiration date | | **redeemAt** | Date | yes | Voucher's redemption date | | **assignedAt** | Date | yes | Voucher's assignment date | | **createdAt** | Date | no | Voucher's creation date | | **updatedAt** | Date | no | Voucher's update date | --- --- ### VoucherCodesData **Declared In:** lib/classes/models/Vouchers/VoucherCodesData.js **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
class VoucherCodesData extends BaseModel
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **code** | string | no | Voucher's code | | **status** | [VoucherCodeStatus](/developers/mobile-sdk/class-reference/react-native/promotions-and-vouchers#vouchercodestatus) | no | Voucher's status | | **clientId** | string | no | ID of the customer to whom the voucher is assigned | | **clientUuid** | string | no | UUID of the customer to whom the voucher is assigned | | **poolUuid** | string | no | Voucher's pool ID | | **expireIn** | string | no | Voucher's expiration date | | **redeemAt** | Date | no | Voucher's redemption date | | **assignedAt** | Date | no | Voucher's assignment date | | **createdAt** | Date | no | Voucher's creation date | | **updatedAt** | Date | no | Voucher's update date| --- --- ### VoucherCodeStatus **Declared In:** lib/classes/models/Vouchers/VoucherCodeStatus.js **Declaration:**
enum VoucherCodeStatus {
  Unassigned = 'UNASSIGNED',
  Assigned = 'ASSIGNED',
  Redeemed = 'REDEEMED',
  Canceled = 'CANCELED',
}
**Functions:** Converts from **VoucherCodeStatus** to **string**.
function VoucherCodeStatusToString(voucherCodeStatus: VoucherCodeStatus): string
--- Converts from **string** to **VoucherCodeStatus**.
function VoucherCodeStatusFromString(string: string): VoucherCodeStatus
# Recommendations and Documents ## Recommendations --- ### RecommendationResponse Model representing a response with recommendations.
This is a read-only class and it is not meant to be instantiated directly.
**Declared In:** lib/model/content/recommendation_response.dart **Related To:** [Recommendation](/developers/mobile-sdk/class-reference/flutter/recommendations-and-documents#recommendation) **Declaration:**
class RecommendationResponse
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **name** | String | no | Name of the recommendation campaign | | **campaignHash** | String | no | Hash (UUID) of the recommendation campaign | | **campaignID** | String | no | ID of the recommendation campaign | | **items** | List<[Recommendation](/developers/mobile-sdk/class-reference/flutter/recommendations-and-documents#recommendation)> | no | List of items in the recommendation | | **correlationID** | String | no | Recommendation's correlation ID. It can be added to a `recommendation.click` event to associate it with the recommendation request | | **schema** | String | no | Schema of the document which contains the recommendation | | **slug** | String | no | Slug of the document | | **uuid** | String | no | UUID of the document | --- --- ### Recommendation Model representating a recommendation item data.
This is a read-only class and it is not meant to be instantiated directly.
**Declared In:** lib/model/content/recommendation.dart **Related To:** [RecommendationResponse](/developers/mobile-sdk/class-reference/flutter/recommendations-and-documents#recommendationresponse) **Declaration:**
class Recommendation
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **itemID** | String | no | Product's GTIN | | **attributes** | Map | no | Product's recommendation attributes | --- --- ### RecommendationOptions **Declared In:** lib/model/content/recommendation_options.dart **Related To:** [RecommendationFiltersJoinerRule](/developers/mobile-sdk/class-reference/flutter/recommendations-and-documents#recommendationfiltersjoinerrule) **Declaration:**
class RecommendationOptions
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **slug** | String | no | Unique identifier of a document which includes a recommendation insert | | **productID** | String | yes | Item identifier (for single ID) | | **itemsIds** | List | yes | List of item identifiers (for multiple IDs) | | **itemsExcluded** | List | yes | Items that will be excluded from the generated recommendations | | **additionalFilters** | String | yes | Additional filters. These are merged with the campaign's own filters according to the logic in **filtersJoiner** | | **filtersJoiner** | [RecommendationFiltersJoinerRule](/developers/mobile-sdk/class-reference/flutter/recommendations-and-documents#recommendationfiltersjoinerrule) | yes | Defines the logic of merging additionalFilters with the campaign's existing filters | | **additionalElasticFilters** | String | yes | Additional elastic filters. These are merged with the campaign's own elastic filters according to the logic in **elasticFiltersJoiner** | | **elasticFiltersJoiner** | [RecommendationFiltersJoinerRule](/developers/mobile-sdk/class-reference/flutter/recommendations-and-documents#recommendationfiltersjoinerrule) | yes | Defines the logic of merging **additionalElasticFilters** with the campaign's existing elastic filters | | **displayAttribute** | List | yes | An array of item attributes which value will be returned in a recommendation response | | **includeContextItems** | bool | yes | When true, the recommendation response will include context item metadata | **Initializers:**
RecommendationOptions recommendationOptions = RecommendationOptions(
        slug: slug,
        productID: productId);
--- --- ### RecommendationFiltersJoinerRule **Declared In:** lib/model/content/recommendation_options.dart **Declaration:**
enum RecommendationFiltersJoinerRule {
  and('and'),
  or('or'),
  replace('replace');
**Functions:** Converts from **RecommendationFiltersJoinerRule** to **String**.
```Dart String recommendationFiltersJoinerRuleAsString() ```
Converts from **String** to **RecommendationFiltersJoinerRule**.
```Dart static RecommendationFiltersJoinerRule? getRecommendationFiltersJoinerRuleFromString(String string) ```
--- --- ## Documents --- --- ### DocumentApiQuery Object for setting parameters to facilitate fetching documents from the API. **Declared In:** lib/model/content/document_api_query.dart **Declaration:**
class DocumentApiQuery
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **slug** | String | no | Unique identifier of a document | **Properties used only if the document includes a recommendation insert:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **productId** | String | yes | Item identifier of the context item | | **itemsIds** | List | yes | List of item identifiers, used for multiple item context | | **itemsExcluded** | List | yes | Items that will be excluded from the generated recommendations | | **additionalFilters** | String | yes | Additional filters. These are merged with the campaign's own filters according to the logic in **filtersJoiner** | | **filtersJoiner** | [RecommendationFiltersJoinerRule](/developers/mobile-sdk/class-reference/flutter/recommendations-and-documents#recommendationfiltersjoinerrule) | no | Defines the logic of merging additionalFilters with the campaign's existing filters | | **additionalElasticFilters** | String | yes | Additional elastic filters. These are merged with the campaign's own elastic filters according to the logic in **elasticFiltersJoiner** | | **elasticFiltersJoiner** | [RecommendationFiltersJoinerRule](/developers/mobile-sdk/class-reference/flutter/recommendations-and-documents#recommendationfiltersjoinerrule) | no | Defines the logic of merging **additionalElasticFilters** with the campaign's existing elastic filters | | **displayAttribute** | List | yes | An array of item attributes which value will be returned in a recommendation response | | **includeContextItems** | bool | yes | When true, the recommendation response will include context item metadata | **Initializers:**
DocumentApiQuery({
  required this.slug,
  this.productId,
  this.itemsIds,
  this.itemsExcluded,
  this.additionalFilters,
  this.filtersJoiner,
  this.additionalElasticFilters,
  this.elasticFiltersJoiner,
  this.displayAttribute,
  this.includeContextItems = false
});
--- --- ### Document **Declared In:** lib/model/content/document.dart **Declaration:**
class Document
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **uuid** | String | no | Document's identifier (this parameter was called **identifier** before version 2.0.0)| | **slug** | String | no | Document's slug | | **schema** | String | no | Document's schema type | | **content** | Map | yes | Document's content |
All properties are read-only.
--- --- ## Removed symbols --- ### DocumentsApiQuery{#documentsapiquery} The object to set parameters easily for fetching documents from API. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.5.10 | 3.5.1 | 0.9.10 | 0.2.0 | | Deprecated in: | 4.13.0 | 5.5.0 | 0.17.0 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | 2.0.0 | The object to set parameters easily for fetching documents from API. **Declared In:** lib/model/content/documents_api_query.dart **Related To:** [DocumentsApiQueryType](/developers/mobile-sdk/class-reference/flutter/recommendations-and-documents#documentsapiquerytype) **Declaration:**
class DocumentsApiQuery
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **type** | [DocumentsApiQueryType](/developers/mobile-sdk/class-reference/flutter/recommendations-and-documents#documentsapiquerytype) | no | .bySchema | Query type | | **typeValue** | String | no | null | Value for query type | | **version** | String | yes | null | Specifies the document version | **Initializers:**
DocumentsApiQuery({required this.type, required this.typeValue, this.version})
--- --- ### DocumentsApiQueryType{#documentsapiquerytype} | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.5.10 | 3.5.1 | 0.9.10 | 0.2.0 | | Deprecated in: | 4.13.0 | 5.5.0 | 0.17.0 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | 2.0.0 | **Declared In:** lib/enums/content/documents_api_query_type.dart **Declaration:**
enum DocumentsApiQueryType {
  schema('by-schema');
}
# Event tracking ## Set Tracker Delegate --- This method sets an object for Tracker module delegate methods. **Declared In:** Headers/SNRTracker.h **Related To:** [TrackerDelegate](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#tracker-delegate) **Class:** [Tracker](/developers/mobile-sdk/class-reference/ios/modules#tracker) **Declaration:**
```Swift static func setDelegate(_ delegate: TrackerDelegate) ```
```Objective-C + (void)setDelegate:(SNRTrackerDelegate *)delegate ```
**Discussion:** Learn more about the methods and the purpose of this listener [here](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#tracker-delegate). ## Get customer's events --- This method retrieves events for an authenticated customer. This method requires customer authentication. **Declared In:** Headers/SNRClient.h **Related To:** [ClientEventsApiQuery](/developers/mobile-sdk/class-reference/ios/client#clienteventsapiquery) **Class:** [Client](/developers/mobile-sdk/class-reference/ios/modules#client) **Declaration:**
```Swift static func getEvents(apiQuery: ClientEventsApiQuery, success: (([ClientEventData]) -> Void), failure: ((ApiError) -> Void)) -> Void ```
```Objective-C + (void)getEventsWithApiQuery:(nonnull SNRClientEventsApiQuery *)apiQuery success:(nonnull void (^)(NSArray *events))success failure:(nonnull void (^)(NSError *error))failure ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **apiQuery** | [ClientEventsApiQuery](/developers/mobile-sdk/class-reference/ios/client#clienteventsapiquery) | yes | - | Object responsible for storing all query parameters | | **success** | (([ClientEventData]) -> Void) | yes | - | Closure/Block to be executed when the operation is completed successfully | | **failure** | (([ApiError](/developers/mobile-sdk/class-reference/ios/miscellaneous#snrapierror)) -> Void) | yes | - | Closure/Block to be executed when the operation is completed with an error | **Return Value:** No value is returned. ## Set custom identifier for events --- This method sets a custom identifier in the parameters of every event. You can pass a custom identifier to match your customers in our database. **Declared In:** Headers/SNRTracker.h **Class:** [Tracker](/developers/mobile-sdk/class-reference/ios/modules#tracker) **Declaration:**
```Swift static func setCustomIdentifier(customIdentifier: String?) -> Void ```
```Objective-C + (void)setCustomIdentifier:(nullable NSString *)customIdentifier; ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **customIdentifier** | String | no | - | Customer's custom identifier | **Return Value:** No value is returned. ## Set custom email for events --- This method sets a custom email in the parameters of every event. You can pass a custom email to match your customers in our database. **Declared In:** Headers/SNRTracker.h **Class:** [Tracker](/developers/mobile-sdk/class-reference/ios/modules#tracker) **Declaration:**
```Swift static func setCustomEmail(customEmail: String?) -> Void ```
```Objective-C + (void)setCustomEmail:(nullable NSString *)customEmail; ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **customEmail** | String | no | - | Customer's custom email | **Return Value:** No value is returned. ## Send event --- This method sends an event.
DO NOT send `transaction.charge` events as custom events.
Transactions must be tracked with these endpoints: - [`/v4/transactions`](https://hub.synerise.com/api-reference/data-management#operation/CreateATransaction) (single transaction) - [`/v4/transactions/batch`](https://hub.synerise.com/api-reference/data-management#operation/BatchAddOrUpdateTransactions) (multiple transactions)
- The tracker caches and enqueues all your events locally, so they all will be sent eventually. - The API key must have the `API_BATCH_EVENTS_CREATE` permission from the **Events** group.
**Declared In:** Headers/SNRTracker.h **Related To:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Class:** [Tracker](/developers/mobile-sdk/class-reference/ios/modules#tracker) **Declaration:**
```Swift static func send(_: Event) -> Void ```
```Objective-C + (void)send:(SNREvent *)event ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **event** | [Event](/developers/mobile-sdk/class-reference/ios/events#event) | yes | - | [Event](/developers/mobile-sdk/class-reference/ios/events#event) object | **Return Value:** No value is returned. **Example:** You may use standard objects in SDK, for example `ProductAddedToCartEvent` that represents a 'customer added a product to cart' event:
```Swift let event: ProductAddedToCartEvent = ProductAddedToCartEvent(label: "Product added!", sku: "12345", finalPrice: UnitPrice(amount: 100.0), quantity: 1) event.setCategory("Smartphones") event.setName("iPhone") event.setProducer("Apple") Tracker.send(event) ```
```Objective-C SNRProductAddedToCartEvent *event = [[SNRProductAddedToCartEvent alloc] initWithLabel:@"Product added!" sku:@"12345" finalPrice:[[SNRUnitPrice alloc] initWithAmount:100.0f] quantity:1]; [event setCategory:@"Smartphones"]; [event setName:@"iPhone"]; [event setProducer:@"Apple"]; [SNRTracker send:event]; ```
You can also pass additional parameters along with `ProductAddedToCartEvent` and other events, like in the example below:
```Swift let params: TrackerParams = TrackerParams.make { (builder) in builder.setString("12345", forKey: "snr_sku") builder.setInt(1, forKey: "snr_quantity") builder.setDouble(100.0, forKey: "snr_finalPrice") } let event: ProductAddedToCartEvent = ProductAddedToCartEvent(label: "Product added!", sku: "12345", finalPrice: UnitPrice(amount: 100.0), quantity: 1, params: params) event.setCategory("Smartphones") event.setName("iPhone") event.setProducer("Apple") Tracker.send(event) ```
```Objective-C SNRTrackerParams *params = [SNRTrackerParams makeWithBuilder:^(SNRTrackerParamsBuilder *builder) { [builder setString:@"12345" forKey:@"snr_sku"]; [builder setInt:1 forKey:@"snr_quantity"]; [builder setDouble:100.0f forKey:@"snr_finalPrice"]; }]; SNRProductAddedToCartEvent *event = [[SNRProductAddedToCartEvent alloc] initWithLabel:@"Product added!" sku:@"12345" finalPrice:[[SNRUnitPrice alloc] initWithAmount:100.0f] quantity:1 andParams:params]; [event setCategory:@"Smartphones"]; [event setName:@"iPhone"]; [event setProducer:@"Apple"]; [SNRTracker send:event]; ```
If you want to track a fully customizable event, you should use `CustomEvent`:
```Swift let params: TrackerParams = TrackerParams.make { (builder) in builder.setString("12345", forKey:"key_string"); builder.setInt(1, forKey:"key_integer"); builder.setDouble(1.0, forKey:"key_double"); builder.setFloat(1.0, forKey:"key_float"); builder.setBool(true, forKey:"key_bool"); builder.setObject(["key": "value"], forKey:"key_object"); } let event: CustomEvent = CustomEvent(label: "custom event", action: "custom event action", params: params) Tracker.send(event) ```
```Objective-C SNRTrackerParams *params = [SNRTrackerParams makeWithBuilder:^(SNRTrackerParamsBuilder *builder) { [builder setString:@"string" forKey:@"key_string"]; [builder setInt:1 forKey:@"key_integer"]; [builder setDouble:1.0f forKey:@"key_double"]; [builder setFloat:1.0f forKey:@"key_float"]; [builder setBool:YES forKey:@"key_bool"]; [builder setObject:@{ @"key" : @"value" } forKey:@"key_object"]; }]; SNRCustomEvent *event = [[SNRCustomEvent alloc] initWithLabel:"custom event" action:@"custom event action" andParams:params]; [SNRTracker send:event]; ```
## Flush events from Tracker --- This method forces sending the events from the queue to the server.
The API key must have the `API_BATCH_EVENTS_CREATE` permission from the **Events** group.
**Declared In:** Headers/SNRTracker.h **Related To:** [Event](/developers/mobile-sdk/class-reference/ios/events#event) [TrackerParams](/developers/mobile-sdk/class-reference/ios/events#trackerparams) [TrackerParamsBuilder](/developers/mobile-sdk/class-reference/ios/events#trackerparamsbuilder) **Class:** [Tracker](/developers/mobile-sdk/class-reference/ios/modules#tracker) **Declaration:**
```Swift static func flushEvents(completionHandler: (() -> Void)?) -> Void ```
```Objective-C + (void)flushEventsWithCompletionHandler:(nullable void (^)(void))completion ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **completionHandler** | (() -> Void) | no | - | Block/Closure to be executed when the tracker has finished flushing events to Synerise backend, no matter the result | **Return Value:** No value is returned. # Event tracking --- ## Set custom identifier for events --- This method sets a custom identifier in the parameters of every event. You can pass a custom identifier to match your customers in our database. **Declared In:** lib/main/modules/TrackerModule.js **Class:** [TrackerModule](/developers/mobile-sdk/class-reference/react-native/modules#tracker) **Declaration:**
public setCustomIdentifier(identifier: string)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **identifier** | string | yes | - | Customer's custom identifier | **Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Tracker.setCustomIdentifier("CUSTOM_IDENTIFIER"); ```
## Set custom email for events --- This method sets a custom email in the parameters of every event. You can pass a custom email to match your customers in our database. **Declared In:** lib/main/modules/TrackerModule.js **Class:** [TrackerModule](/developers/mobile-sdk/class-reference/react-native/modules#tracker) **Declaration:**
public setCustomEmail(email: string)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | string | yes | - | Customer's custom email | **Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Tracker.setCustomEmail("CUSTOM_EMAIL"); ```
## Send event --- This method sends an event.
DO NOT send `transaction.charge` events as custom events.
Transactions must be tracked with these endpoints: - [`/v4/transactions`](https://hub.synerise.com/api-reference/data-management#operation/CreateATransaction) (single transaction) - [`/v4/transactions/batch`](https://hub.synerise.com/api-reference/data-management#operation/BatchAddOrUpdateTransactions) (multiple transactions)
- The tracker caches and enqueues all your events locally, so they all will be sent eventually. - The API key must have the `API_BATCH_EVENTS_CREATE` permission from the **Events** group.
**Declared In:** lib/main/modules/TrackerModule.js **Related To:** [Event](/developers/mobile-sdk/class-reference/react-native/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/react-native/events#customevent) **Class:** [TrackerModule](/developers/mobile-sdk/class-reference/react-native/modules#tracker) **Declaration:**
public send(event: Event)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **event** | **Event** | yes | - | Event object | **Return Value:** No value is returned. **Example:**
```JavaScript let parameters = { "name": "John", "surname": "Rise", "company": "Synerise", "age": 25, "lastOrder": 380.50 }; let event = new CustomEvent("label", "my.action", parameters); Synerise.Tracker.send(event); ```
## Flush events from Tracker --- This method forces sending the events from the queue to the server.
The API key must have the `API_BATCH_EVENTS_CREATE` permission from the **Events** group.
**Declared In:** lib/main/modules/TrackerModule.js **Class:** [TrackerModule](/developers/mobile-sdk/class-reference/react-native/modules#tracker) **Declaration:**
public flushEvents(onSuccess: () => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | **Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Tracker.flushEvents(function() { // success }); ```
# Event tracking --- ## Set custom identifier for events --- This method sets a custom identifier in the parameters of every event. You can pass a custom identifier to match your customers in our database. **Declared In:** lib/modules/tracker/tracker_impl.dart **Class:** [TrackerImpl](/developers/mobile-sdk/class-reference/flutter/modules#tracker) **Declaration:**
Future<void> setCustomIdentifier(String customIdentifier)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **identifier** | String | yes | - | Customer’s custom identifier | **Return Value:** No value is returned. **Example:**
```Dart await Synerise.tracker.setCustomIdentifier("CUSTOM_IDENTIFIER"); ```
## Set custom email for events --- This method sets a custom email in the parameters of every event. You can pass a custom email to match your customers in our database. **Declared In:** lib/modules/tracker/tracker_impl.dart **Class:** [TrackerImpl](/developers/mobile-sdk/class-reference/flutter/modules#tracker) **Declaration:**
Future<void> setCustomEmail(String customEmail)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **email** | String | yes | - | Customer’s custom email | **Return Value:** No value is returned. **Example:**
```Dart await Synerise.tracker.setCustomEmail("CUSTOM_EMAIL"); ```
## Send event --- This method sends an event.
DO NOT send `transaction.charge` events as custom events.
Transactions must be tracked with these endpoints: - [`/v4/transactions`](https://hub.synerise.com/api-reference/data-management#operation/CreateATransaction) (single transaction) - [`/v4/transactions/batch`](https://hub.synerise.com/api-reference/data-management#operation/BatchAddOrUpdateTransactions) (multiple transactions)
- The tracker caches and enqueues all your events locally, so they all will be sent eventually. - The API key must have the `API_BATCH_EVENTS_CREATE` permission from the **Events** group.
**Declared In:** lib/modules/tracker/tracker_impl.dart **Related To:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/flutter/events#customevent) **Class:** [TrackerImpl](/developers/mobile-sdk/class-reference/flutter/modules#tracker) **Declaration:**
Future<void> send(Event event)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **event** | [Event](/developers/mobile-sdk/class-reference/flutter/events#event) | yes | - | Event object | **Return Value:** No value is returned. **Example:**
```Dart final paramMap = {"firstKeyCustomParam": "TEST"}; CustomEvent event = CustomEvent("label", "flutter", paramMap); await Synerise.tracker.send(event); ```
## Flush events from Tracker --- This method forces sending the events from the queue to the server.
The API key must have the `API_BATCH_EVENTS_CREATE` permission from the **Events** group.
**Declared In:** lib/modules/tracker/tracker_impl.dart **Related To:** [Event](/developers/mobile-sdk/class-reference/flutter/events#event) [CustomEvent](/developers/mobile-sdk/class-reference/flutter/events#customevent) **Class:** [TrackerImpl](/developers/mobile-sdk/class-reference/flutter/modules#tracker) **Declaration:**
Future<void> flush()
**Return Value:** No value is returned. **Example:**
```Dart await Synerise.tracker.flush(); ```
# Promotions and Vouchers ## Promotions --- ### PromotionResponse **Declared In:** Headers/SNRPromotionResponse.h **Related To:** [PromotionResponseMetadata](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotionresponsemetadata) [Promotion](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotion) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class PromotionResponse: BaseModel ```
```Objective-C @interface SNRPromotionResponse : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **metadata** | [PromotionResponseMetadata](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotionresponsemetadata) | yes | Metadata of the promotion response | | **items** | [[Promotion]](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers/#promotion) | no | List of promotion items |
All properties are read-only.
--- --- ### PromotionResponseMetadata **Declared In:** Headers/SNRPromotionResponseMetadata.h **Related To:** [PromotionResponse](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotionresponse) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class PromotionResponseMetadata: BaseModel ```
```Objective-C @interface SNRPromotionResponseMetadata : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **totalCount** | Int | no | Total count of promotions | | **totalPages** | Int | no | Total count of pages | | **page** | Int | no | Current page | | **limit** | Int | no | Limit of promotions per page | | **code** | Int | no | HTTP code of the response |
All properties are read-only.
--- --- ### Promotion **Declared In:** Headers/SNRPromotion.h **Related To:** [PromotionResponse](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotionresponse) [PromotionStatus](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotionstatus) [PromotionType](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotiontype) [PromotionDetails](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotiondetails) [PromotionItemScope](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotionitemscope) [PromotionDiscountType](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotiondiscounttype) [PromotionDiscountMode](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotiondiscountmode) [PromotionDiscountModeDetails](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotiondiscountmodedetails) [PromotionImage](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotionimage) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class Promotion: BaseModel ```
```Objective-C @interface SNRPromotion : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **uuid** | String | no | Promotion's UUID | | **code** | String | no | Promotion's code | | **status** | [PromotionStatus](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotionstatus) | no | Promotion's status | | **type** | [PromotionType](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotiontype) | no | Promotion's type | | **details** | [PromotionDetails](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotiondetails) | yes | Promotion's details | | **redeemLimitPerClient** | NSNumber | yes | Redemption limit per customer | | **redeemQuantityPerActivation** | NSNumber | yes | Redemption quantity per activation | | **currentRedeemedQuantity** | NSNumber | no | Current redemption quantity | | **currentRedeemLimit** | NSNumber | no | Current redemption limit | | **activationCounter** | NSNumber | no | Promotion's activation counter | | **possibleRedeems** | NSNumber | no | Maximum number of promotion redemptions | | **requireRedeemedPoints** | NSNumber | yes | Required redeemed points | | **discountType** | [PromotionDiscountType](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotiondiscounttype) | no | Discount type | | **discountValue** | NSNumber | no | Discount value | | **discountMode** | [PromotionDiscountMode](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotiondiscountmode) | no | Discount mode | | **discountModeDetails** | [PromotionDiscountModeDetails](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotiondiscountmodedetails) | yes | Discount mode details | | **priority** | NSNumber | no | Promotion's priority | | **price** | NSNumber | no | Item price | | **itemScope** | [PromotionItemScope](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotionitemscope) | no | Promotion's item scope | | **minBasketValue** | NSNumber | yes | Minimum basket value | | **maxBasketValue** | NSNumber | yes | Maximum basket value | | **name** | String | no | Promotion's name | | **headline** | String | yes | Promotion's headline | | **descriptionText** | String | yes | Promotion's description | | **images** | [[PromotionImage](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotionimage)] | yes | List of promotion images | | **startAt** | Date | yes | Start time of a promotion | | **expireAt** | Date | yes | Expiration time of the promotion | | **lastingAt** | Date | yes | Date when the promotion expires for the current profile | | **lastingTime** | NSNumber | yes | Duration of the promotion in seconds | | **displayFrom** | String | yes | Date as a string when the promotion starts being displayed | | **displayTo** | String | yes | Date as a string when the promotions ends being displayed | | **catalogIndexItems** | [String] | yes | List of item indexes | | **params** | [AnyHashable: Any] | yes | Promotion's custom parameters | | **tags** | [AnyObject] | yes | Promotion's custom tags |
All properties are read-only.
--- --- ### PromotionStatus **Declared In:** Headers/SNRPromotionStatus.h **Related To:** [Promotion](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotion) **Declaration:**
```Swift enum PromotionStatus: Int { none, active, assigned, redeemed } ```
```Objective-C typedef NS_ENUM(NSUInteger, SNRPromotionStatus) { SNRPromotionStatusNone = 0, SNRPromotionStatusActive, SNRPromotionStatusAssigned, SNRPromotionStatusRedeemed } ```
**Functions:** Converts from **PromotionStatus** to **String**.
```Swift func SNR_PromotionStatusToString(_: PromotionStatus) -> String ```
```Objective-C NSString * SNR_PromotionStatusToString(SNRPromotionStatus type) ```
--- Converts from **String** to **PromotionStatus**.
```Swift func SNR_StringToPromotionStatus(_: String) -> PromotionStatus ```
```Objective-C SNRPromotionStatus SNR_StringToPromotionStatus(NSString * _Nullable string) ```
**Note:** The following string constants can be used in [PromotionsApiQuery](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotionsapiquery) object: - SNR_PROMOTION_STATUS_NONE - SNR_PROMOTION_STATUS_ACTIVE - SNR_PROMOTION_STATUS_ASSIGNED - SNR_PROMOTION_STATUS_REDEEMED --- --- ### PromotionType **Declared In:** Headers/SNRPromotionType.h **Related To:** [Promotion](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotion) **Declaration:**
```Swift enum PromotionType: Int { unknown, membersOnly, custom, general, handbill } ```
```Objective-C typedef NS_ENUM(NSUInteger, SNRPromotionType) { SNRPromotionTypeUnknown = 0, SNRPromotionTypeMembersOnly, SNRPromotionTypeCustom, SNRPromotionTypeGeneral, SNRPromotionTypeHandbill } ```
**Functions:** Converts from **PromotionType** to **String**.
```Swift func SNR_PromotionTypeToString(_: PromotionType) -> String ```
```Objective-C NSString * SNR_PromotionTypeToString(SNRPromotionType type) ```
--- Converts from **String** to **PromotionType**.
```Swift func SNR_StringToPromotionType(_: String) -> PromotionType ```
```Objective-C SNRPromotionType SNR_StringToPromotionType(NSString * _Nullable string) ```
**Note:** The following string constants can be used in [PromotionsApiQuery](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotionsapiquery) object: - SNR_PROMOTION_TYPE_UNKNOWN - SNR_PROMOTION_TYPE_MEMBERS_ONLY - SNR_PROMOTION_TYPE_CUSTOM - SNR_PROMOTION_TYPE_GENERAL --- --- ### PromotionItemScope **Declared In:** Headers/SNRPromotionItemScope.h **Related To:** [Promotion](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotion) **Declaration:**
```Swift enum PromotionItemScope: Int { lineItem, basket } ```
```Objective-C typedef NS_ENUM(NSUInteger, SNRPromotionItemScope) { SNRPromotionItemScopeLineItem = 0, SNRPromotionItemScopeBasket } ```
**Functions:** Converts from **PromotionItemScope** to **String**.
```Swift func SNR_PromotionItemScopeToString(_: PromotionItemScope) -> String ```
```Objective-C NSString * SNR_PromotionItemScopeToString(SNRPromotionItemScope scope) ```
--- Converts from **String** to **PromotionItemScope**.
```Swift func SNR_StringToPromotionItemScope(_: String) -> PromotionItemScope ```
```Objective-C SNRPromotionItemScope SNR_StringToPromotionItemScope(NSString * _Nullable string) ```
--- --- ### PromotionDetails **Declared In:** Headers/SNRPromotionDetails.h **Related To:** [Promotion](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotion) [PromotionDiscountTypeDetails](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotiondiscounttypedetails) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class PromotionDetails: BaseModel ```
```Objective-C @interface SNRPromotionDetails : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **discountType** | [PromotionDiscountTypeDetails](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotiondiscounttypedetails) | no | Discount details |
All properties are read-only.
--- --- ### PromotionDiscountTypeDetails **Declared In:** Headers/SNRPromotionDiscountTypeDetails.h **Related To:** [PromotionDetails](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotiondetails) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class PromotionDiscountTypeDetails: BaseModel ```
```Objective-C @interface SNRPromotionDiscountTypeDetails : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **name** | String | no | Discount's name | | **outerScope** | Bool | no | When `true`, the items required to trigger the promotion are different than the items included in that promotion. | | **requiredItemsCount** | Int | no | Number of items required to qualify for the discount | | **discountedItemsCount** | Int | no | Number of discounted items |
All properties are read-only.
--- --- ### PromotionDiscountMode **Declared In:** Headers/SNRPromotionDiscountType.h **Related To:** [Promotion](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotion) **Declaration:**
```Swift enum PromotionDiscountMode: Int { static, step } ```
```Objective-C typedef NS_ENUM(NSUInteger, SNRPromotionDiscountMode) { SNRPromotionDiscountModeStatic = 0, SNRPromotionDiscountModeStep } ```
**Functions:** Converts from **PromotionDiscountMode** to **String**.
```Swift func SNR_PromotionDiscountModeToString(_: PromotionDiscountMode) -> String ```
```Objective-C NSString * SNR_PromotionDiscountModeToString(SNRPromotionDiscountMode mode) ```
--- Converts from **String** to **PromotionDiscountMode**.
```Swift func SNR_StringToPromotionDiscountMode(_: String) -> PromotionDiscountMode ```
```Objective-C SNRPromotionDiscountMode SNR_StringToPromotionDiscountMode(NSString * _Nullable string) ```
--- --- ### PromotionDiscountModeDetails **Declared In:** Headers/SNRPromotionDiscountModeDetails.h **Related To:** [Promotion](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotion) [PromotionDiscountStep](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotiondiscountstep) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class PromotionDiscountModeDetails: BaseModel ```
```Objective-C @interface SNRPromotionDiscountModeDetails : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **discountSteps** | [[SNRPromotionDiscountStep]](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers/#promotion) | no | List of discount steps | | **discountUsageTrigger** | [PromotionDiscountUsageTrigger](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotiondiscountusagetrigger) | no | Usage trigger for the discount |
All properties are read-only.
--- --- ### PromotionDiscountStep **Declared In:** Headers/SNRPromotionDiscountStep.h **Related To:** [PromotionDiscountModeDetails](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotiondiscountmodedetails) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class PromotionDiscountStep: BaseModel ```
```Objective-C @interface SNRPromotionDiscountStep : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **discountValue** | NSNumber | no | Value of the discount | | **usageThreshold** | NSNumber | no | Usage threshold |
All properties are read-only.
--- --- ### PromotionDiscountUsageTrigger **Declared In:** Headers/SNRPromotionDiscountUsageTrigger.h **Related To:** [PromotionDiscountModeDetails](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotiondiscountmodedetails) **Declaration:**
```Swift enum PromotionDiscountUsageTrigger: Int { transaction, redeem } ```
```Objective-C typedef NS_ENUM(NSUInteger, SNRPromotionDiscountUsageTrigger) { SNRPromotionDiscountUsageTriggerTransaction = 0, SNRPromotionDiscountUsageTriggerRedeem } ```
**Functions:** Converts from **PromotionDiscountUsageTrigger** to **String**.
```Swift func SNR_PromotionDiscountUsageTriggerToString(_: PromotionDiscountUsageTrigger) -> String ```
```Objective-C NSString * SNR_PromotionDiscountUsageTriggerToString(SNRPromotionDiscountUsageTrigger trigger) ```
--- Converts from **String** to **PromotionDiscountUsageTrigger**.
```Swift func SNR_StringToPromotionDiscountUsageTrigger(_: String) -> PromotionDiscountUsageTrigger ```
```Objective-C SNRPromotionDiscountUsageTrigger SNR_StringToPromotionDiscountUsageTrigger(NSString * _Nullable string) ```
--- --- ### PromotionImage **Declared In:** Headers/SNRPromotion.h **Related To:** [Promotion](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotion) [PromotionImageType](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotionimagetype) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class PromotionImage: BaseModel ```
```Objective-C @interface SNRPromotionImage : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **url** | String | no | Image's URL | | **type** | [PromotionImageType](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotionimagetype) | no | Image type |
All properties are read-only.
--- --- ### PromotionImageType **Declared In:** Headers/SNRPromotionImageType.h **Related To:** [Promotion](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotion) **Declaration:**
```Swift enum PromotionImageType: Int { image, thumbnail } ```
```Objective-C typedef NS_ENUM(NSUInteger, SNRPromotionImageType) { SNRPromotionImageTypeImage = 0, SNRPromotionImageTypeThumbnail } ```
**Functions:** Converts from **PromotionImageType** to **String**.
```Swift func SNR_PromotionImageTypeToString(_: PromotionImageType) -> String ```
```Objective-C NSString * SNR_PromotionImageTypeToString(SNRPromotionImageType type) ```
--- Converts from **String** to **PromotionImageType**.
```Swift func SNR_StringToPromotionImageType(_: String) -> PromotionImageType ```
```Objective-C SNRPromotionImageType SNR_StringToPromotionImageType(NSString * _Nullable string) ```
--- --- ### PromotionDiscountType **Declared In:** Headers/SNRPromotionDiscountType.h **Related To:** [Promotion](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotion) **Declaration:**
```Swift enum PromotionDiscountType: Int { none, percent, amount, 2For1, points, multibuy, exactPrice } ```
```Objective-C typedef NS_ENUM(NSUInteger, SNRPromotionDiscountType) { SNRPromotionDiscountTypeNone = 0, SNRPromotionDiscountTypePercent, SNRPromotionDiscountTypeAmount, SNRPromotionDiscountType2For1, SNRPromotionDiscountTypePoints, SNRPromotionDiscountTypeMultibuy, SNRPromotionDiscountTypeExactPrice } ```
**Functions:** Converts from **PromotionDiscountType** to **String**.
```Swift func SNR_PromotionDiscountTypeToString(_: PromotionDiscountType) -> String ```
```Objective-C NSString * SNR_PromotionDiscountTypeToString(SNRPromotionDiscountType type) ```
--- Converts from **String** to **PromotionDiscountType**.
```Swift func SNR_StringToPromotionDiscountType(_: String) -> PromotionDiscountType ```
```Objective-C SNRPromotionDiscountType SNR_StringToPromotionDiscountType(NSString * _Nullable string) ```
--- --- ### PromotionIdentifier **Declared In:** Headers/SNRPromotionIdentifier.h **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class PromotionIdentifier: BaseModel ```
```Objective-C @interface SNRPromotionIdentifier : SNRBaseModel ```
**Initializers:**
```Swift init(uuid: String) ```
```Objective-C - (instancetype)initWithUUID:(NSString *)UUID ```
---
```Swift init(code: String) ```
```Objective-C - (instancetype)initWithCode:(NSString *)code ```
--- --- ### PromotionsApiQuery Object for setting parameters to facilitate fetching promotions from the API. **Declared In:** Headers/SNRPromotionsApiQuery.h **Related To:** [PromotionResponse](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotionresponse) [Promotion](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#promotion) [ApiQuerySortingOrderString](/developers/mobile-sdk/class-reference/ios/miscellaneous#apiquerysortingorder) **Inherits From:** [NSObject](https://developer.apple.com/documentation/objectivec/nsobject) **Declaration:**
```Swift class PromotionsApiQuery: NSObject ```
```Objective-C @interface SNRPromotionsApiQuery : NSObject ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **statuses** | [[SNRPromotionStatusString]](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers/#promotionstatus) | no | [] | List of promotion statuses for query | | **types** | [[SNRPromotionTypeString]](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers/#promotiontype) | no | [] | List of promotion types for query | | **sorting** | [[SNRPromotionSortingKey: SNRApiQuerySortingOrderString]] | yes | [] | Specifies sorting rules for items in the response | | **limit** | Int | no | 100 | Limit of items per page in the response | | **page** | Int | no | 1 | Page number | | **includeMeta** | Bool | no | false | Specifies if meta data should be included in the response |
- Check the list of promotion sorting keys available in [Loyalty - Promotion sorting options](/developers/mobile-sdk/loyalty#promotion-sorting-options) section. - See [ApiQuerySortingOrderString](/developers/mobile-sdk/class-reference/ios/miscellaneous#apiquerysortingorder) to check ordering options.
**Initializers:**
```Swift init() ```
```Objective-C - (instancetype)init ```
--- --- ## Vouchers --- ### AssignVoucherResponse **Declared In:** Headers/SNRAssignVoucherResponse.h **Related To:** [AssignVoucherData](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#assignvoucherdata) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class AssignVoucherResponse: BaseModel ```
```Objective-C @interface SNRAssignVoucherResponse : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **message** | String | no | Message from the Voucher assignment response | | **assignVoucherData** | [AssignVoucherData](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#assignvoucherdata) | yes | List of vouchers in a pool |
All properties are read-only.
--- --- ### VoucherCodesResponse **Declared In:** Headers/SNRVoucherCodesResponse.h **Related To:** [SNRVoucherCodesData](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#vouchercodesdata) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class VoucherCodesResponse: BaseModel ```
```Objective-C @interface SNRVoucherCodesResponse : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **items** | [[VoucherCodesData]](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers/#vouchercodesdata) | no | List of voucher items |
All properties are read-only.
--- --- ### AssignVoucherData **Declared In:** Headers/SNRAssignVoucherData.h **Related To:** [AssignVoucherResponse](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#assignvoucherresponse) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class AssignVoucherData: BaseModel ```
```Objective-C @interface SNRAssignVoucherData : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **code** | String | no | Voucher's code | | **expireIn** | Date | yes | Voucher's expiration date | | **redeemAt** | Date | yes | Voucher's redemption date | | **assignedAt** | Date | yes | Voucher's assignment date | | **createdAt** | Date | no | Voucher's creation date | | **updatedAt** | Date | no | Voucher's update date |
All properties are read-only.
--- --- ### VoucherCodesData **Declared In:** Headers/SNRVoucherCodesData.h **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class VoucherCodesData: BaseModel ```
```Objective-C @interface SNRVoucherCodesData : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **code** | String | no | Voucher's code | | **status** | [VoucherStatus](/developers/mobile-sdk/class-reference/ios/promotions-and-vouchers#voucherstatus) | no | Voucher's status | | **clientId** | String | no | ID of the customer to whom the voucher is assigned | | **clientUuid** | String | no | UUID of the customer to whom the voucher is assigned | | **poolUuid** | String | no | Voucher's pool ID | | **expireIn** | Date | no | Voucher's expiration date | | **redeemAt** | Date | no | Voucher's redemption date | | **assignedAt** | Date | no | Voucher's assignment date | | **createdAt** | Date | no | Voucher's creation date | | **updatedAt** | Date | no | Voucher's update date|
All properties are read-only.
--- --- ### VoucherStatus **Declared In:** Headers/SNRVoucherStatus.h **Declaration:**
```Swift enum VoucherStatus: Int { unassigned, assigned, redeemed, canceled } ```
```Objective-C typedef NS_ENUM(NSUInteger, SNRVoucherStatus) { SNRVoucherStatusUnassigned = 0, SNRVoucherStatusAssigned, SNRVoucherStatusRedeemed, SNRVoucherStatusCanceled } ```
**Functions:** Converts from **VoucherStatus** to **String**.
```Swift func SNR_VoucherStatusToString(_: VoucherStatus) -> String ```
```Objective-C NSString * SNR_VoucherStatusToString(SNRVoucherStatus type) ```
--- Converts from **String** to **VoucherStatus**.
```Swift func SNR_StringToVoucherStatus(_: String) -> VoucherStatus ```
```Objective-C SNRVoucherStatus SNR_StringToVoucherStatus(NSString * _Nullable string) ```
# Promotions and Vouchers ## Promotions --- ### PromotionResponse Class model for a promotion response. **Declared In:** `com.synerise.sdk.promotions.model.promotion.PromotionResponse` **Declaration:**
```Java public class PromotionResponse ```
```Kotlin class PromotionResponse ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **promotionMetadata** | [PromotionMetadata](/developers/mobile-sdk/class-reference/android/promotions-and-vouchers#promotionmetadata) | no | - | Metadata | | **promotions** | List<[Promotion](/developers/mobile-sdk/class-reference/android/promotions-and-vouchers#promotion)> | no | - | List of promotions |
All the properties above are accessible by using getters.
**Initializers:** There are no initializers. **Methods:** This method retrieves the value of the `promotionMetadata` parameter.
public PromotionMetadata getPromotionMetadata()
--- This method retrieves a list of promotions.
public List<Promotion> getPromotions()
--- --- --- ### SinglePromotionResponse Class model for a single promotion response. **Declared In:** `com.synerise.sdk.promotions.model.promotion.SinglePromotionResponse` **Declaration:**
```Java public class SinglePromotionResponse ```
```Kotlin class SinglePromotionResponse ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **promotion** | [Promotion](/developers/mobile-sdk/class-reference/android/promotions-and-vouchers#promotion) | no | - | Promotion |
All the properties above are accessible by using getters and setters.
**Initializers:** There are no initializers. **Methods:** There are only getters and setters for the above properties. This method retrieves the value of the `promotion` parameter.
public Promotion getPromotion()
--- This method defines the value of the `promotion` parameter.
public void setPromotion(Promotion data)
--- --- --- ### PromotionMetadata Class model for a promotion metadata. **Declared In:** `com.synerise.sdk.promotions.model.promotion.PromotionMetadata` **Declaration:**
```Java public class PromotionMetadata implements Serializable ```
```Kotlin class PromotionMetadata : Serializable ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **totalCount** | int | no | - | Total count of promotions | | **totalPages** | int | no | - | Total count of pages | | **page** | int | no | - | Page | | **limit** | int | no | - | Limit of promotions per page | | **code** | int | no | - | Code |
All the properties above are accessible by using getters.
**Initializers:** There are no initializers. **Methods:** This method retrieves the value of the `totalCount` parameter.
public int getTotalCount()
--- This method retrieves the value of the `totalPages` parameter.
public int getTotalPages()
--- This method retrieves the value of the `page` parameter.
public int getPage()
--- This method retrieves the value of the `limit` parameter.
public int getLimit()
--- This method retrieves the value of the `code` parameter.
public int getCode()
--- --- --- ### Promotion Class model for a promotion. **Declared In:** `com.synerise.sdk.promotions.model.promotion.Promotion` **Declaration:**
```Java public class Promotion extends BaseModel implements Serializable ```
```Kotlin class Promotion : BaseModel, Serializable ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **uuid** | String | no | - | Promotion UUID | | **code** | String | no | - | Promotion code | | **status** | String | no | - | Promotion status | | **type** | String | no | - | Promotion type | | **redeemLimitPerClient** | int | no | - | Redemption limit per client | | **redeemQuantityPerActivation** | int | no | - | Redemption quantity per activation | | **currentRedeemedQuantity** | int | no | - | Current redeemed quantity | | **currentRedeemLimit** | int | no | - | Current redemption limit | | **activationCounter** | int | no | - | Activation counter | | **discountType** | String | no | - | Discount type | | **discountValue** | int | no | - | Discount value | | **requireRedeemedPoints** | int | no | - | Required redeemed points | | **name** | String | no | - | Promotion name | | **headline** | String | no | - | Promotion headline | | **description** | String | no | - | Promotion description | | **images** | List | no | - | List of promotion images | | **startAt** | Date | no | - | Start time of a promotion | | **expireAt** | Date | no | - | Expiration time of a promotion | | **lastingAt** | Date | no | - | How long a promotion lasts | | **params** | HashMap | no | - | Promotion custom parameters | | **catalogIndexItems** | List | no | - | List of item indexes | | **price** | long | no | - | Item price | | **priority** | int | no | - | Promotion priority |
All the properties above are accessible by using getters.
**Initializers:** There are no initializers. **Methods:** There are only getters for the above properties. --- --- --- ### PromotionStatus This enum contains values for a promotion status. **Declared In:** `com.synerise.sdk.promotions.model.promotion.PromotionStatus` **Declaration:**
```Java public enum PromotionStatus ```
```Kotlin public enum PromotionStatus ```
**Values:** | Property | Value | Description | | --- | --- | --- | | **ASSIGNED** | "ASSIGNED" | Promotion status | | **ACTIVE** | "ACTIVE" | Promotion status | | **REDEEMED** | "REDEEMED" | Promotion status | | **UNKNOWN** | "UNKNOWN" | Promotion status | **Methods:** This method retrieves a promotion status.
public static PromotionStatus getByPromotionStatus(String status)
--- --- --- ### PromotionType This enum contains values for a promotion type. **Declared In:** `com.synerise.sdk.promotions.model.promotion.PromotionType` **Declaration:**
```Java public enum PromotionType ```
```Kotlin public enum PromotionType ```
**Values:** | Property | Value | Description | | --- | --- | --- | | **GENERAL** | "GENERAL" | Promotion type | | **CUSTOM** | "CUSTOM" | Promotion type | | **MEMBERS_ONLY** | "MEMBERS_ONLY" | Promotion type | | **UNKNOWN** | "UNKNOWN" | Promotion type | **Methods:** This method retrieves a promotion type.
public static PromotionType getByPromotionType(String type)
--- --- --- ### PromotionIdentifier Class model for a promotion identifier. **Declared In:** `com.synerise.sdk.promotions.model.promotion.PromotionIdentifier` **Declaration:**
```Java public class PromotionIdentifier implements Serializable ```
```Kotlin class PromotionIdentifier : Serializable ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **key** | String | no | - | Promotion key identifier | | **value** | String | no | - | Promotion identifier value | **Initializers:** There is a constructor. **Methods:** There are no methods. --- --- ### PromotionsApiQuery Class responsible for creating a promotion query. **Declared In:** `com.synerise.sdk.promotions.model.promotion.PromotionsApiQuery` **Declaration:**
```Java public class PromotionsApiQuery ```
```Kotlin class PromotionsApiQuery ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **statuses** | List<[PromotionStatus](/developers/mobile-sdk/class-reference/android/promotions-and-vouchers#promotionstatus)> | yes | - | List of promotion states | | **types** | List<[PromotionType](/developers/mobile-sdk/class-reference/android/promotions-and-vouchers#promotiontype)> | yes | - | List of promotion types | | **sortParameters** | LinkedHashMap | yes | - | Sort parameters. If you add more than one sorting attribute, the importance of each attribute depends on its position. The first one is the most important. | | **limit** | int | no | 100 | Limit of promotions per page | | **page** | int | no | 1 | Page number | | **includeMeta** | Boolean | no | false | If true, the response includes metadata |
All the properties above are accessible by using setters.
**Initializers:** There are no initializers. **Methods:** There are only setters for above properties. --- --- ## Vouchers --- ### AssignVoucherResponse Class model of AssignVoucherResponse. **Declared In:** `com.synerise.sdk.promotions.model.AssignVoucherResponse` **Declaration:**
```Java public class AssignVoucherResponse ```
```Kotlin class AssignVoucherResponse ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **message** | String | no | - | Message | | **data** | [AssignVoucherData](/developers/mobile-sdk/class-reference/android/promotions-and-vouchers#assignvoucherdata) | no | - | Voucher data |
All the properties above are accessible by using getters.
**Initializers:** There are no initializers. **Methods:** There are only getters for the above properties. This method retrieves the value of the `message` parameter.
public String getMessage()
--- This method retrieves the value of the `data` parameter.
public AssignVoucherData getData()
--- --- --- ### VoucherCodesResponse Class model of VoucherCodesResponse. **Declared In:** `com.synerise.sdk.promotions.model.VoucherCodesResponse` **Declaration:**
```Java public class VoucherCodesResponse ```
```Kotlin class VoucherCodesResponse ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **data** | List<[VoucherCodesData](/developers/mobile-sdk/class-reference/android/promotions-and-vouchers#vouchercodesdata)> | no | - | Voucher data |
All the properties above are accessible by using getters.
**Initializers:** There are no initializers. **Methods:** There are only getters for the above properties. This method retrieves the list of values of the `data` parameter.
public List<VoucherCodesData> getData()
--- --- --- ### AssignVoucherData Class model of AssignVoucherData. **Declared In:** `com.synerise.sdk.promotions.model.AssignVoucherData` **Declaration:**
```Java public class AssignVoucherData ```
```Kotlin class AssignVoucherData ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **code** | String | no | - | Code | | **expireIn** | Date | no | - | Date of expiration | | **redeemAt** | Date | no | - | Redemption at date | | **assignedAt** | Date | no | - | Date of assigning voucher | | **createdAt** | Date | no | - | Date of creation | | **updatedAt** | Date | no | - | Date of voucher update |
All the properties above are accessible by using getters.
**Initializers:** There are no initializers. **Methods:** There are only getters for the above properties. This method retrieves the value of the `code` parameter.
public String getCode()
--- This method retrieves the value of the `ExpireIn` parameter.
public Date getExpireIn()
--- This method retrieves the value of the `RedeemAt` parameter.
public Date getRedeemAt()
--- This method retrieves the value of the `AssignedAt` parameter.
public Date getAssignedAt()
--- This method retrieves the value of the `CreatedAt` parameter.
public Date getCreatedAt()
--- This method retrieves the value of the `UpdateAt` parameter.
public Date getUpdatedAt()
--- --- --- ### VoucherCodesData Class model of VoucherCodesData. **Declared In:** `com.synerise.sdk.promotions.model.VoucherCodesData` **Declaration:**
```Java public class VoucherCodesData ```
```Kotlin class VoucherCodesData ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **code** | String | no | - | Voucher code | | **status** | String | no | - | Voucher status | | **clientUuid** | String | no | - | Profile's UUID | | **poolUuid** | String | no | - | Pool UUID | | **expireIn** | Date | no | - | Voucher expiration date | | **assignedAt** | Date | no | - | Voucher assignment date | | **createdAt** | Date | no | - | Voucher creation date | | **updatedAt** | Date | no | - | Voucher update date |
All the properties above are accessible by using getters.
**Initializers:** There are no initializers. **Methods:** There are only getters for the above properties. --- --- --- ### VoucherCodesStatus This enum contains values for a voucher code status. **Declared In:** `com.synerise.sdk.client.model.client.VoucherCodeStatus` **Declaration:**
```Java public enum VoucherCodeStatus ```
```Kotlin public enum VoucherCodeStatus ```
**Values:** | Property | Value | Description | | --- | --- | --- | | **ASSIGNED** | "ASSIGNED" | Assigned | | **UNASSIGNED** | "UNASSIGNED" | Unassigned | | **REDEEMED** | "REDEEMED" | Redeemed | | **CANCELED** | "CANCELED" | Canceled | **Methods:** This method retrieves the voucher status.
public String getStatus()
--- This method retrieves the voucher status.
public static VoucherCodeStatus getStatus(String status)
--- # Profile identification, authentication, and management # Customer session ## Refresh customer token --- This method refreshes the customer’s current token.
Returns an error if the token has expired and cannot be refreshed.
**Method name:** Client.refreshToken() **Declaration:**
```Java public static IApiCall refreshToken() ```
```Kotlin fun refreshToken():IApiCall ```
**Parameters:** No parameters required. **Return Value:** [IApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#iapicall) object to execute the request. **Example:**
```Java boolean success = Client.refreshToken(); ```
```Kotlin var success = Client.refreshToken() ```
## Retrieve customer token --- This method retrieves the customer’s current, active token.
Returns an error if the token has expired and cannot be retrieved.
**Method name:** Client.retrieveToken()
This method replaces `Client.getToken()`.
**Declaration:**
```Java public static IDataApiCall retrieveToken() ```
```Kotlin fun retrieveToken():IDataApiCall ```
**Parameters:** No parameters required. **Return Value:** [IDataApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#idataapicall)<[Token](/developers/mobile-sdk/class-reference/android/client#token)> object to execute the request. **Example:**
```Java IDataApiCall retrieveTokenCall = Client.retrieveToken(); retrieveTokenCall.execute(success -> onSuccess(), this::onFailure); ```
```Kotlin val retrieveTokenCall = Client.retrieveToken() retrieveTokenCall.execute({ success-> onSuccess() }, ({ this.onFailure() })) ```
## Get current customer UUID --- This method retrieves the customer’s current UUID. **Method name:** Client.getUuid() **Declaration:**
```Java public static String getUuid() ```
```Kotlin fun getUuid():String ```
**Parameters:** No parameters required. **Return Value:** Customer's UUID as a string. **Example:**
```Java Client.getUuid() ```
```Kotlin Client.getUuid() ```
## Get customer UUID for use in authentication --- This method retrieves the current UUID or generates a new one from a seed. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 4.15.0 | 5.15.0 | n/a | n/a |
This operation doesn't affect the customer session in the SDK.
**Method name:** Client.getUuidForAuthentication() **Declaration:**
```Java public static String getUuidForAuthentication(@NonNull String authId) ```
```Kotlin fun getUuidForAuthentication( authId: String ): String ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **authId** | String | yes | --- | Seed for UUID generation | **Return Value:** The UUID for use in authentication as a string. **Example:**
```Java Client.getUuidForAuthentication(authId) ```
```Kotlin Client.getUuidForAuthentication(authId) ```
## Regenerate customer --- This method regenerates the UUID and clears the authentication token, login session, custom email, and custom identifier. This operation works only if the customer is anonymous. This operation clears the authentication token, login (if applicable), custom email, and custom identifier. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.3.10 | 3.3.5 | 0.9.0 | 0.7.0 | **Method name:** Client.regenerateUuid() **Declaration:**
```Java public static boolean regenerateUuid() ```
```Kotlin fun regenerateUuid():Boolean ```
**Parameters:** No parameters required. **Return Value:** Returns true if the current Customer is anonymous and the operation succeeds. **Example:**
```Java boolean success = Client.regenerateUuid(); ```
```Kotlin var success = Client.regenerateUuid() ```
## Regenerate customer with identifier --- This method regenerates the UUID and clears the authentication token, login session, custom email, and custom identifier. This operation works only if the customer is anonymous. This operation clears the authentication token, login (if applicable), custom email, and custom identifier The optional `clientIdentifier` parameter is a seed for UUID generation. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.6.5 | 3.6.4 | 0.9.10 | 0.7.2 | **Method name:** Client.regenerateUuid(clientIdentifier) **Declaration:**
```Java public static boolean regenerateUuid(clientIdentifier) ```
```Kotlin fun regenerateUuid(clientIdentifier):Boolean ```
**Parameters:** | Parameter | Type | Mandatory | Description | | --- | --- | --- | --- | | **clientIdentifier** | String | no | Seed for UUID generation |
The **clientIdentifier** parameter is used for decreasing the number of UUID refreshes, so it must be unique for every customer.
**Return Value:** Returns true if the current Client is anonymous and the operation succeeds. **Example:**
```Java boolean success = Client.regenerateUuid(clientIdentifier); ```
```Kotlin var success = Client.regenerateUuid(clientIdentifier) ```
## Destroy current session --- This method destroys the session completely. This method clears all session data (both client and anonymous) and removes cached data. Then, it regenerates the UUID and creates the new anonymous session. **Method name:** Client.destroySession() **Declaration:**
```Java public static void destroySession() ```
```Kotlin fun destroySession() ```
**Parameters:** No parameters required. **Return Value:** Method is void type. **Example:**
```Java Client.destroySession(); ```
```Kotlin Client.destroySession() ```
# Promotions and Vouchers ## Promotions --- ### PromotionResponse **Declared In:** lib/model/promotions/promotion_response.dart **Related To:** [Promotion](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotion) **Declaration:**
class PromotionResponse
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **totalCount** | int | no | Total count of promotions | | **totalPages** | int | no | Total count of pages | | **page** | int | no | Current page | | **limit** | int | no | Limit of promotions per page | | **code** | int | no | HTTP code of the response | | **items** | List<[Promotion](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotion)> | no | List of promotion items | --- --- ### Promotion **Declared In:** lib/model/promotions/promotion.dart **Related To:** [PromotionResponse](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotionresponse) [PromotionStatus](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotionstatus) [PromotionType](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotiontype) [PromotionDiscountType](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotiondiscounttype) **Declaration:**
class Promotion
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **uuid** | String | no | Promotion's UUID | | **code** | String | no | Promotion's code | | **status** | [PromotionStatus](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotionstatus) | yes | Promotion's status | | **type** | [PromotionType](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotiontype) | yes | Promotion's type | | **details** | [PromotionDetails](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotiondetails) | yes | Promotion's details | | **redeemLimitPerClient** | int | yes | Redemption limit per customer | | **redeemQuantityPerActivation** | int | yes | Redemption quantity per activation | | **currentRedeemedQuantity** | int | no | Current redemption quantity | | **currentRedeemLimit** | int | no | Current redemption limit | | **activationCounter** | int | no | Promotion's activation counter | | **possibleRedeems** | int | no | Maximum number of promotion redemptions | | **requireRedeemedPoints** | int | yes | Required redeemed points | | **discountType** | [PromotionDiscountType](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotiondiscounttype) | yes | Discount type | | **discountValue** | int | no | Discount value | | **discountMode** | [PromotionDiscountMode](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotiondiscountmode) | no | Discount mode | | **discountModeDetails** | [PromotionDiscountModeDetails](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotiondiscountmodedetails) | yes | Discount mode details | | **priority** | int | no | Promotion's priority | | **price** | int | no | Item price | | **itemScope** | [PromotionItemScope](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotionitemscope) | no | Promotion's item scope | | **minBasketValue** | int | yes | Minimum basket value | | **maxBasketValue** | int | yes | Maximum basket value | | **name** | String | no | Promotion's name | | **headline** | String | yes | Promotion's headline | | **descriptionText** | String | yes | Promotion's description | | **images** | List<[PromotionImage](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotiontype)> | yes | List of promotion images | | **startAt** | DateTime | yes | Start time of a promotion | | **expireAt** | DateTime | yes | Expiration time of the promotion | | **lastingAt** | DateTime | yes | Date when the promotion expires for the current profile | | **lastingTime** | int | yes | Duration of the promotion in seconds | | **displayFrom** | String | yes | DateTime as a String when the promotion starts being displayed | | **displayTo** | String | yes | DateTime as a String when the promotions ends being displayed | | **catalogIndexItems** | List<String> | yes | List of item indexes | | **params** | Map | yes | Promotion's custom parameters | | **tags** | List<Object> | yes | Promotion's custom tags | --- --- ### PromotionStatus **Declared In:** lib/enums/promotions/promotion_status.dart **Related To:** [Promotion](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotion) **Declaration:**
enum PromotionStatus {
  none('NONE'),
  active('ACTIVE'),
  assigned('ASSIGNED'),
  redeemed('REDEEMED');
}
**Functions:** Converts from **PromotionStatus** to **String**.
String promotionStatusAsString()
--- Converts from **String** to **PromotionStatus**.
PromotionStatus getPromotionStatusFromString(String string)
--- --- ### PromotionType **Declared In:** lib/enums/promotions/promotion_type.dart **Related To:** [Promotion](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotion) **Declaration:**
enum PromotionType {
  unknown('UNKNOWN'),
  membersOnly('MEMBERS_ONLY'),
  custom('CUSTOM'),
  general('GENERAL'),
  handbill('HANDBILL');
}
**Functions:** Converts from **PromotionType** to **String**.
String promotionTypeAsString() {
--- Converts from **String** to **PromotionType**.
PromotionType getPromotionTypeFromString(String string) {
--- --- ### PromotionDiscountType **Declared In:** lib/enums/promotions/promotion_discount_type.dart **Related To:** [Promotion](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotion) **Declaration:**
enum PromotionDiscountType {
  none('NONE'),
  percent('PERCENT'),
  amount('AMOUNT'),
  twoForOne('2_FOR_1'),
  points('POINTS'),
  multibuy('MULTIBUY'),
  exactPrice('EXACT_PRICE');
}
**Functions:** Converts from **String** to **PromotionDiscountType**.
PromotionDiscountType getPromotionDiscountTypeFromString(String string)
--- --- ### PromotionItemScope **Declared In:** lib/enums/promotions/promotion_item_scope.dart **Related To:** [Promotion](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotion) **Declaration:**
enum PromotionItemScope {
  lineItem('LINE_ITEM'),
  basket('BASKET');
**Functions:** Converts from **PromotionItemScope** to **String**.
```Dart String promotionItemScopeAsString() ```
--- Converts from **String** to **PromotionItemScope**.
```Dart static PromotionItemScope getPromotionItemScopeFromString(String string) ```
--- --- ### PromotionDetails **Declared In:** lib/model/promotions/promotion_details.dart **Related To:** [Promotion](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotion) [PromotionDiscountTypeDetails](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotiondiscounttypedetails) **Declaration:**
class PromotionDetails
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **discountType** | [PromotionDiscountTypeDetails](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotiondiscounttypedetails) | no | Discount details |
All properties are read-only.
--- --- ### PromotionDiscountTypeDetails **Declared In:** lib/model/promotions/promotion_discount_type_details.dart **Related To:** [PromotionDetails](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotiondetails) **Declaration:**
class PromotionDiscountTypeDetails
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **name** | String | no | Discount's name | | **outerScope** | bool | no | When `true`, the items required to trigger the promotion are different than the items included in that promotion. | | **requiredItemsCount** | int | no | Number of items required to qualify for the discount | | **discountedItemsCount** | int | no | Number of discounted items |
All properties are read-only.
--- --- ### PromotionDiscountMode **Declared In:** lib/enums/promotions/promotion_discount_mode.dart **Related To:** [Promotion](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotion) **Declaration:**
enum PromotionDiscountMode {
  staticMode('STATIC'),
  stepMode('STEP');
**Functions:** Converts from **String** to **PromotionDiscountMode**.
```Dart static PromotionDiscountMode getPromotionDiscountModeFromString(String string) ```
--- --- ### PromotionDiscountModeDetails **Declared In:** lib/model/promotions/promotion_discount_mode_details.dart **Related To:** [Promotion](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotion) [PromotionDiscountStep](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotiondiscountstep) **Declaration:**
class PromotionDiscountModeDetails
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **discountSteps** | [PromotionDiscountStep](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotion) | no | List of discount steps | | **discountUsageTrigger** | [PromotionDiscountUsageTrigger](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotiondiscountusagetrigger) | no | Usage trigger for the discount |
All properties are read-only.
--- --- ### PromotionDiscountStep **Declared In:** lib/model/promotions/promotion_discount_step.dart **Related To:** [PromotionDiscountModeDetails](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotiondiscountmodedetails) **Declaration:**
class PromotionDiscountStep
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **discountValue** | int | no | Value of the discount | | **usageThreshold** | int | no | Usage threshold |
All properties are read-only.
--- --- ### PromotionDiscountUsageTrigger **Declared In:** lib/enums/promotions/promotion_discount_usage_trigger.dart **Related To:** [PromotionDiscountModeDetails](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotiondiscountmodedetails) **Declaration:**
enum PromotionDiscountUsageTrigger {
  transaction('TRANSACTION'),
  redeem('REDEEM');
**Functions:** Converts from **PromotionDiscountUsageTrigger** to **String**.
```Dart String promotionDiscountUsageTriggerAsString() { ```
--- Converts from **String** to **PromotionDiscountUsageTrigger**.
```Dart static PromotionDiscountUsageTrigger getPromotionDiscountUsageTriggerFromString(String string) { ```
--- --- ### PromotionImage **Declared In:** lib/model/promotions/promotion_image.dart **Related To:** [Promotion](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotion) [PromotionImageType](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotionimagetype) **Declaration:**
class PromotionImage
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **url** | String | no | Image's URL | | **type** | [PromotionImageType](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotionimagetype) | no | Image type |
All properties are read-only.
--- --- ### PromotionImageType **Declared In:** lib/enums/promotions/promotion_image_type.dart **Related To:** [Promotion](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotion) **Declaration:**
enum PromotionImageType {
  image('image'),
  thumbnail('thumbnail'),
  large('large'),
  unknown('UNKNOWN');
**Functions:** Converts from **PromotionImageType** to **String**.
```Dart String promotionImageTypeAsString() { ```
--- Converts from **String** to **PromotionImageType**.
```Swift static PromotionImageType getPromotionImageTypeFromString(String string) ```
--- --- ### PromotionIdentifier **Declared In:** lib/model/promotions/promotion_identifier.dart **Declaration:**
class PromotionIdentifier {
  PromotionIdentifierKey key;
  String value;
}
**Properties:** Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **key** | String | yes | | Promotion identifier type (see [PromotionIdentifierKey enum](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotionidentifierkey))| | **value** | String | yes | | Promotion identifier value | **Initializers:**
PromotionIdentifier({required this.key, required this.value});
--- --- ### PromotionIdentifierKey **Declared In:** lib/enums/promotions/promotion_identifier_key.dart **Declaration:**
enum PromotionIdentifierKey {
  uuid('UUID'),
  code('CODE');
}
--- --- ### PromotionsApiQuery Object for setting parameters to facilitate fetching promotions from the API. **Declared In:** lib/model/promotions/promotions_api_query.dart **Related To:** [PromotionResponse](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotionresponse) [Promotion](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotion) **Declaration:**
class PromotionsApiQuery
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **statuses** | List<[PromotionStatus](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotionstatus)> | no | [] | List of promotion statuses for query | | **types** | List<[PromotionType](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#promotiontype)> | no | [] | List of promotion types for query |
- Check the list of promotion sorting keys available in [Loyalty - Promotion sorting options](/developers/mobile-sdk/loyalty#promotion-sorting-options) section. - See [ApiQuerySortingOrderString](/developers/mobile-sdk/class-reference/flutter/miscellaneous#apiquerysortingorder) to check ordering options.
**Initializers:**
PromotionsApiQuery(
      {required this.statuses,
      required this.types,
      required super.sorting,
      required super.limit,
      required super.page,
      required super.includeMeta});
--- --- ## Vouchers --- ### AssignVoucherResponse **Declared In:** lib/model/vouchers/assign_voucher_response.dart **Related To:** [AssignVoucherData](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#assignvoucherdata) **Declaration:**
class AssignVoucherResponse
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **message** | String | no | Message from the Voucher assignment response | | **assignVoucherData** | [AssignVoucherData](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#assignvoucherdata) | yes | List of vouchers in a pool | --- --- ### VoucherCodesResponse **Declared In:** lib/model/vouchers/voucher_codes_response.dart **Related To:** [VoucherCodesData](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#vouchercodesdata) **Declaration:**
class VoucherCodesResponse
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **items** | List<[VoucherCodesData](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#vouchercodesdata)> | no | List of voucher items | --- --- ### AssignVoucherData **Declared In:** lib/model/vouchers/assign_voucher_data.dart **Related To:** [AssignVoucherResponse](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#assignvoucherresponse) **Declaration:**
class AssignVoucherData
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **code** | String | no | Voucher's code | | **expireIn** | DateTime | yes | Voucher's expiration date | | **redeemAt** | DateTime | yes | Voucher's redemption date | | **assignedAt** | DateTime | yes | Voucher's assignment date | | **createdAt** | DateTime | no | Voucher's creation date | | **updatedAt** | DateTime | no | Voucher's update date | --- --- ### VoucherCodesData **Declared In:** lib/model/vouchers/voucher_codes_data.dart **Declaration:**
class VoucherCodesData
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **code** | String | no | Voucher's code | | **status** | [VoucherCodeStatus](/developers/mobile-sdk/class-reference/flutter/promotions-and-vouchers#vouchercodestatus) | no | Voucher's status | | **clientId** | String | no | ID of the customer to whom the voucher is assigned | | **clientUuid** | String | no | UUID of the customer to whom the voucher is assigned | | **poolUuid** | String | no | Voucher's pool ID | | **expireIn** | String | no | Voucher's expiration date | | **redeemAt** | DateTime | no | Voucher's redemption date | | **assignedAt** | DateTime | no | Voucher's assignment date | | **createdAt** | DateTime | no | Voucher's creation date | | **updatedAt** | DateTime | no | Voucher's update date| --- --- ### VoucherCodeStatus **Declared In:** lib/enums/vouchers/voucher_code_status.dart **Declaration:**
enum VoucherCodeStatus {
  unassigned('UNASSIGNED'),
  assigned('ASSIGNED'),
  redeemed('REDEEMED'),
  canceled('CANCELED');
}
**Functions:** Converts from **VoucherCodeStatus** to **String**.
String voucherCodeStatusAsString() {
--- Converts from **String** to **VoucherCodeStatus**.
VoucherCodeStatus getVoucherCodeStatusFromString(String string) {
# Campaigns --- ## Set Injector listener --- This method sets callbacks for an injector module. **Declared In:** lib/main/modules/InjectorModule.js **Related To:** [ClientStateChangeListener](/developers/mobile-sdk/listeners-and-delegates/react-native-listeners#injector-listener) **Class:** [InjectorModule](/developers/mobile-sdk/class-reference/react-native/modules#injector) **Declaration:**
public setListener(listener: IInjectorListener)
**Discussion:** Learn more about the methods and the purpose of this listener [here](/developers/mobile-sdk/listeners-and-delegates/react-native-listeners#injector-listener). ## Set In-App Message listener --- This method sets callbacks for in-app message campaigns. **Declared In:** lib/main/modules/InjectorModule.js **Related To:** [ClientStateChangeListener](/developers/mobile-sdk/listeners-and-delegates/react-native-listeners#injector-in-app-message-listener) **Class:** [InjectorModule](/developers/mobile-sdk/class-reference/react-native/modules#injector) **Declaration:**
public setInAppMessageListener(listener: IInjectorInAppMessageListener)
**Discussion:** Learn more about the methods and the purpose of this listener [here](/developers/mobile-sdk/listeners-and-delegates/react-native-listeners#injector-in-app-message-listener). ## Close In-App message --- Closes an in-app message and sends an `inApp.discard` event. Usage examples: - Closing a top bar or bottom bar when the user taps outside the in-app area. - Automatically dismissing messages when navigating away from a screen. - Controlling in-app visibility based on app logic for a smoother user experience. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | ----------------------------------------------- | ----------- | --------------- | -------------------- | --------------- | | Introduced in: | 5.7.0 | 6.7.0 | 1.5.0 | 2.5.0 | **Declared In:** lib/main/modules/InjectorModule.js **Class:** [InjectorModule](/developers/mobile-sdk/class-reference/react-native/modules#injector) **Declaration:**
public closeInAppMessage(campaignHash: string)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | ---------------- | ------ | --------- | ------- | ---------------------------------------- | | **campaignHash** | string | yes | - | Unique identifier of the in-app campaign | ## Set Notifications listener --- This method sets callbacks for notifications module. **Declared In:** lib/main/modules/NotificationsModule.js **Class:** [NotificationsModule](/developers/mobile-sdk/class-reference/react-native/modules#notifications) **Declaration:**
public setListener(listener: INotificationsListener)
## Register for push notifications --- This method passes the Firebase Token to Synerise for notifications.
- You should call this method every time the user changes the system or application consent for notifications. - The API key must have the `API_PERSONAL_DEVICE_CLIENT_UPDATE` permission from the **Client** group. - If the registration fails, the SDK requests a token update again by a listener/delegate method ([Android](/developers/mobile-sdk/listeners-and-delegates/android-listeners#on-register-for-push-listener), [iOS](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#synerise-delegate-register-for-push-notifications-is-needed), [React Native](/developers/mobile-sdk/listeners-and-delegates/react-native-listeners#notifications-listener), [Flutter](/developers/mobile-sdk/listeners-and-delegates/flutter-listeners#notifications-listener)).
**Declared In:** lib/main/modules/NotificationsModule.js **Class:** [NotificationsModule](/developers/mobile-sdk/class-reference/react-native/modules#notifications) **Declaration:**
public registerForNotifications(registrationToken: string, mobileAgreement: boolean | null, onSuccess: () => void, onError: (error: Error) => void)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **registrationToken** | string | yes | - | Firebase Token | | **mobileAgreement** | boolean | false | null | Agreement (consent) for mobile push campaigns | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. **Example:**
```JavaScript // If you integrate Firebase Messaging in the native part of app Synerise.Notifications.setListener({ onRegistrationToken: function(registrationToken) { Synerise.Notifications.registerForNotifications(registrationToken, true, function(){ //success }, function() { //failure }); }, onNotification: function(payload) { //... } //... //other listener's methods }); // Or if you want to use Firebase Messaging in react native Synerise.Notifications.registerForNotifications("YOUR_FIREBASE_TOKEN", true, function(){ //success }, function() { //failure }); ```
## Check if push notification is from Synerise --- This method verifies if a notification was sent by Synerise. **Declared In:** lib/main/modules/NotificationsModule.js **Class:** [NotificationsModule](/developers/mobile-sdk/class-reference/react-native/modules#notifications) **Declaration:**
public isSyneriseNotification(payload: object): boolean
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **payload** | object | yes | - | Notification's key-value data object | **Return Value:** **true** if a notification was sent by Synerise, otherwise **false**. **Example:**
```JavaScript Synerise.Notifications.setListener({ onNotification: function(payload) { if (Synerise.Notifications.isSyneriseNotification(payload)) { Synerise.Notifications.handleNotification(payload); } } //... //other listener's methods }); ```
## Check if push notification is a Simple Push Campaign --- This method verifies if a notification’s sender is Synerise and if the notification is a Simple Push campaign **Declared In:** lib/main/modules/NotificationsModule.js **Class:** [NotificationsModule](/developers/mobile-sdk/class-reference/react-native/modules#notifications) **Declaration:**
public isSyneriseSimplePush(payload: object): boolean
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **payload** | object | yes | - | Notification's key-value data object | **Return Value:** **true** if a notification is a Simple Push, otherwise **false**. **Example:**
```JavaScript Synerise.Notifications.setListener({ onNotification: function(payload) { if (Synerise.Notifications.isSyneriseSimplePush(payload)) { Synerise.Notifications.handleNotification(payload); } } //... //other listener's methods }); ```
## Check if push notification is a Silent Command --- This method verifies if a notification’s sender is Synerise and if the notification is a Silent Command. **Declared In:** lib/main/modules/NotificationsModule.js **Class:** [NotificationsModule](/developers/mobile-sdk/class-reference/react-native/modules#notifications) **Declaration:**
public isSilentCommand(payload: object): boolean
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **payload** | object | yes | - | Notification's key-value data object | **Return Value:** **true** if a notification is a Silent Command, otherwise **false**. **Example:**
```JavaScript Synerise.Notifications.setListener({ onNotification: function(payload) { if (Synerise.Notifications.isSilentCommand(payload)) { Synerise.Notifications.handleNotification(payload); } } //... //other listener's methods }); ```
## Check if push notification is a Silent SDK Command --- This method verifies if a notification's sender is Synerise and if the notification is a Silent SDK Command. **Declared In:** lib/main/modules/NotificationsModule.js **Class:** [NotificationsModule](/developers/mobile-sdk/class-reference/react-native/modules#notifications) **Declaration:**
public isSilentSDKCommand(payload: object): boolean
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **payload** | object | yes | - | Notification's key-value data object | **Return Value:** **true** if a notification is a Silent SDK Command, otherwise **false**. **Example:**
```JavaScript Synerise.Notifications.setListener({ onNotification: function(payload) { if (Synerise.Notifications.isSilentSDKCommand(payload)) { Synerise.Notifications.handleNotification(payload); } } //... //other listener's methods }); ```
## Check if push notification is encrypted --- This method verifies if a notification is encrypted. **Declared In:** lib/main/modules/NotificationsModule.js **Class:** [NotificationsModule](/developers/mobile-sdk/class-reference/react-native/modules#notifications) **Declaration:**
public isNotificationEncrypted(payload: object): boolean
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **payload** | object | yes | - | Notification's key-value data object | **Return Value:** **true** if a notification is encrypted, otherwise **false**. **Example:**
```JavaScript Synerise.Notifications.setListener({ onNotification: function(payload) { if (Synerise.Notifications.isNotificationEncrypted(payload)) { Synerise.Notifications.decryptNotification(payload); } } //... //other listener's methods }); ```
## Decrypt push notification --- This method decrypts the notification payload.
If the notification is not encrypted, the method returns the raw payload.
If a notification is not decrypted successfully, the method returns nil.
**Declared In:** lib/main/modules/NotificationsModule.js **Class:** [NotificationsModule](/developers/mobile-sdk/class-reference/react-native/modules#notifications) **Declaration:**
public decryptNotification(payload: object): object | null
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **payload** | object | yes | - | Notification's key-value data object | **Return Value:** Notification’s key-value data object with decrypted content **Example:**
```JavaScript Synerise.Notifications.setListener({ onNotification: function(payload) { let data = Synerise.Notifications.decryptNotification(payload) // custom notification implementation } //... //other listener's methods }); ```
## Handle Synerise push notification --- This method handles a notification payload and starts activity. **Declared In:** lib/main/modules/NotificationsModule.js **Class:** [NotificationsModule](/developers/mobile-sdk/class-reference/react-native/modules#notifications) **Declaration:**
public handleNotification(payload: object, actionIdentifier: string | null)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **payload** | object | yes | - | Notification's key-value data object | **Return Value:** No value is returned. **Example:**
```JavaScript Synerise.Notifications.setListener({ onNotification: function(payload) { Synerise.Notifications.handleNotification(payload); } //... //other listener's methods }); ```
## Removed methods ### Check if push notification is a Banner Campaign {#check-if-push-notification-is-a-banner-campaign} --- This method verifies if a notification’s sender is Synerise and if the notification is a Banner campaign. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | n/a | **Declared In:** lib/main/modules/NotificationsModule.js **Class:** [NotificationsModule](/developers/mobile-sdk/class-reference/react-native/modules#notifications) **Declaration:**
public isSyneriseBanner(payload: object): boolean
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **payload** | object | yes | - | Notification's key-value data object | **Return Value:** **true** if a notification is a Banner, otherwise **false**. **Example:**
```JavaScript Synerise.Notifications.setListener({ onNotification: function(payload) { if (Synerise.Notifications.isSyneriseBanner(payload)) { Synerise.Notifications.handleNotification(payload); } } //... //other listener's methods }); ```
### Fetch Banners {#fetch-banners} --- This method fetches banners set for mobile campaigns and caches the valid ones. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Removed in: | 4.6.0 | 4.7.0 | 0.12.0 | n/a |
This method was removed in SDK version 0.12.0.
**Declared In:** lib/main/modules/InjectorModule.js **Class:** [InjectorModule](/developers/mobile-sdk/class-reference/react-native/modules#injector) **Declaration:**
public fetchBanners(onSuccess, onError)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **onSuccess** | Function | no | - | Function to be executed when the operation is completed successfully | | **onError** | Function | no | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned. ### Get Banners {#get-banners} --- This method provides valid banners directly from SDK cache. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Removed in: | 4.6.0 | 4.7.0 | 0.12.0 | n/a |
This method was removed in SDK version 0.12.0.
**Declared In:** lib/main/modules/InjectorModule.js **Class:** [InjectorModule](/developers/mobile-sdk/class-reference/react-native/modules#injector) **Declaration:**
public getBanners()
**Return Value:** No value is returned. ### Show Banner {#show-banner} --- This method shows a banner immediately. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Removed in: | 4.6.0 | 4.7.0 | 0.12.0 | - |
This method was removed in SDK version 0.12.0.
**Declared In:** lib/main/modules/InjectorModule.js **Class:** [InjectorModule](/developers/mobile-sdk/class-reference/react-native/modules#injector) **Declaration:**
public showBanner(banner: object, markPresented: boolean)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **banner** | object | yes | - | Object representation of a banner | | **markPresented** | boolean | yes | - | Sets the banner as presented and this banner instance representation will not appear again | **Return Value:** No value is returned. ### Get Walkthrough {#get-walkthrough} --- This method fetches a walkthrough. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | 2.0.0 |
The API key must have the `CAMPAIGN_BACKEND_CAMPAIGN_READ` permission from the **Campaign** group.
**Declared In:** lib/main/modules/InjectorModule.js **Class:** [InjectorModule](/developers/mobile-sdk/class-reference/react-native/modules#injector) **Declaration:**
public getWalkthrough()
**Return Value:** No value is returned. ### Show Walkthrough {#show-walkthrough} --- This method shows a walkthrough when it is loaded. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | 2.0.0 | **Declared In:** lib/main/modules/InjectorModule.js **Class:** [InjectorModule](/developers/mobile-sdk/class-reference/react-native/modules#injector) **Declaration:**
public showWalkthrough()
**Return Value:** No value is returned. ### Check if Walkthrough is loaded {#check-if-walkthrough-is-loaded} --- This method checks if a walkthrough is loaded. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | 2.0.0 | **Declared In:** lib/main/modules/InjectorModule.js **Class:** [InjectorModule](/developers/mobile-sdk/class-reference/react-native/modules#injector) **Declaration:**
public isWalkthroughLoaded(): boolean
**Return Value:** **true** if the walkthrough is loaded, otherwise returns **false**. ### Check if is loaded Walkthrough unique {#check-if-is-loaded-walkthrough-unique} --- This method checks if the walkthrough is unique compared to the previous one. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | 2.0.0 | **Declared In:** lib/main/modules/InjectorModule.js **Class:** [InjectorModule](/developers/mobile-sdk/class-reference/react-native/modules#injector) **Declaration:**
public isLoadedWalkthroughUnique(): boolean
**Return Value:** **true** if the loaded walkthrough is unique, otherwise returns **false**. # Recommendations and Documents ## Recommendations --- ### RecommendationRequestBody Class responsible for creating a recommendation request. **Declared In:** `com.synerise.sdk.content.model.recommendation.RecommendationRequestBody` **Declaration:**
```Java public final class RecommendationRequestBody implements Serializable ```
```Kotlin class RecommendationRequestBody:Serializable ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **productId** | String | no | - | Item identifier of the context item | | **itemsIds** | ArrayList | no | - | List of item identifiers, used for multiple item context | | **itemsExcluded** | ArrayList | no | Items that will be excluded from the generated recommendations | | **additionalFilters** | String | no | Additional filters. These are merged with the campaign's own filters according to the logic in **filtersJoiner** | | **filtersJoiner** | String | no | Defines the logic of merging additionalFilters with the campaign's existing filters | | **additionalElasticFilters** | String | no | Additional elastic filters. These are merged with the campaign's own elastic filters according to the logic in **elasticFiltersJoiner** | | **elasticFiltersJoiner** | String | no | Defines the logic of merging **additionalElasticFilters** with the campaign's existing elastic filters | | **displayAttribute** | ArrayList | no | An array of item attributes which value will be returned in a recommendation response | | **includeContextItems** | Boolean | no | When true, the recommendation response will include context item metadata | **Initializers:** There are no initializers. **Methods:** Setter for productId
public RecommendationRequestBody setProductId(String productId)
--- Setter for itemsIds
public RecommendationRequestBody setItemsIds(ArrayList<String> itemsIds)
--- --- --- ### RecommendationResponse Class responsible for receiving recommendations. **Declared In:** `com.synerise.sdk.content.model.recommendation.RecommendationResponse` **Declaration:**
```Java public class RecommendationResponse ```
```Kotlin class RecommendationResponse ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **recommended** | List<[Recommendation](/developers/mobile-sdk/class-reference/android/recommendations-and-documents#recommendation)> | no | - | List of recommendations | | **extras** | RecommendationResponseExtras | yes | - | Additional details of the recommendation | | **name** | String | no | - | Name of the recommendation campaign | | **campaignHash** | String | no | - | Hash (UUID) of the recommendation campaign | | **campaignId** | String | no | - | ID of the recommendation campaign | | **correlationId** | String | no | - | Recommendation's correlation ID. It can be added to a `recommendation.click` event to associate it with the recommendation request | | **schema** | String | no | - | Schema of the document which contains the recommendation | | **slug** | String | no | - | Slug of the document | | **uuid** | String | no | - | UUID of the document |
All the properties above are accessible by using getters.
**Initializers:** There are no initializers. **Methods:** This method retrieves a recommendation schema.
public String getSchema()
--- This method retrieves the value of the `slug` parameter.
public String getSlug()
--- This method retrieves the value of the `UUID` parameter.
public String getUuid()
--- This method retrieves a list of recommendations.
public List<Recommendation> getRecommendationsV2()
--- This method retrieves the value of the `campaignHash` parameter.
public String getCampaignHash()
--- This method retrieves the value of the `campaignId` parameter.
public String getCampaignId()
--- --- --- ### Recommendation Class model for a recommendation. **Declared In:** `com.synerise.sdk.content.model.recommendation.Recommendation` **Declaration:**
```Java public class Recommendation extends BaseModel ```
```Kotlin class Recommendation : BaseModel ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **itemId** | String | no | - | Product's GTIN | | **feed** | HashMap | no | - | Product’s recommendation attributes |
All the properties above are accessible by using getters and setters.
**Initializers:** There are no initializers. **Methods:** There are only getters and setters for the above properties. --- --- --- ### RecommendationAttribute Class model for custom attributes. **Declared In:** `com.synerise.sdk.content.model.recommendation.RecommendationAtribute` **Declaration:**
```Java public class RecommendationAtribute ```
```Kotlin class RecommendationAtribute ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **name** | String | no | - | Attribute name | | **type** | String | no | - | Attribute type | | **value** | String | no | - | Attribute value |
All the properties above are accessible by using getters and setters.
**Initializers:** There are no initializers. **Methods:** There are only getters and setters for the above properties. --- ## Documents --- ### DocumentApiQuery Class responsible for creating a query to the Documents API. **Declared In:** `com.synerise.sdk.content.model.DocumentApiQuery` **Declaration:**
```Java public class DocumentApiQuery ```
```Kotlin class DocumentApiQuery ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **slug** | String | no | Unique identifier of a document | **Properties used only if the document includes a recommendation insert:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **productId** | String | no | Item identifier of the context item | | **itemsIds** | ArrayList | no | List of item identifiers, used for multiple item context | | **itemsExcluded** | ArrayList | no | Items that will be excluded from the generated recommendations | | **additionalFilters** | String | no | Additional filters. These are merged with the campaign's own filters according to the logic in **filtersJoiner** | | **filtersJoiner** | String | no | Defines the logic of merging additionalFilters with the campaign's existing filters | | **additionalElasticFilters** | String | no | Additional elastic filters. These are merged with the campaign's own elastic filters according to the logic in **elasticFiltersJoiner** | | **elasticFiltersJoiner** | String | no | Defines the logic of merging **additionalElasticFilters** with the campaign's existing elastic filters | | **displayAttribute** | ArrayList | no | An array of item attributes which value will be returned in a recommendation response | | **includeContextItems** | Boolean | no | When true, the recommendation response will include context item metadata | | **params** | HashMap | yes | Additional parameters to pass for [Inserts in the document](/developers/inserts/screen-views-documents#handling-variables-when-displaying-screen-viewsdocuments). For example, if the insert is `{{ foo }}`, you need to pass the value of `foo` | **Initializers:** There is a constructor.
public DocumentApiQuery(String feedSlug)
**Methods:** Setter for feedSlug
public void setFeedSlug(String feedSlug)
--- Setter for additionalFilters
public DocumentApiQuery setAdditionalFilters(String additionalFilters)
--- Setter for itemsExcluded
public DocumentApiQuery setItemsExcluded(ArrayList<String> itemsExcluded)
--- Setter for filtersJoiner
public DocumentApiQuery setFiltersJoiner(FiltersJoinerRule filtersJoiner)
--- Setter for additionalElasticFilters
public DocumentApiQuery setAdditionalElasticFilters(String additionalElasticFilters)
--- Setter for elasticFiltersJoiner
public DocumentApiQuery setElasticFiltersJoiner(FiltersJoinerRule elasticFiltersJoiner)
--- Setter for displayAttributes
public DocumentApiQuery setDisplayAttributes(ArrayList<String> displayAttribute)
--- Setter for includeContextItems
public DocumentApiQuery setIncludeContextItems(Boolean includeContextItems)
--- Setter for itemsIds
public DocumentApiQuery setItemsIds(ArrayList<String> itemsIds)
--- Setter for productId
public DocumentApiQuery setProductId(String productId)
--- --- --- ### Document **Declared In:** `com.synerise.sdk.content.model.document` **Declaration:**
```java public class Document ```
```kotlin class Document ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **uuid** | String | no | Document's identifier (UUID) | | **slug** | String | no | Document's slug | | **schema** | String | no | Document's schema type | | **content** | [AnyHashable: Any] | no | Document's content |
All the properties above are accessible by using getters.
**Initializers:** There are no initializers. **Methods:** There are only getters for the above properties. --- --- ## Removed symbols --- ### DocumentsApiQuery{#documentsapiquery} The object to set parameters easily for fetching documents from API. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.5.10 | 3.5.1 | 0.9.10 | 0.2.0 | | Deprecated in: | 4.13.0 | 5.5.0 | 0.17.0 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | 2.0.0 | Class responsible for creating a query to the Documents API. **Declared In:** `com.synerise.sdk.content.model.DocumentsApiQuery` **Declaration:**
```Java public class DocumentsApiQuery ```
```Kotlin class DocumentsApiQuery ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **type** | [DocumentsApiQueryType](/developers/mobile-sdk/class-reference/android/recommendations-and-documents#documentsapiquerytype) | yes | - | Document's query type | | **typeValue** | String | yes | - | Document's query type value | | **version** | String | yes | - | Document version | **Initializers:** There are no initializers. **Methods:** This method sets query parameters.
public void setDocumentQueryParameters(DocumentsApiQueryType type, String typeValue)
--- This method sets a document version.
public void setVersion(String version)
--- --- --- ### DocumentsApiQueryType{#documentsapiquerytype} | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.5.10 | 3.5.1 | 0.9.10 | 0.2.0 | | Deprecated in: | 4.13.0 | 5.5.0 | 0.17.0 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | 2.0.0 | This enum contains values for the Documents API query type. **Declared In:** `com.synerise.sdk.content.model.DocumentsApiQueryType` **Declaration:**
```Java public enum DocumentsApiQueryType ```
```Kotlin public enum DocumentsApiQueryType ```
**Values:** | Property | Value | Description | | --- | --- | --- | | **SCHEMA** | "by-schema" | Query type | **Methods:** Get by path type.
public static DocumentsApiQueryType getByPathType(String type)
--- # Campaigns --- ## Set Injector listener --- This method sets callbacks for an injector module. **Declared In:** lib/modules/injector/injector_impl.dart **Related To:** [InjectorListener](/developers/mobile-sdk/listeners-and-delegates/react-native-listeners#injector-listener) **Class:** [InjectorImpl](/developers/mobile-sdk/class-reference/flutter/modules#injector) **Declaration:**
void listener(InjectorListenerFunction listenerFunction)
**Discussion:** Learn more about the methods and their purpose of this listener [here](/developers/mobile-sdk/listeners-and-delegates/flutter-listeners#injector-listener). ## Set In-App Message listener --- This method sets callbacks for in-app message campaigns. **Declared In:** lib/modules/injector/injector_impl.dart **Related To:** [InjectorInAppMessageListener](/developers/mobile-sdk/listeners-and-delegates/react-native-listeners#injector-in-app-message-listener) **Class:** [InjectorImpl](/developers/mobile-sdk/class-reference/flutter/modules#injector) **Declaration:**
void inAppMessageListener(InjectorInAppMessageListenerFunction listenerFunction)
**Discussion:** Learn more about the methods and their purpose of this listener [here](/developers/mobile-sdk/listeners-and-delegates/flutter-listeners#injector-in-app-message-listener). ## Close in-app message --- Closes an in-app message and sends an `inApp.discard` event. Usage examples: - Closing a top bar or bottom bar when the user taps outside the in-app area. - Automatically dismissing messages when navigating away from a screen. - Controlling in-app visibility based on app logic for a smoother user experience. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | ----------------------------------------------- | ----------- | --------------- | -------------------- | --------------- | | Introduced in: | 5.7.0 | 6.7.0 | 1.5.0 | 2.5.0 | **Declared In:** lib/modules/injector/injector_impl.dart **Declaration:**
void closeInAppMessage(String campaignHash)
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | ---------------- | ------ | --------- | ------- | ---------------------------------------- | | **campaignHash** | string | yes | - | Unique identifier of the in-app campaign | ## Register for push notifications --- This method passes the Firebase Token to Synerise for notifications.
- You should call this method every time the user changes the system or application consent for notifications. - The API key must have the `API_PERSONAL_DEVICE_CLIENT_UPDATE` permission from the **Client** group. - If the registration fails, the SDK requests a token update again by a listener/delegate method ([Android](/developers/mobile-sdk/listeners-and-delegates/android-listeners#on-register-for-push-listener), [iOS](/developers/mobile-sdk/listeners-and-delegates/ios-delegates#synerise-delegate-register-for-push-notifications-is-needed), [React Native](/developers/mobile-sdk/listeners-and-delegates/react-native-listeners#notifications-listener), [Flutter](/developers/mobile-sdk/listeners-and-delegates/flutter-listeners#notifications-listener)).
**Declared In:** lib/modules/notifications/notifications_impl.dart **Class:** [NotificationsImpl](/developers/mobile-sdk/class-reference/flutter/modules#notifications)
**Declaration:**
Future<void> registerForNotifications(String registrationToken,
      {bool? mobileAgreement,
      required void Function() onSuccess,
      required void Function(SyneriseError error) onError})
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **registrationToken** | String | yes | - | Firebase Token | | **mobileAgreement** | bool | no | null | Agreement (consent) for receiving mobile push campaigns | | **onSuccess** | Function() | yes | - | Function to be executed when the operation is completed successfully | | **onError** | Function([SyneriseError](/developers/mobile-sdk/class-reference/flutter/miscellaneous#syneriseerror) error) | yes | - | Function to be executed when the operation is completed with an error | **Return Value:** No value is returned.
This method also allows using the `registerForPushWithoutAgreement` native method. The `registerForPushWithoutAgreement` method will be used when the `mobileAgreement` parameter is not filled.
**Example:**
FirebaseMessaging.instance.onTokenRefresh.listen((event) {
      FirebaseMessaging.instance.getToken().then((token) {
        if (token != null) {
          firebaseToken = token;
          Synerise.notifications.registerForNotifications(
            firebaseToken!,
            mobileAgreement: true,
            onSuccess: () {},
            onError: (error) {},
          );
        }
      });
    });
**Declaration:**
Future<void> registerForNotifications(String registrationToken, [bool? mobileAgreement])
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **registrationToken** | String | yes | - | Firebase Token | | **mobileAgreement** | bool | no | null | Agreement (consent) for receiving mobile push campaigns | **Return Value:** No value is returned.
This method also allows to use `registerForPushWithoutAgreement` native method. The `registerForPushWithoutAgreement` method will be used when the `mobileAgreement` parameter is not filled.
**Example:**
FirebaseMessaging.instance.onTokenRefresh.listen((event) {
      FirebaseMessaging.instance.getToken().then((token) {
        if (token != null) {
          firebaseToken = token;
          Synerise.notifications.registerForNotifications(
            firebaseToken!,
            mobileAgreement: true,
          );
        }
      });
    });
## Handle Synerise push notification --- This method handles a notification payload and starts activity. **Declared In:** lib/modules/notifications/notifications_impl.dart **Class:** [NotificationsImpl](/developers/mobile-sdk/class-reference/flutter/modules#notifications) **Declaration:**
Future<bool> handleNotification(Map notification) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **notification** | Map | yes | - | Notification’s key-value data object | **Return Value:** **true** if the notification is handled properly. **Example:**
```Dart FirebaseMessaging.onMessage.listen((RemoteMessage message,) { Synerise.notifications.handleNotification(message.toMap()); }); FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) { Synerise.notifications.handleNotificationClick(message.toMap()); }); ```
## Handle Synerise push notification click --- This method handles a notification payload with a user interaction and starts activity. **Declared In:** lib/modules/notifications/notifications_impl.dart **Class:** [NotificationsImpl](/developers/mobile-sdk/class-reference/flutter/modules#notifications) **Declaration:**
Future<bool> handleNotificationClick(Map notification) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **notification** | Map | yes | - | Notification’s key-value data object | **Return Value:** **true** if the notification is handled properly. **Example:**
```Dart FirebaseMessaging.onMessage.listen((RemoteMessage message,) { Synerise.notifications.handleNotification(message.toMap()); }); FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) { Synerise.notifications.handleNotificationClick(message.toMap()); }); ```
## Check if push notification is from Synerise --- This method verifies if a notification was sent by Synerise. **Declared In:** lib/modules/notifications/notifications_impl.dart **Class:** [NotificationsImpl](/developers/mobile-sdk/class-reference/flutter/modules#notifications) **Declaration:**
Future<bool> isSyneriseNotification(Map notification) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **notification** | Map | yes | - | Key-Value map of data | **Return Value:** **true** if the notification is provided by Synerise, otherwise returns **false**. **Example:**
```Dart bool isSyneriseNotification = await Synerise.notifications.isSyneriseNotification(remoteMessageMap); ```
## Check if push notification is a Simple Push Campaign --- This method verifies if a notification’s sender is Synerise and if the notification is a Simple Push campaign **Declared In:** lib/modules/notifications/notifications_impl.dart **Class:** [NotificationsImpl](/developers/mobile-sdk/class-reference/flutter/modules#notifications) **Declaration:**
Future<bool> isSyneriseSimplePush(Map notification) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **notification** | Map | yes | - | Key-Value map of data | **Return Value:** **true** if the notification is Synerise Simple Push provided by Synerise, otherwise returns **false**. **Example:**
```Dart bool isSyneriseSimplePush = await Synerise.notifications.isSyneriseSimplePush(remoteMessageMap); ```
## Check if push notification is a Silent Command --- This method verifies if a notification’s sender is Synerise and if the notification is a Silent Command. **Declared In:** lib/modules/notifications/notifications_impl.dart **Class:** [NotificationsImpl](/developers/mobile-sdk/class-reference/flutter/modules#notifications) **Declaration:**
Future<bool> isSilentCommand(Map notification) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **notification** | Map | yes | - | Key-Value map of data | **Return Value:** **true** if the notification is Synerise Silent Command provided by Synerise, otherwise returns **false**. **Example:**
```Dart bool isSilentCommand = await Synerise.notifications.isSilentCommand(remoteMessageMap); ```
## Check if push notification is a Silent SDK Command --- This method verifies if a notification's sender is Synerise and if the notification is a Silent SDK Command. **Declared In:** lib/modules/notifications/notifications_impl.dart **Class:** [NotificationsImpl](/developers/mobile-sdk/class-reference/flutter/modules#notifications) **Declaration:**
Future<bool> isSilentSDKCommand(Map notification) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **notification** | Map | yes | - | Key-Value map of data | **Return Value:** **true** if the notification is Synerise Silent SDK Command provided by Synerise, otherwise returns **false**. **Example:**
```Dart bool isSilentSDKCommand = await Synerise.notifications.isSilentSDKCommand(remoteMessageMap); ```
## Removed methods ### Check if push notification is a Banner Campaign {#check-if-push-notification-is-a-banner-campaign} --- This method verifies if a notification’s sender is Synerise and if the notification is a Banner campaign. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | n/a | **Declared In:** lib/modules/notifications/notifications_impl.dart **Class:** [NotificationsImpl](/developers/mobile-sdk/class-reference/flutter/modules#notifications) **Declaration:**
Future<bool> isSyneriseBanner(Map notification) async
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **notification** | Map | yes | - | Key-Value map of data | **Return Value:** **true** if the notification is Synerise Banner provided by Synerise, otherwise returns **false**. **Example:**
```Dart bool isSyneriseBanner = await Synerise.notifications.isSyneriseBanner(remoteMessageMap); ```
### Get Walkthrough {#get-walkthrough} --- This method fetches a walkthrough. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | 2.0.0 |
The API key must have the `CAMPAIGN_BACKEND_CAMPAIGN_READ` permission from the **Campaign** group.
**Declared In:** lib/modules/injector/injector_impl.dart **Class:** [InjectorImpl](/developers/mobile-sdk/class-reference/flutter/modules#injector) **Declaration:**
void getWalkthrough()
**Return Value:** No value is returned. **Example:**
```Dart Synerise.injector.getWalkthrough(); ```
### Show Walkthrough {#show-walkthrough} --- This method shows a walkthrough when it is loaded. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | 2.0.0 | **Declared In:** lib/modules/injector/injector_impl.dart **Class:** [InjectorImpl](/developers/mobile-sdk/class-reference/flutter/modules#injector) **Declaration:**
void showWalkthrough()
**Return Value:** No value is returned. **Example:**
```Dart Synerise.injector.showWalkthrough(); ```
### Check if Walkthrough is loaded {#check-if-walkthrough-is-loaded} --- This method checks if a walkthrough is loaded. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | 2.0.0 | **Declared In:** lib/modules/injector/injector_impl.dart **Class:** [InjectorImpl](/developers/mobile-sdk/class-reference/flutter/modules#injector) **Declaration:**
Future<bool> isWalkthroughLoaded()
**Return Value:** **true** if the walkthrough is loaded, otherwise returns **false**. **Example:**
```Dart var isLoaded = await Synerise.injector.isWalkthroughLoaded(); ```
### Check if is loaded Walkthrough unique {#check-if-is-loaded-walkthrough-unique} --- This method checks if the walkthrough is unique compared to the previous one. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | 2.0.0 | **Declared In:** lib/modules/injector/injector_impl.dart **Class:** [InjectorImpl](/developers/mobile-sdk/class-reference/flutter/modules#injector) **Declaration:**
Future<bool> isLoadedWalkthroughUnique()
**Return Value:** **true** if the loaded walkthrough is unique, otherwise returns **false**. **Example:**
```Dart var isLoaded = await Synerise.injector.isLoadedWalkthroughUnique(); ```
# Recommendations and Documents ## Recommendations --- ### RecommendationResponse **Declared In:** Headers/SNRRecommendationResponse.h **Related To:** [Recommendation](/developers/mobile-sdk/class-reference/ios/recommendations-and-documents#recommendation) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class RecommendationResponse ```
```Objective-C @interface SNRRecommendationResponse ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **name** | String | no | Name of the recommendation campaign | | **campaignHash** | String | no | Hash (UUID) of the recommendation campaign | | **campaignID** | String | no | ID of the recommendation campaign | | **correlationID** | String | no | Recommendation's correlation ID. It can be added to a `recommendation.click` event to associate it with the recommendation request | | **extras** | RecommendationResponseExtras | yes | Additional details of the recommendation | | **schema** | String | no | Schema of the document which contains the recommendation| | **slug** | String | no | Slug of the document | | **uuid** | String | no | UUID of the document | | **items** | [[Recommendation]](/developers/mobile-sdk/class-reference/ios/recommendations-and-documents/#recommendation) | no | List of items in the recommendation | --- --- ### Recommendation **Declared In:** Headers/SNRRecommendation.h **Related To:** [RecommendationResponse](/developers/mobile-sdk/class-reference/ios/recommendations-and-documents#recommendationresponse) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class Recommendation ```
```Objective-C @interface SNRRecommendation ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **itemID** | String | no | Product's GTIN | | **attributes** | [AnyHashable: Any] | no | Product’s recommendation attributes | --- --- ### RecommendationOptions **Declared In:** Headers/SNRRecommendationOptions.h **Related To:** [RecommendationFiltersJoinerRule](/developers/mobile-sdk/class-reference/ios/recommendations-and-documents#recommendationfiltersjoinerrule) **Declaration:**
```Swift class RecommendationOptions ```
```Objective-C @interface SNRRecommendationOptions ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **slug** | String | no | Unique identifier of a document which includes a recommendation insert | | **productID** | String | no | Item identifier of the context item | | **productIDs** | [String] | no | List of item identifiers, used for multiple item context | | **itemsExcluded** | [String] | no | Items that will be excluded from the generated recommendations | | **additionalFilters** | String | no | Additional filters. These are merged with the campaign's own filters according to the logic in **filtersJoiner** | | **filtersJoiner** | [RecommendationFiltersJoinerRule](/developers/mobile-sdk/class-reference/ios/recommendations-and-documents#recommendationfiltersjoinerrule) | no | Defines the logic of merging additionalFilters with the campaign's existing filters | | **additionalElasticFilters** | String | no | Additional elastic filters. These are merged with the campaign's own elastic filters according to the logic in **elasticFiltersJoiner** | | **elasticFiltersJoiner** | [RecommendationFiltersJoinerRule](/developers/mobile-sdk/class-reference/ios/recommendations-and-documents#recommendationfiltersjoinerrule) | no | Defines the logic of merging **additionalElasticFilters** with the campaign's existing elastic filters | | **displayAttribute** | [String] | no | An array of item attributes which value will be returned in a recommendation response | | **includeContextItems** | Bool | no | When true, the recommendation response will include context item metadata | --- --- ### RecommendationFiltersJoinerRule **Declared In:** Headers/SNRRecommendationOptions.h **Declaration:**
```Swift enum RecommendationFiltersJoinerRule: Int { and, or, replace } ```
```Objective-C typedef NS_ENUM(NSUInteger, SNRRecommendationFiltersJoinerRule) { SNRRecommendationFiltersJoinerRuleAnd, SNRRecommendationFiltersJoinerRuleOr, SNRRecommendationFiltersJoinerRuleReplace } ```
**Functions:** Converts from **RecommendationFiltersJoinerRule** to **String**.
```Swift func SNR_RecommendationFiltersJoinerRuleToString(_: RecommendationFiltersJoinerRule) -> String ```
```Objective-C NSString * SNR_RecommendationFiltersJoinerRuleToString(SNRRecommendationFiltersJoinerRule rule) ```

--- --- ## Documents --- ### DocumentApiQuery The object to set parameters easily for fetching documents from API. **Declared In:** Headers/SNRDocumentApiQuery.h **Inherits From:** [NSObject](https://developer.apple.com/documentation/objectivec/nsobject) **Declaration:**
```Swift class DocumentApiQuery: NSObject ```
```Objective-C @interface SNRDocumentApiQuery : NSObject ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **slug** | String | no | nil | Unique identifier of a document | **Properties used only if the document includes a recommendation insert:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **productId** | String | yes | Item identifier of the context item | | **itemsIds** | [String] | yes | List of item identifiers, used for multiple item context | | **itemsExcluded** | [String] | yes | Items that will be excluded from the generated recommendations | | **additionalFilters** | String | yes | Additional filters. These are merged with the campaign's own filters according to the logic in **filtersJoiner** | | **filtersJoiner** | [RecommendationFiltersJoinerRule](/developers/mobile-sdk/class-reference/ios/recommendations-and-documents#recommendationfiltersjoinerrule) | yes | Defines the logic of merging additionalFilters with the campaign's existing filters | | **additionalElasticFilters** | String | yes | Additional elastic filters. These are merged with the campaign's own elastic filters according to the logic in **elasticFiltersJoiner** | | **elasticFiltersJoiner** | [RecommendationFiltersJoinerRule](/developers/mobile-sdk/class-reference/ios/recommendations-and-documents#recommendationfiltersjoinerrule) | yes | Defines the logic of merging **additionalElasticFilters** with the campaign's existing elastic filters | | **displayAttribute** | [String] | yes | An array of item attributes which value will be returned in a recommendation response | | **includeContextItems** | Bool | yes | When true, the recommendation response will include context item metadata | | **params** | [String: Any] | yes | Additional parameters to pass for [Inserts in the document](/developers/inserts/screen-views-documents#handling-variables-when-displaying-screen-viewsdocuments). For example, if the insert is `{{ foo }}`, you need to pass the value of `foo` | **Initializers:**
```Swift init(slug: String) ```
```Objective-C - (instancetype)initWithSlug:(NSString *)slug ```
--- --- ### Document **Declared In:** Headers/SNRDocument.h **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/ios/miscellaneous#basemodel) **Declaration:**
```Swift class Document: BaseModel ```
```Objective-C @interface SNRDocument : SNRBaseModel ```
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **uuid** | String | no | Document's identifier (this parameter was called **identifier** before version 5.0.0) | | **slug** | String | no | Document's slug | | **schema** | String | no | Document's schema type | | **content** | [AnyHashable: Any] | no | Document's content |
All properties are read-only.
--- --- ## Removed symbols --- ### DocumentsApiQuery{#documentsapiquery} The object to set parameters easily for fetching documents from API. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.5.10 | 3.5.1 | 0.9.10 | 0.2.0 | | Deprecated in: | 4.13.0 | 5.5.0 | 0.17.0 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | 2.0.0 | **Declared In:** Headers/SNRDocumentsApiQuery.h **Related To:** [DocumentsApiQueryType](/developers/mobile-sdk/class-reference/ios/recommendations-and-documents#documentsapiquerytype) **Inherits From:** [NSObject](https://developer.apple.com/documentation/objectivec/nsobject) **Declaration:**
```Swift class DocumentsApiQuery: NSObject ```
```Objective-C @interface SNRDocumentsApiQuery : NSObject ```
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **type** | [DocumentsApiQueryType](/developers/mobile-sdk/class-reference/ios/recommendations-and-documents#documentsapiquerytype) | no | .bySchema | Query type | | **typeValue** | String | no | nil | Value for query type | | **version** | String | yes | nil | Specifies the document version | **Initializers:**
```Swift init(type: DocumentsApiQueryType, value: String) ```
```Objective-C - (instancetype)initWithType:(SNRDocumentsApiQueryType)type typeValue:(nonnull NSString *)typeValue ```
--- --- ### DocumentsApiQueryType{#documentsapiquerytype} **Declared In:** Headers/SNRDocumentsApiQueryType.h **Declaration:**
```Swift enum DocumentsApiQueryType: Int { bySchema } ```
```Objective-C typedef NS_ENUM(NSInteger, SNRDocumentsApiQueryType) { SNRDocumentsApiQueryTypeBySchema } ```
# Mobile SDK This section explains how to implement and use Synerise SDK in your mobile applications (Android, iOS, React Native). The best way to start is to read the [Overview](/developers/mobile-sdk/overview) article. It contains all information about the possibilities Mobile SDK offers. After reading the Overview, we recommend familiarizing with the instructions and performing the actions described in them in the presented order: - [Installation and configuration](/developers/mobile-sdk/installation-and-configuration) - [Configuring push notifications](/developers/mobile-sdk/configuring-push-notifications) - [Settings](/developers/mobile-sdk/settings) - [Profile identification, authorization and management](/developers/mobile-sdk/user-identification-and-authorization) - [Event tracking](/developers/mobile-sdk/event-tracking) - [Campaigns](/developers/mobile-sdk/campaigns) - [Loyalty](/developers/mobile-sdk/loyalty) After that, you can read and configure the other modules in any order. # Recommendations and Documents ## Recommendations --- ### RecommendationResponse **Declared In:** lib/classes/content/RecommendationResponse.js **Related To:** [Recommendation](/developers/mobile-sdk/class-reference/react-native/recommendations-and-documents#recommendation) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
class RecommendationResponse extends BaseModel
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **name** | string | no | Name of the recommendation campaign | | **campaignHash** | string | no | Hash (UUID) of the recommendation campaign | | **campaignID** | string | no | ID of the recommendation campaign | | **items** | [Array](/developers/mobile-sdk/class-reference/react-native/recommendations-and-documents#recommendation) | no | List of items in the recommendation | --- --- ### Recommendation Model representating a recommendation item data.
This is a read-only class and it is not meant to be instantiated directly.
**Declared In:** lib/classes/Content/Recommendation.js **Related To:** [RecommendationResponse](/developers/mobile-sdk/class-reference/react-native/recommendations-and-documents#recommendationresponse) **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
class Recommendation extends BaseModel
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **itemID** | string | no | Product's GTIN | | **attributes** | Record | no | Product's recommendation attributes | --- --- ### RecommendationOptions **Declared In:** lib/classes/content/RecommendationOptions.js **Declaration:**
class RecommendationOptions
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **slug** | string | no | Unique identifier of a document which includes a recommendation insert | | **productID** | string | no | Item identifier of the context item | --- --- ### RecommendationFiltersJoinerRule **Declared In:** lib/classes/models/Content/RecommendationOptions.js **Declaration:**
enum RecommendationFiltersJoinerRule {
  And = 'AND',
  Or = 'OR',
  Replace = 'REPLACE'
}
--- --- ## Documents --- ### DocumentApiQuery The object to set parameters easily for fetching screen views from API. **Declared In:** lib/classes/api_queries/DocumentApiQuery.js **Declaration:**
class DocumentApiQuery
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **slug** | string | no | Unique identifier of a document | **Properties used only if the document includes a recommendation insert:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **productId** | string | yes | Item identifier of the context item | | **itemsIds** | Array | yes | List of item identifiers, used for multiple item context | | **itemsExcluded** | Array | yes | Items that will be excluded from the generated recommendations | | **additionalFilters** | string | yes | Additional filters. These are merged with the campaign's own filters according to the logic in **filtersJoiner** | | **filtersJoiner** | [RecommendationFiltersJoinerRule](/developers/mobile-sdk/class-reference/react-native/recommendations-and-documents#recommendationfiltersjoinerrule) | no | Defines the logic of merging additionalFilters with the campaign's existing filters | | **additionalElasticFilters** | string | yes | Additional elastic filters. These are merged with the campaign's own elastic filters according to the logic in **elasticFiltersJoiner** | | **elasticFiltersJoiner** | [RecommendationFiltersJoinerRule](/developers/mobile-sdk/class-reference/react-native/recommendations-and-documents#recommendationfiltersjoinerrule) | no | Defines the logic of merging **additionalElasticFilters** with the campaign's existing elastic filters | | **displayAttribute** | Array | yes | An array of item attributes which value will be returned in a recommendation response | | **includeContextItems** | boolean | yes | When true, the recommendation response will include context item metadata | **Initializers:**
constructor()
--- --- ### Document Model representing a highest-priority customer screen view campaign.
This is a read-only class and it is not meant to be instantiated directly.
**Declared In:** lib/classes/content/Document.js **Inherits From:** [BaseModel](/developers/mobile-sdk/class-reference/react-native/miscellaneous#basemodel) **Declaration:**
class Document extends BaseModel
**Properties:** | Property | Type | Optional | Description | | --- | --- | --- | --- | | **uuid** | string | no | Document's identifier (UUID) | | **slug** | string | no | Document's slug | | **schema** | string | no | Document's schema type | | **content** | object | no | Document's content | --- --- ## Removed symbols --- ### DocumentsApiQuery{#documentsapiquery} The object to set parameters easily for fetching documents from API. | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.5.10 | 3.5.1 | 0.9.10 | 0.2.0 | | Deprecated in: | 4.13.0 | 5.5.0 | 0.17.0 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | 2.0.0 | The object to set parameters easily for fetching documents from API. **Declared In:** lib/classes/api_queries/DocumentsApiQuery.js **Related To:** [DocumentsApiQueryType](/developers/mobile-sdk/class-reference/react-native/recommendations-and-documents#documentsapiquerytype) **Declaration:**
class DocumentsApiQuery
**Properties:** | Property | Type | Optional | Default | Description | | --- | --- | --- | --- | --- | | **type** | [DocumentsApiQueryType](/developers/mobile-sdk/class-reference/react-native/recommendations-and-documents#documentsapiquerytype) | no | .bySchema | Query type | | **typeValue** | string | no | nil | Value for query type | | **version** | string | yes | nil | Specifies the document version | **Initializers:**
constructor(type: DocumentsApiQueryType, typeValue: string, version: string)
--- --- ### DocumentsApiQueryType {#documentsapiquerytype} | | **iOS SDK** | **Android SDK** | **React Native SDK** | **Flutter SDK** | | --- | --- | --- | --- | --- | | Introduced in: | 3.5.10 | 3.5.1 | 0.9.10 | 0.2.0 | | Deprecated in: | 4.13.0 | 5.5.0 | 0.17.0 | n/a | | Removed in: | 5.0.0 | 6.0.0 | 1.0.0 | 2.0.0 | **Declared In:** lib/classes/api_queries/DocumentsApiQueryType.js **Declaration:**
enum DocumentsApiQueryType {
    SCHEMA = 'by-schema',
}
# Event tracking ## Get customer's events --- This method retrieves events for an authenticated customer. This method requires customer authentication. **Method name:** Client.getEvents(clientEventsQuery) **Declaration:**
```Java public static IDataApiCall> getEvents(ClientEventsQuery clientEventsQuery) ```
```Kotlin fun getEvents(clientEventsQuery:ClientEventsQuery):IDataApiCall> ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **clientEventsQuery** | ClientEventsQuery | yes | - | Object to create clientEvent query | **Return Value:** [IDataApiCall](/developers/mobile-sdk/method-reference/android/public-interfaces#idataapicall)> object to execute the request. **Example:**
```Java private IDataApiCall> getEventClientsCall; if (getEventClientsCall != null) getEventClientsCall.cancel(); getEventClientsCall = Client.getEvents(clientEventsQuery); getEventClientsCall.execute(({ this.onSuccess() }), ({ this.onFailure() }); ```
```Kotlin private val getEventClientsCall:IDataApiCall> if (getEventClientsCall != null) getEventClientsCall.cancel() getEventClientsCall = Client.getEvents(clientEventsQuery) getEventClientsCall.execute(({ this.onSuccess() }), ({ this.onFailure() }) ```
## Set custom identifier for events --- This method sets a custom identifier in the parameters of every event. You can pass a custom identifier to match your customers in our database. **Method name:** Tracker.setCustomIdentifier(customIdentifier) **Declaration:**
```java public static void setCustomIdentifier(String customIdentifier) ```
```kotlin fun setCustomIdentifier(customIdentifier:String) ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **customIdentifier** | String | yes | - | Client's custom identifier | **Return Value:** Void type method. **Example:**
```java Tracker.setCustomIdentifier(customIdentifier) ```
```kotlin Tracker.setCustomIdentifier(customIdentifier) ```
## Set custom email for events --- This method sets a custom email in the parameters of every event. You can pass a custom email to match your customers in our database. **Method name:** Tracker.setCustomEmail(customEmail) **Declaration:**
```java public static void setCustomEmail(String customEmail) ```
```kotlin fun setCustomEmail(customEmail:String) ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **customEmail** | String | yes | - | Customer's email | **Return Value:** Void type method. **Example:**
```java private void setCustomEmail(String customEmail) { Tracker.setCustomEmail(customEmail); } ```
```kotlin private fun setCustomEmail(customEmail:String) { Tracker.setCustomEmail(customEmail) } ```
## Send event --- This method sends an event.
DO NOT send `transaction.charge` events as custom events.
Transactions must be tracked with these endpoints: - [`/v4/transactions`](https://hub.synerise.com/api-reference/data-management#operation/CreateATransaction) (single transaction) - [`/v4/transactions/batch`](https://hub.synerise.com/api-reference/data-management#operation/BatchAddOrUpdateTransactions) (multiple transactions)
- The tracker caches and enqueues all your events locally, so they all will be sent eventually. - The API key must have the `API_BATCH_EVENTS_CREATE` permission from the **Events** group.
It also supports Android O's [Background Execution Limits](https://developer.android.com/about/versions/oreo/background.html). **Method name:** Tracker.send(event) **Declaration:**
```java public static void send(Event event) ```
```kotlin fun send(event:Event) ```
**Parameters:** | Parameter | Type | Mandatory | Default | Description | | --- | --- | --- | --- | --- | | **event** | Event | yes | - | Event object (e.g. `CustomEvent()` instance). | **Return Value:** Void type method. **Example:**
```java Tracker.send(new CustomEvent("my.action", "label")); ```
```kotlin Tracker.send(CustomEvent("my.action", "label")) ```
## Flush events from Tracker --- This method forces sending the events from the queue to the server.
The API key must have the `API_BATCH_EVENTS_CREATE` permission from the **Events** group.
**Method name:** Tracker.flush() **Declaration:**
```java public static void flush() ```
```kotlin fun flush() ```
**Parameters:** No parameters required. **Return Value:** Void type method. **Example:**
```java Tracker.flush(); ```
```kotlin Tracker.flush(); ```