Tracking for iOS SDK
Track customers and events using the iOS SDK
You can track events in Marketing to learn more about your app’s usage patterns and to segment your customers by their interactions.
By default, the SDK tracks certain events automatically, including:
- Installation (after app installation and after invoking anonymize)
- User session start and end
- Banner event for showing an in-app message or content block
notification_stateevent for push notification token tracking (SDK versions 3.8.0 and higher). Learn more.
Additionally, you can track any custom event relevant to your business.
Also see Mobile SDK tracking FAQ at Bloomreach Support Help Center.
Protect the privacy of your customers
Make sure you have obtained and stored tracking consent from your customer before initializing Exponea iOS SDK.
To ensure you're not tracking events without the customer's consent, you can use
Exponea.shared.clearLocalCustomerData(appGroup: String)when a customer opts out from tracking (this applies to new users or returning customers who have previously opted out). This will bring the SDK to a state as if it was never initialized. This option also prevents reusing existing cookies for returning customers.Refer to Clear local customer data for details.
If customer denied tracking consent after Exponea iOS SDK is initialized, you can use
Exponea.shared.stopIntegration()to stop SDK integration and remove all locally stored data.Refer to Stop SDK integration for details.
Events
Track event
Use the trackEvent() method to track any custom event type relevant to your business.
You can use any name for a custom event type. We recommended using a descriptive and human-readable name.
Refer to the Custom events documentation for an overview of commonly used custom events.
Arguments
| Name | Type | Description |
|---|---|---|
| properties | [String: JSONConvertible] | Dictionary of event properties. |
| timestamp | Double | Unix timestamp specifying when the event was tracked. Specify nil value to use the current time. |
| eventType (required) | String | Name of the event type, for example screen_view. |
Examples
Imagine you want to track which screens a customer views. You can create a custom event screen_view for this.
First, create a dictionary with properties you want to track with this event. In our example, you want to track the name of the screen, so you include a property screen_name along with any other relevant properties:
let properties: [String: JSONConvertible] = [
"screen_name": "dashboard",
"other_property": 123.45
]Pass the dictionary to trackEvent() along with the eventType (screen_view) as follows:
Exponea.shared.trackEvent(properties: properties,
timestamp: nil,
eventType: "screen_view")The second example below shows how you can use a nested JSON structure for complex properties if needed:
let properties: [String: JSONConvertible] = [
"purchase_status": "success",
"product_list": [
["product_id": "abc123", "quantity": 2],
["product_id": "abc456", "quantity": 1]
],
"total_price": 7.99,
]
Exponea.shared.trackEvent(properties: properties,
timestamp: nil,
eventType: "purchase")Optionally, you can provide a custom
timestampif the event happened at a different time. By default, the current time will be used.
Customers
Identifying your customers allows you to track them across devices and platforms, improving the quality of your customer data.
Without identification, events are tracked for an anonymous customer, only identified by a cookie. Once the customer is identified by a hard ID, these events will be transferred to a newly identified customer.
Keep in mind that, while an app user and a customer record can be related by a soft or hard ID, they are separate entities, each with their own lifecycle. Take a moment to consider how their lifecycles relate and when to use identify and anonymize.
Identify
Use the identifyCustomer() method to identify a customer using their unique hard ID.
The default hard ID is registered and its value is typically the customer's email address. However, your Marketing project may define a different hard ID.
Optionally, you can track additional customer properties such as first and last names, age, etc.
Although it's possible to use
identifyCustomerwith a soft ID, developers should use caution when doing this. In some cases (for example, after usinganonymize), this can unintentionally associate the current user with an incorrect customer profile.
The SDK stores data, including customer hard ID, in a local cache on the device. Removing the hard ID from the local cache requires calling anonymize in the app.
If the customer profile is anonymized or deleted in the Marketing webapp, subsequent initialization of the SDK in the app can cause the customer profile to be reidentified or recreated from the locally cached data.
Always use a hard ID to identify a customer. Using a soft ID with
identifyCustomercould unintentionally cause the customer to be associated with an incorrect profile.
Arguments
| Name | Type | Description |
|---|---|---|
| customerIds (required) | [String: String] | Dictionary of customer unique identifiers. Only identifiers defined in the Marketing project are accepted. |
| properties | [String: JSONConvertible] | Dictionary of customer properties. |
| timestamp | Double | Unix timestamp specifying when the customer properties were updated. Specify the nil value to use the current time. |
Examples
First, create a dictionary containing at least the customer's hard ID:
let customerIds: [String: JSONConvertible] = [
"registered": "[email protected]"
]Optionally, create a dictionary with additional customer properties:
let properties: [String: JSONConvertible] = [
"first_name": "Jane",
"last_name": "Doe",
"age": 32
]Pass the customerIds and properties dictionaries to identifyCustomer():
Exponea.identifyCustomer(customerIds: customerIds,
properties: properties,
timestamp: nil)If you only want to update the customer ID without any additional properties, you can pass an empty dictionary literal for properties:
Exponea.identifyCustomer(customerIds: customerIds,
properties: [:],
timestamp: nil)Optionally, you can provide a custom
timestampif the identification happened at a different time. By default the current time will be used.
Identify with auth context (Stream/Data hub)
When using Stream JWT integration, you can provide customer IDs and the JWT token together using identifyCustomer(context:properties:timestamp:). This is the preferred method for Stream mode as it atomically associates the customer identity with the JWT.
Arguments
| Name | Type | Description |
|---|---|---|
| context (required) | CustomerIdentity | Contains customerIds (dictionary of customer IDs) and optional jwtToken (Stream JWT). |
| properties | [String: JSONConvertible] | Dictionary of customer properties. |
| timestamp | Double | Unix timestamp specifying when the identification happened. Specify nil to use the current time. |
Example
let context = CustomerIdentity(
customerIds: ["registered": "[email protected]"],
jwtToken: "YOUR_STREAM_JWT_TOKEN"
)
Exponea.shared.identifyCustomer(context: context, properties: [:], timestamp: nil)The JWT is stored in the Keychain and used for subsequent Stream requests. You can omit jwtToken if the token was already set via setSdkAuthToken.
Anonymize
Use the anonymize() method to delete all information stored locally and reset the current SDK state. A typical use case for this is when the user signs out of the app.
Invoking this method will cause the SDK to:
- Track a
session_endevent ifautomaticSessionTrackingis enabled. - Invalidate the push notification token by tracking
notification_statewithvalid: false. - In Stream mode with a JWT or a JWT error handler set, try to send all pending events to the server with the current JWT while it is still available. Otherwise, the events stay in the queue and the SDK sends them later.
- Remove the push notification token for the current customer from local device storage and the customer profile in Marketing.
- Clear local repositories and caches, excluding tracked events.
- Clear the JWT from the Keychain (Stream mode).
- If
regenerateDeviceIdOnAnonymizeis set totrue, regenerate the SDK's persisted telemetrydevice_idso subsequent events for the new customer carry a freshly-generated identifier (see the callout below for the full data flow). This step runs before the new customer record is created so the newdevice_idis in place for steps 8–12. - Create a new customer record in Marketing (a new
cookiesoft ID is generated). - Assign the previous push notification token to the new customer record.
- Preload in-app messages and app inbox for the new customer. In-app content block cache is cleared and the catalog is reloaded; placeholders listed in
inAppContentBlocksPlaceholdersare prefetched for the new anonymous customer. - Track a new
installationevent for the new customer. - Track a new session start if
automaticSessionTrackingis enabled.
You can also use the anonymize method to switch to a different integration. The SDK will then track events to a new customer record, similar to the first app session after installation on a new device.
Stream/JWT integrators
anonymize()creates a new anonymous customer profile. If your integration requires that every event is associated with an authenticated customer and valid JWT, usestopIntegration(completion:)on logout instead.stopIntegrationdoes not generate anonymous events.
Telemetrydevice_idbehavior onanonymize()The SDK's locally-stored telemetry
device_idis the same UUID that appears as thedevice_idproperty on tracked events (notification_state,installation,session_*, etc.) — it's the bridge between local SDK telemetry and backend analytics.By default,
anonymize()preserves thisdevice_idacross the call, so platform diagnostics keyed ondevice_id(for example, crash-rate dashboards) remain continuous through a sign-out + sign-in flow. The new customer profile carries the samedevice_idas the previous one.If your privacy requirements mean that the new profile can't be linked back to the previous customer through the device identifier, set
regenerateDeviceIdOnAnonymizetotruein yourConfiguration. The next event tracked afteranonymize()carries a freshly-generateddevice_id. The pre-anonymizenotification_state(valid=false, description="Invalidated")event (step 2 above) still carries the OLDdevice_idso the invalidation lands on the previous customer profile; all post-anonymize events carry the NEWdevice_id.The full-teardown alternative
stopIntegration()rotates thedevice_idunconditionally regardless of this flag.
Choose betweenanonymize()andstopIntegration()→configure()
Scenario Recommended method Reason The user signs out and may sign back in as a different user. anonymize()Creates a new anonymous profile. In Stream mode with a JWT, pending events are sent before local data is cleared. The user revokes personalized consent but keeps marketing consent. stopIntegration(), thenconfigure()in the completion blockTries to send pending events to the current profile, removes all local data, and restarts the SDK for anonymous marketing tracking. No old customer identifiers carry over. The user revokes all tracking consent. stopIntegration()(don't re-configure)Tries to send remaining events to the current profile, then stops all tracking and removes all local data. If your General Data Protection Regulation (GDPR) requirements require a clean break between the old and new profile, use
stopIntegration()followed byconfigure(). See Re-initialize the SDK after GDPR consent revocation for the full flow.
anonymize()sends pending events before it clears local data only in Stream mode, and only if a JWT or a JWT error handler is set. In Project mode, or in Stream mode without a JWT, the events stay in the queue. The SDK sends them later with the customer identifiers they were tracked with. If the flush fails in Stream mode, for example because the device is offline, the SDK sends the events without a JWT. A stream with signed-only permissions rejects them.stopIntegration()tries to send pending events to the current profile first and then removes all local data.
Overloads
| Method | Description |
|---|---|
anonymize() | Anonymize with current integration settings. |
anonymize(completion:) | Same as above, but calls completion on the main thread after flush + teardown are complete. Recommended for Stream mode so the host app knows when it is safe to proceed. |
anonymize(exponeaIntegrationType:exponeaProjectMapping:) | Anonymize and switch to a different integration (accepts both ExponeaProject and ExponeaIntegration). |
anonymize(exponeaIntegrationType:exponeaProjectMapping:completion:) | Anonymize and switch to a different integration (Project or Stream), then call completion on the main thread once flush + teardown are complete. The completion is particularly valuable in Stream mode (where the pre-anonymize flush is asynchronous when a JWT or error handler is set) and for wrapper SDKs that need to resolve their async bridge contract. Project-mode callers can use it too; the callback will simply fire almost immediately. |
anonymize(exponeaProject:projectMapping:)is deprecated. Useanonymize(exponeaIntegrationType:exponeaProjectMapping:)instead, which accepts anyExponeaIntegrationType(both Project and Stream).
Completion guarantee foranonymize(completion:)andanonymize(...completion:)When the SDK is configured and no stop is in progress, the completion-bearing
anonymizeoverloads invoke the callback on the main thread on the successful path. Public-API short-circuits that also invoke the callback are:
- SDK stopped via
stopIntegration- Prior internal exception
In those short-circuit cases, the SDK performs no anonymization — the callback signals only that the call resolved.
The SDK queues calls placed before
configure(...)finishes. If the deferred call succeeds, the SDK invokes the callback once configuration completes.Exponea.loggerlogs deferred failures — prior internal exception orNSExceptionduring deferred execution — which may not surface in the callback.A similar guarantee applies to
flushData(completion:). Public-API short-circuits that deliver aFlushResult.error(_:)carrying the underlyingExponeaErrorare:
- SDK stopped
- Prior internal exception
- Insufficient authorization
Pipeline short-circuits that deliver their typed
FlushResultcase are:
- No internet connection
- Flush already in progress
- Empty queue (returns
.success(0))Flutter, React Native, and similar wrapper SDKs that resolve a
PromiseorFutureinside the iOS callback can rely on this contract for post-configure paths.
Examples
Exponea.shared.anonymize()Anonymize with completion (recommended for Stream mode):
Exponea.shared.anonymize {
// Flush and teardown are complete, safe to re-configure or navigate
}Switch to a different Project:
Exponea.shared.anonymize(
exponeaIntegrationType: ExponeaProject(
baseUrl: "https://api.exponea.com",
projectToken: "YOUR PROJECT TOKEN",
authorization: .token("YOUR API KEY")
),
exponeaProjectMapping: nil
)Switch to a Stream integration:
Exponea.shared.anonymize(
exponeaIntegrationType: ExponeaIntegration(
baseUrl: "https://api.exponea.com",
streamId: "YOUR_STREAM_ID"
),
exponeaProjectMapping: nil
)Switch integration with completion (works for both Project and Stream mode; most useful in Stream mode and for wrapper SDKs that need to resolve a Promise/Future once the switch is done):
Exponea.shared.anonymize(
exponeaIntegrationType: ExponeaIntegration(
baseUrl: "https://api.exponea.com",
streamId: "YOUR_STREAM_ID"
),
exponeaProjectMapping: nil,
completion: {
// Pre-anonymize flush and teardown are complete, safe to re-configure or navigate
}
)Sessions
The SDK tracks sessions automatically by default, producing two events: session_start and session_end.
The session represents the actual time spent in the app. It starts when the application is launched and ends when it goes into the background. If the user returns to the app before the session times out, the application will continue the current session.
The default session timeout is 60 seconds. Set sessionTimeout in the Configuration for iOS SDK to specify a different timeout.
Track session manually
To disable automatic session tracking, set automaticSessionTracking to false in the Configuration for iOS SDK.
Use the trackSessionStart() and trackSessionEnd() methods to track sessions manually.
Examples
Exponea.shared.trackSessionStart()The default behavior for manually calling
Exponea.shared.trackSessionStart()multiple times can be controlled by themanualSessionAutoCloseflag in theConfiguration, which is set totrueby default. If a previous session is still open (i.e., it hasn’t been manually closed withExponea.shared.trackSessionEnd()) beforeExponea.shared.trackSessionStart()is called again, the SDK will automatically track asessionEndfor the previous session and then trigger a newsessionStartevent. To prevent this behavior, set themanualSessionAutoCloseflag in theConfigurationtofalse.
Exponea.shared.trackSessionEnd()Get the current customer cookie
Use Exponea.shared.customerCookie to retrieve the cookie that identifies the current customer being tracked. The value is available only after the SDK is initialized. Before initialization, the API returns nil.
By default, the SDK tracks events for an anonymous customer identified by a cookie. When you identify the customer with a hard ID, the SDK keeps using the same cookie alongside the hard ID. The cookie persists until you call:
Exponea.shared.anonymize()to generate a new cookie immediately.Exponea.shared.stopIntegration()orExponea.shared.clearLocalCustomerData(appGroup: String)to remove the cookie. A new one is created only on the next SDK initialization.
Use this cookie value to work with the current anonymous identity in your app, for example, to synchronize identity with a webview.
Example
let cookie = Exponea.shared.customerCookiePush notifications
If developers integrate push notification functionality in their app, the SDK automatically tracks the push notification token by default.
In the Configuration for iOS SDK, you can disable automatic push notification tracking by setting the Boolean value of the pushNotificationTracking property to false. It is then up to the developer to manually track push notifications.
The behavior of push notification tracking may be affected by the tracking consent feature, which in enabled mode requires explicit consent for tracking. Refer to the Tracking consent for iOS SDK documentation for details.
Track token manually
Use the trackPushToken() method to manually track the token for receiving push notifications. The token is assigned to the currently logged-in customer (with the identifyCustomer method).
Invoking this method will track a push token immediately regardless of the value of tokenTrackFrequency (refer to the Configuration for iOS SDK documentation for details).
Each time the app becomes active, the SDK invokes verifyPushStatusAndTrackPushToken, which re-evaluates the configured tokenTrackFrequency. Under everyLaunch, this produces up to one frequency-based notification_state per app process. Foreground transitions don't re-track unless push permission changed or another override applies. Other frequency modes track in one of the following situations:
- Their configured condition is met.
- An OS push authorization flip is detected. This always forces a fresh
notification_stateregardless of frequency.
Arguments
| Name | Type | Description |
|---|---|---|
| token (required) | String | String containing the push notification token. |
Example
Exponea.shared.trackPushToken("value-of-push-token")Remember to invoke anonymize whenever the user signs out to ensure the push notification token is removed from the user's customer profile. Failing to do this may cause multiple customer profiles share the same token, resulting in duplicate push notifications.
Track push notification delivery manually
Use the trackPushReceived() method to manually track push notification delivery.
You can pass either the notification data or the user info as argument.
Arguments
| Name | Type | Description |
|---|---|---|
| content (required) | UNNotificationContent | Notification data. |
or:
| Name | Type | Description |
|---|---|---|
| userInfo (required) | [AnyHashable: Any] | User info object from the notification data. |
Example
Passing notification data as argument:
func trackPushNotifReceived() {
let notifContent = UNMutableNotificationContent()
notifContent.title = "Example title"
// ... and anything you need, but only `userInfo` is required for tracking
notifContent.userInfo = [
"url": "https://example.com/ios",
"title": "iOS Title",
"action": "app",
"message": "iOS Message",
"image": "https://example.com/image.jpg",
"actions": [
["title": "Action 1", "action": "app", "url": "https://example.com/action1/ios"],
["title": "Action 2", "action": "browser", "url": "https://example.com/action2/ios"]
],
"sound": "default",
"aps": [
"alert": ["title": "iOS Alert Title", "body": "iOS Alert Body"],
"mutable-content": 1
],
"attributes": [
"event_type": "campaign",
"campaign_id": "123456",
"campaign_name": "iOS Campaign",
"action_id": 1,
"action_type": "mobile notification",
"action_name": "iOS Action",
"campaign_policy": "policy",
"consent_category": "General consent",
"subject": "iOS Subject",
"language": "en",
"platform": "ios",
"sent_timestamp": 1631234567.89,
"recipient": "[email protected]"
],
"url_params": ["param1": "value1", "param2": "value2"],
"source": "xnpe_platform",
"silent": false,
"has_tracking_consent": true,
"consent_category_tracking": "iOS Consent"
]
Exponea.shared.trackPushReceived(content: notifContent)
}Passing user info as argument:
func trackPushNotifReceived() {
let userInfo: [AnyHashable: Any] = [
"url": "https://example.com/ios",
"title": "iOS Title",
"action": "app",
"message": "iOS Message",
"image": "https://example.com/image.jpg",
"actions": [
["title": "Action 1", "action": "app", "url": "https://example.com/action1/ios"],
["title": "Action 2", "action": "browser", "url": "https://example.com/action2/ios"]
],
"sound": "default",
"aps": [
"alert": ["title": "iOS Alert Title", "body": "iOS Alert Body"],
"mutable-content": 1
],
"attributes": [
"event_type": "campaign",
"campaign_id": "123456",
"campaign_name": "iOS Campaign",
"action_id": 1,
"action_type": "mobile notification",
"action_name": "iOS Action",
"campaign_policy": "policy",
"consent_category": "General consent",
"subject": "iOS Subject",
"language": "en",
"platform": "ios",
"sent_timestamp": 1631234567.89,
"recipient": "[email protected]"
],
"url_params": ["param1": "value1", "param2": "value2"],
"source": "xnpe_platform",
"silent": false,
"has_tracking_consent": true,
"consent_category_tracking": "iOS Consent"
]
Exponea.shared.trackPushReceived(userInfo: userInfo)
}Track push notification click manually
Use the trackPushOpened() method to manually track push notification clicks.
Arguments
| Name | Type | Description |
|---|---|---|
| userInfo (required) | [AnyHashable: Any] | User info object from the notification data. |
Example
func trackPushNotifClick() {
let userInfo: [AnyHashable: Any] = [
"url": "https://example.com/ios",
"title": "iOS Title",
"action": "app",
"message": "iOS Message",
"image": "https://example.com/image.jpg",
"actions": [
["title": "Action 1", "action": "app", "url": "https://example.com/action1/ios"],
["title": "Action 2", "action": "browser", "url": "https://example.com/action2/ios"]
],
"sound": "default",
"aps": [
"alert": ["title": "iOS Alert Title", "body": "iOS Alert Body"],
"mutable-content": 1
],
"attributes": [
"event_type": "campaign",
"campaign_id": "123456",
"campaign_name": "iOS Campaign",
"action_id": 1,
"action_type": "mobile notification",
"action_name": "iOS Action",
"campaign_policy": "policy",
"consent_category": "General consent",
"subject": "iOS Subject",
"language": "en",
"platform": "ios",
"sent_timestamp": 1631234567.89,
"recipient": "[email protected]"
],
"url_params": ["param1": "value1", "param2": "value2"],
"source": "xnpe_platform",
"silent": false,
"has_tracking_consent": true,
"consent_category_tracking": "iOS Consent"
]
Exponea.shared.trackPushOpened(with: userInfo)
}Clear local customer data
Your application should always ask customers for consent to track their app usage. If the customer consents to tracking events at the application level but not at the personal data level, use stopIntegration() followed by configure(). anonymize() isn't sufficient in this case, because it can send events tracked before the call later, with the customer identifiers they were tracked with. See Re-initialize the SDK after GDPR consent revocation.
If the customer doesn't consent to any tracking, it's recommended not to initialize the SDK at all.
If the customer asks to delete personalized data, use the clearLocalCustomerData(appGroup: String) method to delete all information stored locally before SDK is initialized.
The customer may also revoke all tracking consent after the SDK is fully initialized and tracking is enabled. In this case, you can stop SDK integration and remove all locally stored data using the stopIntegration method.
Invoking this method will cause the SDK to:
- Remove the push notification token for the current customer from local device storage.
- Clear local repositories and caches, including all previously tracked events that haven't been flushed yet.
- Clear all session start and end information.
- Remove the customer record stored locally.
- Clear any previously loaded in-app messages, in-app content blocks, and app inbox messages.
- Clear the SDK configuration from the last invoked initialization.
- Clear the Stream JWT from the Keychain (if Stream integration was used).
- Stop handling of received push notifications.
- Stop tracking of deep links and universal links (your app's handling of them isn't affected).
Stop SDK integration
❗️ App group must be same for configuration and NotificationServices ❗️
- otherwise received push could be tracked
Your application should always ask the customer for consent to track their app usage. If the customer consents to tracking events at the application level but not at the personal data level, call stopIntegration(), then configure(). anonymize() isn't enough in this case. The SDK can still send events tracked before the call afterward, with the customer identifiers they were tracked with. For details, see Re-initialize the SDK after GDPR consent revocation.
If the customer doesn't consent to any tracking before the SDK is initialized, it's recommended that the SDK isn't initialized at all. For the case of deleting personalized data before SDK initialization, see more info in the usage of the clearLocalCustomerData method.
The customer may also revoke all tracking consent later, after the SDK is fully initialized and tracking is enabled. In this case, you can stop SDK integration and remove all locally stored data by using the Exponea.shared.stopIntegration() method.
Use the stopIntegration() method to stop the SDK. The SDK tries to send all pending data to the server and then deletes all information stored locally. If sending fails, for example because the device is offline, the SDK still deletes all local data. Events that weren't sent are lost.
Preferred for Stream/JWT modeUse
stopIntegrationinstead ofanonymize()when non-anonymous traffic is required (e.g. Stream JWT mode). Unlikeanonymize,stopIntegrationdoes not create a new anonymous customer profile.
When the SDK is running, invoking this method will cause the SDK to:
- Track a
session_endevent if automatic session tracking is enabled. (If you use manual session tracking, calltrackSessionEnd()beforestopIntegration.) - Invalidate the push notification token by tracking
notification_statewithvalid: false. - Try to send all pending events to the server (using the current JWT in Stream mode). If sending fails, the SDK continues with the next steps, and the events that weren't sent are lost.
- Clear the Stream JWT from the Keychain (Stream mode).
- Remove the push notification token for the current customer from local device storage.
- Clear local repositories and caches.
- Clear all session start and end information.
- Remove the customer record stored locally.
- Clear any in-app messages, in-app content blocks, and App Inbox messages previously loaded.
- Clear the SDK configuration from the last invoked initialization.
- Stop handling of received push notifications.
- Stop tracking of deep links and universal links (your app's handling of them is not affected).
- Stop and disable session tracking, event tracking, and flushing.
- Stop displaying in-app messages, in-app content blocks, and App Inbox UI. Already displayed messages are dismissed, and the default App Inbox button is hidden.
App Inbox button afterstopIntegration()
DefaultAppInboxProviderhides the cached App Inbox button when integration stops. This applies to host apps that keep a reference to the button returned bygetAppInboxButton(), such as React Native or SwiftUI wrappers.While the SDK is stopped,
getAppInboxButton()returns a hidden button. After you initialize the SDK again, the next call togetAppInboxButton()restores a visible button.If you extend
DefaultAppInboxProvider, callsuper.getAppInboxButton()to inherit this behavior. For a fully customAppInboxProvider, hide or remove the button in your ownstopIntegration()handling.The SDK clears
onIntegrationStoppedCallbacksafter they fire. To keep a custom callback across multiple stop and reinitialization cycles, register it again each time you initialize the SDK. The example below removes the button from the view hierarchy entirely, which is a stronger action than hiding it:
// Register during each SDK initialization.
IntegrationManager.shared.onIntegrationStoppedCallbacks.append { [weak self] in
self?.appInboxButton.removeFromSuperview()
self?.view.layoutIfNeeded()
}After invoking stopIntegration(), the SDK will drop any API method invocation until you initialize the SDK again.
stopIntegration(completion:)
stopIntegration(completion:)Use the completion variant to be notified when the stop process is complete. The completion block is called on the main thread. It doesn't confirm that pending data was sent. You may safely call Exponea.shared.configure(...) again inside the completion handler (e.g. for re-login flows).
Exponea.shared.stopIntegration {
// The SDK is stopped, the JWT is cleared, and all local data is removed.
// Safe to re-configure for a different user:
Exponea.shared.configure(
Exponea.StreamSettings(streamId: "NEW_STREAM_ID"),
pushNotificationTracking: .enabled(appGroup: "YOUR_APP_GROUP")
)
Exponea.shared.setSdkAuthToken("NEW_USER_JWT")
}Please validate dismiss behaviour if you customized the App Inbox UI layout.
Use cases
Correct usage of the stopIntegration() method depends on the use case, so consider all scenarios.
Stop the SDK but upload tracked data
stopIntegration() tries to send all pending events before clearing local data. If sending fails, for example because the device is offline, the SDK still clears local data. Events that weren't sent are lost.
To lower the risk of losing events, call flushData(completion:) first, and call stopIntegration() only if the result is .success:
Exponea.shared.flushData { result in
guard case .success = result else {
// The flush didn't run, for example because the device is offline
// or another flush is in progress. Retry later or decide whether to stop anyway.
return
}
Exponea.shared.stopIntegration {
// The SDK is stopped and all local data is cleared.
}
}
.successdoesn't guarantee that all events were sent
flushData(completion:)returns.success(N), whereNis the number of uploaded objects. It also returns.successwhen some or all uploads failed, and.success(0)when there was nothing to send. No public SDK API confirms that all events were sent. For details, see Completion guarantee.
stopIntegration()also tracks its own events:session_endif automatic session tracking is enabled, and anotification_stateevent that invalidates the push token. The SDK sends them only in its own best-effort flush, which runs after yourflushDatacall.
The completion block of stopIntegration() only confirms that the stop process is complete, not that the data was sent.
Stop the SDK and wipe all tracked data
The SDK caches data (such as sessions, events, and customer properties) in an internal local database and periodically sends them to the Marketing app. If the device has no network or if you configured the SDK to upload them less frequently, these data are kept locally.
You may face the use case where the customer gets removed from the Marketing platform, and subsequently, you want to remove them from local storage too.
Please do not initialize the SDK in this case. Depending on your configuration, the SDK may upload the stored tracked events. This may lead to the customer's profile being recreated in Marketing. Stored events may have been tracked for this customer, and uploading them will result in the recreation of the customer profile based on the assigned customer IDs.
To prevent this from happening, invoke stopIntegration() immediately without initializing the SDK:
Exponea.shared.stopIntegration()This results in all previously stored data being removed from the device. The next SDK initialization will be considered a fresh new start.
Stop the already running SDK
The method stopIntegration() can be invoked anytime on a configured and running SDK.
This can be used in case the customer previously consented to tracking but revoked their consent later. You may freely invoke stopIntegration() with immediate effect.
// User gave you permission to track
Exponea.shared.configure(...)
// Later, user decides to stop tracking
Exponea.shared.stopIntegration()This results in the SDK trying to send all pending events, then stopping all internal processes (such as session tracking and push notifications handling) and removing all locally stored data. Events that weren't sent are lost.
Re-initialize the SDK after GDPR consent revocation
A customer may revoke personalized consent but keep marketing consent, for example to still receive non-personalized push notifications. In this case, your app must:
- Try to send remaining events to the current profile, then clear all local data.
- Invalidate the push notification token on the old profile.
- Start a fresh SDK session for anonymous marketing-level tracking.
anonymize() isn't sufficient for this scenario because it doesn't always send pending events first. It does so only in Stream mode with a JWT or a JWT error handler. Otherwise, the events stay in the queue and the SDK sends them later with the customer identifiers they were tracked with. Instead, use stopIntegration(). It tries to send events to the current profile before removing local data, so the next configuration starts clean.
Use stopIntegration() followed by configure():
// Stop the SDK (tries to send pending events to the current profile, then removes all local data).
// Use the completion block to make sure configure() runs only after the stop completes.
Exponea.shared.stopIntegration {
// Check if the customer still has marketing consent
if userHasMarketingConsent {
// Configure the SDK again for anonymous tracking
Exponea.shared.configure(
Exponea.ProjectSettings(
projectToken: "YOUR PROJECT TOKEN",
authorization: .token("YOUR API KEY"),
baseUrl: "https://api.exponea.com"
),
pushNotificationTracking: .enabled(appGroup: "YOUR_APP_GROUP")
)
}
}This flow:
- Tries to send pending events to the current (old) customer profile before removing local data.
- Removes all local data, including the cached push token, the Stream JWT, in-app messages, in-app content blocks, segmentation data, App Inbox messages, and configuration.
- Generates a new
device_idandcookiewhen you configure the SDK again. - Registers for push notifications again in
configure(). If you set up push tracking in the standard way (automatic tracking orExponeaAppDelegate), the SDK then tracks the push token on the new anonymous profile. - Runs
configure()only after the stop process completes, because you call it inside the completion block.
The flush is best effortIf the flush fails, for example because the device is offline,
stopIntegration()still removes all local data. The SDK drops any pending events that weren't sent.If another flush is already in progress when you call
stopIntegration(), the SDK doesn't wait for it. This can be a periodic flush, or the flush that the default immediate flushing mode starts shortly after you track an event. The SDK removes local data right away, so thesession_endandnotification_stateevents thatstopIntegration()just tracked aren't sent. The completion block can also run before that earlier flush finishes. To lower this risk, flush the data first.
If a silent push notification triggers this flow, call stopIntegration() with the completion block in the silent push handler. Then call configure() inside the block, based on the customer's current consent status.
Customer denies tracking consent
It is recommended to ask the customer for tracking consent as soon as possible in your application. If the customer denies consent, please do not initialize the SDK at all.
❗️ Stop receiving push after stopIntegration()
You have to override the method in ExponeaAppDelegate
func userNotificationCenter(
_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
) {
super.userNotificationCenter(.....)
// your code if needed
}
}If you can't override this method and call super, make sure you add if to your method
if IntegrationManager.shared.isStopped && Exponea.isExponeaNotification(userInfo: notification.request.content.userInfo) {
Exponea.logger.log(.error, message: "Will present wont finish, SDK is stopping")
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [notification.request.identifier])
completionHandler([])
}Payments
The SDK tracks in-app purchases automatically.
Track payment
Use the trackPayment() method to track payments manually.
Arguments
| Name | Type | Description |
|---|---|---|
| properties | [String: JSONConvertible] | Dictionary of payment properties. |
| timestamp | Double | Unix timestamp specifying when the event was tracked. Specify the nil value to use the current time. |
Example
Exponea.shared.trackPayment(
properties: [
"productId": "123",
"currency": "USD",
"price": 123.45,
"quantity": 2
]
timestamp: nil
)Default properties
You can configure default properties to be tracked with every event. Note that the value of a default property will be overwritten if the tracking event has a property with the same key.
Refer to defaultProperties in the Configuration for iOS SDK documentation for details.
After initializing the SDK, you can change the default properties using the Exponea.shared.defaultProperties() method.
Updated 2 days ago

