# Connect your iOS app

> Add the Releva Swift SDK with Swift Package Manager, initialise the client with your Access Token, register the FCM token with a token provider, handle taps and silent inbox pushes, track screens with page tokens and check in Releva that data arrives.

`RelevaSDK` connects a native iOS app to Releva: screen and product tracking, product blocks, banners, stories, NPS surveys, app push through Firebase Cloud Messaging and the App Inbox. The code is cut down from Releva’s SwiftUI example app and the SDK’s README at version 5.2.1. The latest release is 5.2.1 (21 October 2026); see the [integrations changelog](https://releva.ai/documentation/changelog/integrations/) for what changed. Every method is listed in the [Swift SDK reference](https://releva.ai/documentation/integrations/ios-swift/sdk-reference/).

## Before you start

* iOS 15 or later, Swift 5.7 language mode or later. Xcode as required by the Firebase version Swift Package Manager resolves (the SDK accepts `firebase-ios-sdk` 11.15.0 up to, not including, 13.0.0; pin `"11.15.0"..<"12.0.0"` to stay on an older Xcode).
* Your shop’s **Access Token** from **Settings › Shop & Integration › General**: [Find your Access Token and Secret Key](https://releva.ai/documentation/guides/shop-settings/find-your-api-keys/). Never put the **Secret Key** in the app.
* One page token per screen you want to track or personalise, from the **Token:** bar on **Personalization › Product Blocks**: [Pages and tokens](https://releva.ai/documentation/learn/product-blocks/how-product-blocks-work/#pages-and-tokens).
* For push: a Firebase project with `GoogleService-Info.plist`, and its service account uploaded in Releva: [Add your Firebase credentials for app push](https://releva.ai/documentation/integrations/mobile/add-firebase-credentials-for-app-push/). The Swift SDK registers FCM tokens, so **iOS APNs environment** does not apply to it.

## Install

Swift Package Manager is the only distribution channel. The package has two products: `RelevaSDK` for the app target and `RelevaNotificationExtension` for a Notification Service Extension (images and buttons on pushes).

In Xcode: **File › Add Package Dependencies…**, enter `https://github.com/Releva-ai/sdk-swift.git` with **Up to Next Major Version** from `5.2.1`, and add `RelevaSDK` to your app target. Then add `https://github.com/firebase/firebase-ios-sdk.git` as a second package and add its `FirebaseMessaging` and `FirebaseCore` products to the app target: Firebase is a dependency of the SDK, but Swift Package Manager only lets your code use products from packages your own project declares, and the push setup below calls `Messaging.messaging()`.

In a `Package.swift`:

```plaintext
dependencies: [
    .package(url: "https://github.com/Releva-ai/sdk-swift.git", from: "5.2.1"),
    .package(url: "https://github.com/firebase/firebase-ios-sdk.git", "11.15.0"..<"13.0.0")
],
targets: [
    .target(name: "YourApp", dependencies: [
        .product(name: "RelevaSDK", package: "sdk-swift"),
        .product(name: "FirebaseMessaging", package: "firebase-ios-sdk"),
        .product(name: "FirebaseCore", package: "firebase-ios-sdk")
    ])
]
```

Add `GoogleService-Info.plist` to the app target and call `FirebaseApp.configure()` at launch, as in the standard Firebase setup. For push, add the **Push Notifications** capability and **Background Modes › Remote notifications** under **Signing & Capabilities**.

## Configure

### 1. App delegate: client, delegate order, token provider, permission

```plaintext
import SwiftUI
import FirebaseCore
import FirebaseMessaging
import RelevaSDK


class AppDelegate: NSObject, UIApplicationDelegate, MessagingDelegate {
    static var relevaClient: RelevaClient?


    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool {
        FirebaseApp.configure()


        // realm: "" unless Releva gives you one. accessToken: Settings › Shop & Integration › General.
        let client = RelevaClient(realm: "", accessToken: "<yourAccessToken>")
        client.setDeviceId(deviceId)          // a UUID you store on first launch
        client.setProfileId("DEMO-1001")      // after login; before that, your own anonymous id


        // If your app has its own UNUserNotificationCenterDelegate, set it BEFORE this call:
        // the SDK takes the delegate slot and forwards what it does not own.
        client.enablePushEngagementTracking()


        // Lets the SDK re-upload the current FCM token on every foreground and profile change.
        client.pushTokenProvider = { completion in
            Messaging.messaging().token { token, _ in completion(token) }
        }
        client.initializeInbox()
        AppDelegate.relevaClient = client


        Messaging.messaging().delegate = self
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, _ in
            if granted {
                DispatchQueue.main.async { application.registerForRemoteNotifications() }
            }
        }
        return true
    }


    func application(_ application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        // Only needed when Firebase method swizzling is off (FirebaseAppDelegateProxyEnabled = NO).
        Messaging.messaging().apnsToken = deviceToken
        registerPushToken()
    }


    func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
        registerPushToken()
    }


    private func registerPushToken() {
        Task {
            do {
                let fcmToken = try await Messaging.messaging().token()
                try await AppDelegate.relevaClient?.registerPushToken(fcmToken, deviceType: .ios)
            } catch {
                print("Push token registration failed: \(error.localizedDescription)")
            }
        }
    }
}
```

`RelevaClient` is `@MainActor`; the first instance you create becomes `RelevaClient.shared`. Methods that return a result or an error are `async throws`; the rest are fire-and-forget. With `pushTokenProvider` set, the SDK fetches and re-registers the token on every foreground and whenever the profile id changes, skipping the upload when the token, profile and a registration younger than 24 hours are unchanged. Without it the stored token drifts stale and pushes fail with “device token expired”.

Do not add a `userNotificationCenter(_:didReceive:)` that calls `trackEngagement(..., type: .opened)` for Releva pushes: since 5.2.1 the SDK tracks and forwards every tap itself, and such a handler counts each tap twice. If your delegate routes every tap generically, skip Releva’s with `client.isRelevaMessage(userInfo:)`.

If your app keeps its own `UNUserNotificationCenterDelegate`, or calls `enablePushEngagementTracking()` after `application(_:didFinishLaunchingWithOptions:)` returns, use SDK 5.3.0 or later and pass each tap to `client.handleNotificationResponse(response)` in `userNotificationCenter(_:didReceive:withCompletionHandler:)`. The SDK tracks and routes the tap once and returns `false` for a push that is not Releva’s, so you can route your own. Without it, the SDK does not see those taps (for a late start, the tap that launches a closed app), so they are not tracked and do not navigate.

### 2. Silent inbox-sync pushes

The SDK handles `inbox_sync` pushes only on the tap path. Forward the silent ones yourself:

```plaintext
func application(_ application: UIApplication,
                 didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    Messaging.messaging().appDidReceiveMessage(userInfo)   // only when swizzling is off


    let isInboxSync = (userInfo["inbox_sync"] as? String) == "true"
        || (userInfo["click_action"] as? String) == "RELEVA_INBOX_SYNC"
    if isInboxSync {
        InboxService.shared.handleSyncSignal()
    }
    completionHandler(.newData)
}
```

The example app waits for the refresh to finish before calling the completion handler, so iOS does not suspend the app mid-request.

### 3. Rich notifications (images, buttons)

Add a Notification Service Extension target (**File › New › Target › Notification Service Extension**), add the `RelevaNotificationExtension` product to it and replace the generated class:

```plaintext
import UserNotifications
import RelevaNotificationExtension


class NotificationService: RelevaNotificationServiceExtension {
    // No code needed. The SDK handles the rich notification.
}
```

### 4. Navigate from a tap

The SDK posts a `NotificationCenter` notification; your app navigates:

```plaintext
NotificationCenter.default.addObserver(forName: Notification.Name("RelevaNavigateToScreen"), object: nil, queue: .main) { note in
    guard let screen = note.userInfo?["screen"] as? String else { return }
    let parameters = note.userInfo?["parsedParameters"] as? [String: Any]   // KV Pairs from the push form
    // route to `screen`
}
NotificationCenter.default.addObserver(forName: Notification.Name("RelevaNavigateToURL"), object: nil, queue: .main) { note in
    guard let url = note.userInfo?["url"] as? URL else { return }           // your own schemes only
    // handle the deep link
}
NotificationCenter.default.addObserver(forName: Notification.Name("RelevaNavigateToInbox"), object: nil, queue: .main) { note in
    let parameters = note.userInfo?["parsedParameters"] as? [String: Any]
    let inboxMessageId = parameters?["inboxMessageId"]
    // open the inbox, optionally that message
}


// After the observers exist: replay a tap the SDK handled during a cold launch.
if let pending = AppDelegate.relevaClient?.consumePendingNavigation() {
    NotificationCenter.default.post(name: pending.name, object: nil, userInfo: pending.userInfo)
}
```

`screen` is the **Screen** name and `parsedParameters` the **KV Pairs** set under **Mobile Targeting** on the push’s **Behavior** tab. `https://` links are opened in Safari by the SDK; only your own schemes post `RelevaNavigateToURL`.

### 5. Track screens with page tokens

```plaintext
// Screen view with the page token from Personalization › Product Blocks
let response = try await client.trackScreenView(screenToken: "<homePageToken>")


// Cart and wishlist are stateful: set them and the SDK syncs the changes
let product = CartProduct(id: "DEMO-1001", price: 29.99, quantity: 1,
                          custom: CustomFields().withStringField(key: "size", values: ["M"]))
client.setCart(Cart(products: [product]))
client.setWishlist([WishlistProduct(id: "DEMO-1002")])


// Order placed in the app
try await client.trackCheckoutSuccess(orderedCart: Cart(products: [product], orderId: "DEMO-ORDER-1001"))
```

A screen sent without a page token, or with a token Releva does not know, is accepted but records no page view and returns no banners or stories. The SDK sends no page URL, so URL-based targeting of banners and stories does not apply on iOS; target by page token or segment.

Banners, stories and NPS attach to SwiftUI views with `.bannerDisplay(client:targetSelector:onLinkTap:)`, `.storyDisplay(client:onLinkTap:)` and `.npsDisplay(onSubmit:)`. Scroll triggers need `.relevaScrollTracking(client)` on the content of the `ScrollView` (or `client.reportScrollPercentage(_:)` from UIKit). See the [SDK reference](https://releva.ai/documentation/integrations/ios-swift/sdk-reference/#on-screen-content).

### 6. Logout

```plaintext
client.setProfileId(UUID().uuidString, true)   // fresh anonymous id, no merge
// With pushTokenProvider set, the SDK re-registers the token under the new profile by itself.
// If you build a new client instead, call oldClient.shutdown() first, or the old one keeps
// re-registering the token under the previous profile on every foreground.
```

## Verify

Run the app, accept the notification permission and open a screen with a page token. Then follow [Check that your mobile app is connected](https://releva.ai/documentation/integrations/mobile/check-that-your-mobile-app-is-connected/). With `RelevaConfig.debug()` the SDK logs `RelevaSDK: ✓ Successfully registered push token for ios` after a successful registration.

## Troubleshooting

**Taps are counted twice.** Your app also calls `trackEngagement(userInfo:type: .opened)` in `didReceive`. Remove it; the SDK tracks taps since 5.2.1.

**Your own notifications stopped showing or their taps no longer reach your delegate.** Your `UNUserNotificationCenterDelegate` was set after `enablePushEngagementTracking()`. Set it first; the SDK forwards `willPresent` for non-Releva notifications, `didReceive` for every tap and `openSettingsFor` always.

**Pushes stop after some days with “device token expired”.** `pushTokenProvider` is not set, so the rotated FCM token was never re-registered.

**A tap on a cold launch navigates nowhere.** The observers were registered after the SDK posted the navigation. Call `consumePendingNavigation()` once the observers exist.

**The inbox does not update until the app is reopened.** Silent `inbox_sync` pushes are not forwarded to `InboxService.shared.handleSyncSignal()`, or **Background Modes › Remote notifications** is off.

**No banners, stories or product blocks, and no Viewed Page event.** The `screenToken` is not a page token. Copy it from **Personalization › Product Blocks**.

**`registerPushToken` throws `missingRequiredField`.** `setDeviceId` has not run.

**`Messaging.messaging().token()` fails or the token never arrives.** Firebase is not configured, the APNs key is not uploaded to the Firebase project, or swizzling is off and `Messaging.messaging().apnsToken` is not set in `didRegisterForRemoteNotificationsWithDeviceToken`.

## What syncs

| Data                                                                        | Endpoint                                                                                       | When the SDK calls it                                                                                                                                                                                                                                                                           |
| --------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Screen, product, search views; custom events; cart, wishlist; checkout      | `POST /api/v0/push`                                                                            | `trackScreenView`, `trackProductView`, `trackSearchView`, `trackCustomEvent`, `trackCheckoutSuccess`, `push(_:)`; `setCart`/`setWishlist` on a change after the first call. Sends `deviceId`, `profile.id`, `sessionId`, `mergeProfileIds`, the page token, the cart and wishlist; no page URL. |
| App push token                                                              | `POST /api/v0/appPush/tokens`                                                                  | `registerPushToken(_:deviceType:)`, and automatically on every foreground and profile change when `pushTokenProvider` is set. FCM tokens only. Writes a **Push Notification Subscribe** event each time.                                                                                        |
| Push engagement                                                             | `GET <callbackUrl>` from the push data                                                         | `opened` and `clicked` immediately on a tap; `delivered` batched (10 events or 30 s) when a push is presented in the foreground.                                                                                                                                                                |
| Banner impressions and actions, story actions                               | `POST /api/v0/impressions`, `POST /api/v0/push/events`                                         | When banners and stories are shown and used.                                                                                                                                                                                                                                                    |
| NPS answer                                                                  | `POST /api/v0/nps/{token}/submissions`                                                         | `submitNpsResponse`.                                                                                                                                                                                                                                                                            |
| App Inbox                                                                   | `GET /api/v0/inbox/messages`, `GET /api/v0/inbox/unread-count`, read, read-all, delete, action | `initializeInbox()`, `handleSyncSignal()`, resume with a cache older than 5 minutes, and the `client.inbox` methods.                                                                                                                                                                            |
| Products, orders paid outside the app, refunds, profile attributes, consent | not sent by the SDK                                                                            | Your backend: see [What your backend still sends](https://releva.ai/documentation/integrations/mobile/mobile-sdks-overview/#what-your-backend-still-sends).                                                                                                                                                      |

The SDK sends no e-mail, phone number, name or consent. Its privacy manifest declares no tracking and the collected data type `User ID`.

## Next steps

* [Swift SDK reference](https://releva.ai/documentation/integrations/ios-swift/sdk-reference/): Look up every client, tracking, push, inbox and on-screen method and the errors to expect.
* [Add your Firebase credentials for app push](https://releva.ai/documentation/integrations/mobile/add-firebase-credentials-for-app-push/): Upload the Firebase service account Releva sends iOS push through and set the APNs environment.
* [Check that your mobile app is connected](https://releva.ai/documentation/integrations/mobile/check-that-your-mobile-app-is-connected/): Confirm that push token registrations arrive and the profile shows App push Subscribed.
* [How the App Inbox works](https://releva.ai/documentation/learn/inbox/how-the-app-inbox-works/): Learn how inbox messages differ from push, when they expire and how the app keeps them in sync.