# Swift SDK reference

> RelevaSDK for iOS at a glance: client and configuration presets, identity, tracking methods and the PushRequest builder, push token handling, navigation notifications, engagement events, inbox and on-screen views, and the errors to expect.

Reference for `RelevaSDK` 5.2.x (`https://github.com/Releva-ai/sdk-swift`). Setup walkthrough: [Connect your iOS app](https://releva.ai/documentation/integrations/ios-swift/connect-your-ios-app/).

## Client

```plaintext
import RelevaSDK
let client = RelevaClient(realm: "", accessToken: "<yourAccessToken>", config: RelevaConfig.full())
```

| Argument      | Value                                                                                                                                      |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `realm`       | `""` for `https://releva.ai`. A non-empty value becomes `https://<realm>.releva.ai`.                                                       |
| `accessToken` | The shop’s **Access Token** from **Settings › Shop & Integration › General**. Sent as `authorization: Bearer <accessToken>` on every call. |
| `config`      | A `RelevaConfig`; default `.full()`.                                                                                                       |

`RelevaClient` is `@MainActor`-isolated. The first instance becomes `RelevaClient.shared`. Methods that return a result or an error are `async throws`; the others are fire-and-forget and may still reach the network from a task the SDK starts.

### Configuration

| Preset              | tracking | screen tracking | push | analytics | debug logging |
| ------------------- | -------- | --------------- | ---- | --------- | ------------- |
| `.full()` (default) | on       | on              | on   | on        | off           |
| `.trackingOnly()`   | on       | on              | off  | on        | off           |
| `.pushOnly()`       | off      | off             | on   | off       | off           |
| `.minimal()`        | on       | off             | on   | off       | off           |
| `.debug()`          | on       | on              | on   | on        | on            |

Or build your own:

```plaintext
let config = RelevaConfig(
    enableTracking: true,
    enableScreenTracking: true,
    enablePushNotifications: true,
    enableAnalytics: true,
    enableDebugLogging: false,
    requestTimeoutInterval: 30.0,   // seconds
    maxRetryAttempts: 3,
    engagementBatchSize: 10,
    engagementBatchInterval: 30.0   // seconds
)
```

`enablePushNotifications` also creates the banner and story managers; with it off, `.relevaScrollTracking` and `reportScrollPercentage` are no-ops.

| Method                                | What it does                                                                    |
| ------------------------------------- | ------------------------------------------------------------------------------- |
| `setEndpointOverride(_ url: String?)` | Send everything to another base URL (local development).                        |
| `setAppVersion(_:)`                   | Reported in the device context; lets NPS surveys target by app version.         |
| `shutdown()`                          | Stops the client’s timers and token refresh. Call it before replacing a client. |

## Identity

| Method                                                                       | What it does                                                                                                                                                                                                       |
| ---------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `setDeviceId(_:)`                                                            | Required before any other call. `registerPushToken` throws `missingRequiredField` without it.                                                                                                                      |
| `setProfileId(_ id: String, _ skipMergeWithPreviousProfileId: Bool = false)` | Your customer id. The previous id is sent as `mergeProfileIds` unless the second argument is `true` (logout). When `pushTokenProvider` is set, a profile change re-registers the push token under the new profile. |

The SDK sends no e-mail, phone number, name or consent. Its `PrivacyInfo.xcprivacy` declares `NSPrivacyTracking` false and the collected data type `User ID`.

## Tracking

All methods call `POST /api/v0/push` and return a `RelevaResponse` with `recommenders`, `banners`, `stories` and the NPS survey.

| Method                                                     | Parameters                                                                                                                                                                                                                                  | Event written in Releva                                              |
| ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------- |
| `trackScreenView(screenToken:productIds:…)`                | `screenToken`, `productIds`, categories, filter, locale, currency                                                                                                                                                                           | **Viewed Page**, only when `screenToken` is a page token of the shop |
| `trackProductView(_ product: ViewedProduct, screenToken:)` | `ViewedProduct(id:)` with `.withStringField(key:values:)` and the other custom-field builders                                                                                                                                               | **Viewed Product**                                                   |
| `trackSearchView(query:…, screenToken:)`                   | `query`, result product ids, filter                                                                                                                                                                                                         | **Search**                                                           |
| `trackCheckoutSuccess(orderedCart:screenToken:)`           | `Cart(products:orderId:)` or `Cart.paid(_:orderId:)`                                                                                                                                                                                        | **Cart Checkout Completed**; the stored cart is cleared afterwards   |
| `trackCustomEvent(_ event: CustomEvent, screenToken:)`     | `CustomEvent(action:)` with `.withProduct`, `.withTag`, `.withCustomFields`                                                                                                                                                                 | The custom action you name                                           |
| `push(_ request: PushRequest)`                             | Anything the methods above do not cover, through the fluent `PushRequest` builder: `.screenView(token)`, `.productView(_:)`, `.search(_:)`, `.pageProductIds(_:)`, `.pageCategories(_:)`, `.pageFilter(_:)`, `.locale(_:)`, `.currency(_:)` | Depends on the request                                               |
| `setCart(_ cart: Cart)`                                    | `Cart(products:)` or `Cart.active(_:)`                                                                                                                                                                                                      | Cart events on a change after the first call                         |
| `setWishlist(_ products: [WishlistProduct])`               | `WishlistProduct(id:)`                                                                                                                                                                                                                      | Wishlist events on a change after the first call                     |
| `trackEvent(_ name: String)`                               | an app event name                                                                                                                                                                                                                           | Not sent; evaluated locally to trigger or cancel NPS surveys         |

`PushRequest` is a value type: every builder returns a new copy, so a part-built request can be reused as the base for several pushes, and a builder called as a bare statement throws its edit away. `CustomFields()` takes `.withStringField`, `.withNumericField` and `.withDateField` (native `Date`, serialised to ISO-8601). Filters: `NestedFilter.and(...)` / `.or(...)` of `SimpleFilter.priceRange(minPrice:maxPrice:)`, `SimpleFilter.brand(_:)` and the other simple filters.

The SDK sends no page URL, so URL-based targeting of banners and stories does not apply on iOS. A `screenToken` that is not a page token is accepted and writes nothing.

## Push

| Member                                                                               | What it does                                                                                                                                                                                                                                                                                                                                                                           |
| ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `enablePushEngagementTracking()`                                                     | Makes the SDK the `UNUserNotificationCenter` delegate and remembers the delegate installed before it. Releva pushes in the foreground are shown and tracked as `delivered`; taps are tracked as `opened`, navigation is posted, then the tap is forwarded. Non-Releva `willPresent`, every `didReceive` and `openSettingsFor` are forwarded to your delegate. Set your delegate first. |
| `pushTokenProvider: ((@escaping (String?) -> Void) -> Void)?`                        | A closure that fetches the current FCM token. With it set, the SDK re-registers on every foreground and profile change, skipping the upload when the token, profile and a registration younger than 24 hours are unchanged.                                                                                                                                                            |
| `registerPushToken(_ token: String, deviceType: DeviceType = .current) async throws` | `POST /api/v0/appPush/tokens` with `deviceType` `ios` (or `android`, `huawei`, `other`; only `android` and `ios` receive pushes). Sends an FCM token; `tokenType`, `bundleId` and `notificationStyle` are not sent.                                                                                                                                                                    |
| `isRelevaMessage(userInfo:)`                                                         | `true` for a Releva push payload.                                                                                                                                                                                                                                                                                                                                                      |
| `trackEngagement(userInfo:type:)`                                                    | Manual engagement tracking. Only needed when you do not call `enablePushEngagementTracking()`; with it, calling this for a tap double-counts.                                                                                                                                                                                                                                          |
| `consumePendingNavigation()`                                                         | Returns and clears a navigation the SDK posted before your observers existed (cold launch), as `name` and `userInfo` to re-post.                                                                                                                                                                                                                                                       |
| `InboxService.shared.handleSyncSignal()`                                             | Refresh the inbox for a silent `inbox_sync` push forwarded from `didReceiveRemoteNotification`.                                                                                                                                                                                                                                                                                        |

### Navigation notifications

| `Notification.Name`      | `userInfo`                                                                                      |
| ------------------------ | ----------------------------------------------------------------------------------------------- |
| `RelevaNavigateToScreen` | `screen` (the **Screen** name from **Mobile Targeting**), `parsedParameters` (the **KV Pairs**) |
| `RelevaNavigateToURL`    | `url` (`URL`); only your own schemes, `https://` is opened in Safari by the SDK                 |
| `RelevaNavigateToInbox`  | `parsedParameters` with `inboxMessageId`                                                        |

A push with **Main Screen** as target posts nothing.

### Engagement events

| Event       | When                                                          | How it is sent                                                             |
| ----------- | ------------------------------------------------------------- | -------------------------------------------------------------------------- |
| `delivered` | A Releva push is presented while the app is in the foreground | Batched: `engagementBatchSize` events or `engagementBatchInterval` seconds |
| `opened`    | The shopper taps the push                                     | Immediately                                                                |
| `clicked`   | The shopper taps the push’s button                            | Immediately                                                                |

Each event is a `GET` of the push’s `callbackUrl`, the click-tracking URL Releva puts in the payload. Releva counts the result as **PushNotification Click**.

### Push payload

Releva sends every visible iOS push with `aps.alert` and `mutable-content: 1`, so iOS draws it in the background and the Notification Service Extension can add the image and button. Data keys: `click_action` (`RELEVA_NOTIFICATION_CLICK` or `RELEVA_INBOX_SYNC`), `title`, `body`, `imageUrl`, `button`, `target`, `navigate_to_screen`, `navigate_to_url`, `navigate_to_parameters` (a JSON string), `inbox_sync`, `callbackUrl`. See [What a delivered push contains](https://releva.ai/documentation/reference/push-notifications/overview/#what-a-delivered-push-contains).

## App Inbox

`client.initializeInbox()` after `setProfileId`; then `client.inbox` (`InboxService.shared`): `state` (`messages`, `unreadCount`, `isLoading`, `hasMore`), `refresh()`, `loadMore()`, `markAsRead(_:)`, `markAllAsRead()`, `deleteMessage(_:)`, and `InboxMessageView(message:)` to render a message and report link taps. Setting a different profile id clears the cache and fetches the new shopper’s messages. Details and endpoints: [How the App Inbox works](https://releva.ai/documentation/learn/inbox/how-the-app-inbox-works/#using-the-sdks), [Inbox API overview](https://releva.ai/documentation/reference/inbox/overview/).

## On-screen content

| View modifier or call                                                                                                          | Purpose                                                                                                                         |
| ------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------- |
| `.bannerDisplay(client:targetSelector:onLinkTap:)`                                                                             | Draws the screen’s popup, flyout, bar and static banners                                                                        |
| `.storyDisplay(client:onLinkTap:)`                                                                                             | Draws stories                                                                                                                   |
| `.npsDisplay(onSubmit:)`                                                                                                       | Draws NPS surveys; call `client.submitNpsResponse(token:score:comment:)` in `onSubmit` (`POST /api/v0/nps/{token}/submissions`) |
| `.relevaScrollTracking(client)` on the content of a `ScrollView`, or `client.reportScrollPercentage(_:)` (0 to 100) from UIKit | Drives scroll-percentage triggers                                                                                               |

Banners reset on every screen view: tracking a screen again re-evaluates the triggers. Impressions, clicks and dismissals are reported automatically (`POST /api/v0/impressions`, `POST /api/v0/push/events`). The leave-intent trigger is web-only.

## Errors

| Where                  | Error                                                             | Cause                                                                                                                                  |
| ---------------------- | ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `registerPushToken`    | `missingRequiredField`                                            | `setDeviceId` not called                                                                                                               |
| `registerPushToken`    | HTTP `400` from the backend                                       | Messages in the [push notifications reference](https://releva.ai/documentation/reference/push-notifications/overview/#register-a-mobile-app-push-token) |
| Any call               | HTTP `402`                                                        | The shop is disabled                                                                                                                   |
| Log, `.debug()` config | `RelevaSDK: refreshPushToken skipped - pushTokenProvider not set` | Automatic re-registration is off because no provider is set                                                                            |

## Next steps

* [Connect your iOS app](https://releva.ai/documentation/integrations/ios-swift/connect-your-ios-app/): Set up the SDK step by step and check that data arrives.
* [Mobile SDKs overview](https://releva.ai/documentation/integrations/mobile/mobile-sdks-overview/): See what to set up in Releva and what has to come from your backend.
* [Push notifications API overview](https://releva.ai/documentation/reference/push-notifications/overview/): See the endpoints that register your app for push.
* [How product blocks work](https://releva.ai/documentation/learn/product-blocks/how-product-blocks-work/): Learn how page tokens connect product blocks to your screens.