AlgorithmX
Integrations25 min read

iOS Integration

Add AlgorithmX to your iOS app step by step: install the SDK, start it, identify customers, send events, connect push notifications, and open the right screen from campaigns.

SDK 1.1.0: these APIs use SDK-generated anonymous/device IDs and API-based in-app delivery. Existing 1.0.x integrations should follow the updated identity and profile instructions below.

This guide adds the AlgorithmX SDK to your iOS app in 9 steps. You keep your app's login, push setup, and navigation. You only add a few lines in places your app already has.

In the examples, names such as AppRouter and AlgorithmXRouting are your own code, not part of the SDK. Every SDK call goes through AlgorithmX.shared:

swift
import AlgorithmXSDK

Work through the basic integration first: start the SDK, recognize one test customer, send one event, and display an API-based in-app campaign or deliver a plain notification. Save the optional service extension for when you need images, buttons, or delivery reports. Each checkpoint tells you which part is working.

Before you start

Check that you have these:

  • An app with iOS 15 or later, built with Xcode 15 or later.
  • The API base URL from AlgorithmX, for example https://api.example.com.
  • Your partner ID from AlgorithmX, for example your-partner-id. The SDK sends it with every SDK API request.
  • The list of customer ID, events, deep links, and custom actions you agreed on with AlgorithmX. See the overview.

Prepare Firebase and your Apple Developer account

AlgorithmX sends through FCM on iOS. Firebase then delivers through Apple's APNs service. Register your bundle ID in Firebase, add its matching GoogleService-Info.plist to the app target, and install FirebaseCore and FirebaseMessaging using Firebase's iOS setup. Choose a Firebase SDK version compatible with your Xcode and deployment target; AlgorithmX does not install Firebase for you.

  1. Push Notifications is turned on for your app (Xcode, target, Signing & Capabilities).
  2. Background Modes, Remote notifications is turned on for your app target. Enable this for background push processing; API-based in-app views work without it.
  3. APNs authentication in Firebase. Upload your Apple .p8 key, Key ID, and Team ID under Project settings → Cloud Messaging → Apple app configuration → APNs Authentication Key. Select the matching app and development/production environment. These credentials belong in Firebase, not AlgorithmX or the app bundle.
  4. App Group (optional): only needed for delivery reports in step 9.

Keep each file in the right place

WhatExampleWhere to find it
iOS Firebase configurationGoogleService-Info.plistDownload for the exact bundle ID and add it to the app target in Xcode.
APNs key, Key ID, Team IDAuthKey_ABC123DEFG.p8Apple Developer account → Firebase Cloud Messaging settings.
Firebase service-account JSONA private key generated under Service accountsUpload in AlgorithmX Settings → In-App Integration. One upload covers iOS and Android apps in that project.
Build environmentDevelopment install or TestFlight/App StoreCheck the signed app's aps-environment entitlement and configure the matching APNs entry in Firebase.

Follow Connect Firebase and Send a Test for the shared dashboard setup. If you already send directly through APNs, keep that sender and its callbacks; add Firebase to obtain the FCM token that AlgorithmX uses.

The steps

StepWhat you doWhere
1Install the SDKXcode or your Podfile
2Start the SDKYour AppDelegate
3Tell AlgorithmX who the customer isLogin, app start, logout
4Send eventsWhere actions happen, such as checkout
5Connect push notificationsYour AppDelegate
6Open the right screenYour navigation code
7Check in-app campaignsNo code
8TestA real iPhone
9Images, buttons, and delivery reports (optional)A notification service extension

Step 1: Install the SDK

This step makes the library available to your app. Finish the build check before adding customer or push code, so a dependency problem is easy to isolate.

Choose one of these two ways.

Swift Package Manager

  1. In Xcode, choose File, then Add Package Dependencies.

  2. Paste this URL:

    Code
    https://github.com/algorithmx-cloud/algorithmx-ios-sdk
    
  3. Choose Up to Next Major Version from 1.1.0.

  4. Add the AlgorithmXSDK product to your app target. If you plan to do step 9, add it to your notification service extension too.

If your project uses a Package.swift file, add this instead:

swift
.package(url: "https://github.com/algorithmx-cloud/algorithmx-ios-sdk", from: "1.1.0")

CocoaPods

Add this line to your app target in the Podfile, then run pod install:

ruby
target 'YourApp' do
  pod 'AlgorithmXSDK', :git => 'https://github.com/algorithmx-cloud/algorithmx-ios-sdk.git', :tag => '1.1.0'
end

The pod is installed from GitHub, because the public CocoaPods registry stops accepting new pods on December 2, 2026. With CocoaPods, do not add the pod to your notification service extension; step 9 explains what to do instead.

Check: import AlgorithmXSDK builds without errors.

The SDK has no other dependencies. To update later, change the version.

Step 2: Start the SDK

Add these lines to application(_:didFinishLaunchingWithOptions:) in your AppDelegate. Keep your existing code.

swift
import AlgorithmXSDK
import FirebaseCore
import FirebaseMessaging
import UIKit
import UserNotifications

final class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate, MessagingDelegate {

    // Your handlers from step 6. Keep this property: the SDK does not keep them alive.
    private let algorithmXRouting = AlgorithmXRouting()

    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
    ) -> Bool {
        // Keep your existing startup code.

        AlgorithmX.shared.initialize(apiBaseUrl: "https://api.example.com", partnerId: "your-partner-id")
        #if DEBUG
        AlgorithmX.shared.setLoggingEnabled(true)
        #endif

        AlgorithmX.shared.notificationClickListener = algorithmXRouting
        AlgorithmX.shared.deepLinkHandler = algorithmXRouting
        AlgorithmX.shared.actionButtonHandler = algorithmXRouting

        if FirebaseApp.app() == nil { FirebaseApp.configure() }
        Messaging.messaging().delegate = self
        UNUserNotificationCenter.current().delegate = self // Keep yours if you already set it.
        application.registerForRemoteNotifications() // On every launch.
        return true
    }
}

Why in the AppDelegate and not on the first screen? iOS can start your app in the background to deliver a campaign. No screen appears then, but this method still runs. SDK calls made before initialize are ignored.

Important: keep your handlers alive. The SDK holds your handlers weakly. Store them in a property of the AppDelegate, as above. If you write AlgorithmX.shared.deepLinkHandler = MyHandler(), the object disappears at once and taps do nothing.

  • App Group (step 9 only): use AlgorithmX.shared.initialize(apiBaseUrl: "https://api.example.com", partnerId: "your-partner-id", appGroup: "group.com.example.shop").
  • SwiftUI apps: connect the AppDelegate with an adaptor, if you do not have one yet:
swift
@main
struct ShopApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    var body: some Scene { WindowGroup { RootView() } }
}

Check: run a debug build. The Xcode console shows the SDK's requests.

Step 3: Tell AlgorithmX who the customer is

The SDK generates and stores an anonymous UUID and a separate installation device UUID during startup. You do not generate either ID or call the bootstrap endpoint yourself. The anonymous UUID stays the same across app restarts and login; events continue to use it in X-Anonymous-Id.

Use the stable account ID from your application's backend when the customer signs in. The SDK sends it as ExternalId, allowing AlgorithmX to resolve the same customer across devices. AlgorithmX manages its own internal profile ID.

Call the identity function after login and when starting with a signed-in customer. Email and phone become trusted identifiers; supported profile fields are sent separately to /Customer/Ingest.

swift
AlgorithmX.shared.identifyUser(userId: "customer_123", attributes: [
    "email": "[email protected]",
    "firstName": "Amina", "lastName": "Hassan",
    "emailOptIn": true, "smsOptIn": false, "pushOptIn": true,
    "gdprAccepted": true, "whatsAppOptIn": false
])

Supported identifier fields are email, phone, and userName; your application's userId becomes ExternalId. Supported profile fields are firstName, lastName, gender, dateOfBirth, registeredAt, emailOptIn, smsOptIn, pushOptIn, gdprAccepted, and whatsAppOptIn. Send dates as ISO 8601 text and consent fields as booleans.

Send a complete profile. /Customer/Ingest replaces these traits: omitted text/date fields are cleared and omitted consent fields become false. Include all current values whenever you send profile fields through identify / identifyUser or setUserProfile. An identify call containing only identifiers does not send a profile update.

Fields such as plan, language, country, and loyaltyTier are not supported customer traits by these endpoints. The SDK rejects unsupported fields. Send arbitrary business data with trackEvent; that records event data and does not create custom profile fields.

To update profile fields later, pass profile, your application's complete current customer profile object, without email, phone, or userName:

swift
AlgorithmX.shared.setUserProfile(profile)

On logout:

swift
AlgorithmX.shared.resetIdentity()

Logout clears waiting campaigns, generates a fresh anonymous UUID and bootstraps a new anonymous profile. The installation's device UUID is retained. Calling identify with a different account ID also rotates the anonymous UUID first, preventing the two accounts from being merged. Close any campaign already on screen as part of your app's logout flow.

To inspect the SDK-generated UUID for diagnostics:

swift
let anonymousId = AlgorithmX.shared.getAnonymousId()

The SDK remembers the external account ID across restarts. These calls do not replace your application's authentication. API requests are sent in order, but the backend responds with 202 Accepted and processes messages asynchronously; confirm the stored customer data in AlgorithmX. Offline event/profile requests are dropped. Bootstrap and saved account identification are attempted again on startup/foreground; profile updates must be sent again by your app if delivery failed.

Check: the customer can be found using the external ID/email you supplied, and the anonymous UUID is unchanged after login. After logout or switching accounts, it changes.

Step 4: Send events

Choose one action you can easily repeat while testing, such as opening a product. Confirm its event arrives before adding all your business events. The campaign team will use these names and details, so agree on them together.

Send an event right after an action succeeds, for example after an order is confirmed. Put it next to your existing analytics calls.

swift
AlgorithmX.shared.trackEvent("productView", properties: ["productId": "SKU-123"])

AlgorithmX.shared.trackEvent("addToCart", properties: ["productId": "SKU-123", "quantity": 2])

AlgorithmX.shared.trackEvent("purchase", properties: [
    "orderId": "ORDER-1001",
    "total": 149.90,
    "currency": "SAR",
    "items": [["productId": "SKU-123", "quantity": 2]]
])

Important: only use these value types: String, Int, Double, Bool, and arrays or dictionaries of them. Any other value, such as a Date, a URL, your own type, or Double.nan, crashes the app. Turn dates into a timestamp or an ISO 8601 string first, and leave out empty optional values.

Other rules:

  • Names and keys: use AlgorithmX's camelCase naming approach, such as addToCart and productId. Custom names and keys are sent as supplied; their casing is not enforced or normalized.
  • Offline: an event sent without internet is lost. It is not sent again later. Keep your own backend as the record of orders and payments.
  • Past data: only new events are sent. To bring in older data, ask your AlgorithmX contact about a data import.

Check: the event appears for the customer in AlgorithmX.

Step 5: Connect push notifications

This step gives AlgorithmX the phone's push address and a way to process its messages. Treat token registration and message delivery as separate checks: receiving a token does not by itself prove that a push can reach the app.

You keep your push setup. You add two things to your AppDelegate.

5a. Send the FCM token

Keep the Firebase configuration and MessagingDelegate from step 2. In the Apple callback, map the APNs token to Firebase, then request the current FCM token. Send refreshed FCM tokens through the messaging delegate too:

swift
func application(
    _ application: UIApplication,
    didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
    Messaging.messaging().apnsToken = deviceToken
    Messaging.messaging().token { token, error in
        if let error = error {
            print("FCM token registration failed: \(error.localizedDescription)")
            return
        }
        if let token = token, !token.isEmpty {
            AlgorithmX.shared.registerDeviceToken(token)
        }
    }
    // Keep any APNs forwarding required by your existing sender.
}

func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String?) {
    guard let token = fcmToken, !token.isEmpty else { return }
    AlgorithmX.shared.registerDeviceToken(token)
}
  • Send the FCM registration token to AlgorithmX. The hexadecimal APNs token is for Firebase or your existing direct APNs sender.
  • Register the current FCM token on every launch and whenever Firebase refreshes it. Step 2 registers with Apple each launch so the mapping and current-token request run again.
  • Merge this code into your existing Firebase messaging delegate if you already have one; do not replace a delegate another integration depends on. This example maps the Apple token explicitly, including when Firebase method swizzling is disabled.
  • Keep your app's own permission prompt for visible alerts. AlgorithmX never asks for notification permission.

Check: the app has a non-empty FCM token, and the SDK sends that value to AlgorithmX. Keep token output in development diagnostics only. A token alone does not confirm that Firebase has valid APNs credentials.

5b. Pass AlgorithmX notifications to the SDK

Add an AlgorithmX check at the top of these three methods. Other notifications continue through your existing code.

swift
// 1. Background notifications. API-based in-app campaigns do not depend on this callback.
func application(
    _ application: UIApplication,
    didReceiveRemoteNotification userInfo: [AnyHashable: Any],
    fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
) {
    if AlgorithmX.shared.isAlgorithmXPush(userInfo: userInfo) {
        AlgorithmX.shared.handleNotification(userInfo: userInfo) {
            completionHandler(.newData)
        }
        return
    }
    // Your existing code. It must call completionHandler once.
}

// 2. A notification arrives while the app is open.
func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    willPresent notification: UNNotification,
    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
) {
    let userInfo = notification.request.content.userInfo
    if AlgorithmX.shared.isAlgorithmXPush(userInfo: userInfo) {
        AlgorithmX.shared.handleNotification(userInfo: userInfo) {
            completionHandler([.banner, .list, .sound]) // Show it as a banner.
        }
        return
    }
    // Your existing code.
}

// 3. The customer taps a notification or one of its buttons.
func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    didReceive response: UNNotificationResponse,
    withCompletionHandler completionHandler: @escaping () -> Void
) {
    let userInfo = response.notification.request.content.userInfo
    if AlgorithmX.shared.isAlgorithmXPush(userInfo: userInfo) {
        AlgorithmX.shared.handleNotificationResponse(
            actionIdentifier: response.actionIdentifier,
            userInfo: userInfo,
            completionHandler: completionHandler
        )
        return
    }
    // Your existing code.
}

Good to know:

  • The SDK calls each completionHandler for you, once.
  • Set the notification delegate inside didFinishLaunchingWithOptions, as in step 2. If you set it later, a tap that starts the app is lost.
  • If another library, such as Firebase, takes over your notification delegate, send a real AlgorithmX notification while testing to check that these lines still run.
  • Taps that start the app: the SDK calls your handlers right after launch, maybe before your first screen is ready. Your router should remember the destination and open it when the app is ready.

Check: use the dashboard test form with this app's FCM token, first with the app in the background. Then send an AlgorithmX campaign to verify the ownership checks and action callbacks. A plain dashboard test has no campaign action payload.

Step 6: Open the right screen when a customer taps

Think of a campaign action as a destination request. The SDK tells your app where the customer wants to go, and your existing router decides how to open that screen. Agree on the supported destinations before your campaign team uses them.

A campaign can do one of four things when the customer taps it. Two of them need your code:

The campaign saysWhat happensYour code
Open a screen (deep link)The SDK gives the link to your handler.Step 6a
Custom actionThe SDK gives the action name and its details to your handler.Step 6b
Open a web pageThe SDK opens it in Safari.None
Open an in-app campaignThe SDK shows it over your app.None

Put all your handlers in one class. This is the AlgorithmXRouting object from step 2:

swift
import AlgorithmXSDK

final class AlgorithmXRouting: NSObject, NotificationClickListener, DeepLinkHandler, ActionButtonHandler {

    func onDeepLinkReceived(url: URL) -> Bool {
        AppRouter.shared.open(url) // Your existing router.
    }

    // The methods from 6b and 6c go here too.
}
  • Return true if your app accepts the link (also when it first waits for login), false if not.
  • The SDK never opens the link by itself. If you set no handler, nothing happens.
  • You do not need a new URL scheme, universal links, or new screens. Give your campaign team the links your app already supports, for example myapp://open/product?id=SKU-123.
  • Links opened from outside the app still go through your onOpenURL or SceneDelegate code. Call the same router from both places.

6b. Custom actions

Map each action name you agreed on to a screen:

swift
// Inside AlgorithmXRouting.

// Runs first on every tap. Return false so the SDK runs the campaign's action.
func onNotificationClick(data: [String: Any]) -> Bool {
    false
}

func onCustomAction(action: String?, data: [String: Any]) -> Bool {
    let details = data["parsedActionData"] as? [String: Any] ?? [:]
    switch action {
    case "viewProduct":
        guard let productId = details["productId"] as? String, !productId.isEmpty else { return false }
        return AppRouter.shared.openProduct(id: productId)
    case "viewCart":
        return AppRouter.shared.openCart()
    default:
        return false
    }
}
  • The action's details are in parsedActionData. A number arrives as a number, so as? String does not work for it. Agree on the types with your campaign team.
  • An action name your app does not know does nothing. Only offer actions that your released app supports.

6c. Notification buttons

Match on the button's action text, not on its title, because the title can be translated:

swift
// Inside AlgorithmXRouting.
func onActionButtonClicked(
    buttonId: String,
    actionText: String,
    title: String,
    notificationData: [String: Any]
) -> Bool {
    switch actionText {
    case "viewCart":
        return AppRouter.shared.openCart()
    case "dismiss":
        return true // Handled: do nothing more.
    default:
        return false
    }
}

Every button opens the app. Return true when you handled the button. If you return false, the SDK runs the notification's main action instead. Buttons only appear after step 9.

Keep your normal login and permission checks before sensitive screens: a campaign only suggests where to go.

Check: send a test notification for each link and action your app supports. The right screen opens once.

Step 7: Check in-app campaigns

Production backend support is pending: the .NET in-app delivery route must be implemented as described in AlgorithmX issue #207. Current device tests use in-app-test-backend; no .NET implementation is included in this SDK update.

In-app campaigns use the API in SDK 1.1.0. Initialise the SDK and identify a signed-in customer; no campaign-fetch code, silent push, push token, or notification permission is needed for this flow.

  1. The SDK bootstraps its anonymous profile and device automatically.
  2. On startup or returning to the foreground, it calls GET /api/v1/inAppViews?language=...&customerId=....
  3. The backend checks the customer's segment, campaign publication/schedule and language, and returns eligible inline HTML, CSS, JavaScript, translations and variation parameters.
  4. The SDK selects a stable variation, applies priority, frequency, expiry and app-enter delay, and displays at most one campaign per visit. The template supplies its close button; Android also supports Back.

The SDK supplies X-Partner-Id, its persistent UUID in X-Anonymous-Id, and the installation UUID in X-Device-Id. Before login, customerId is the anonymous UUID. After identify / identifyUser, it is your application's account ID, stored by AlgorithmX as ExternalId. The backend resolves the internal profile ID; your app does not pass an AlgorithmX profile UUID. Identification, logout and account changes invalidate old campaign requests and content. Signed-in variation selection and local display history use the account ID.

Language defaults to the device/app language. Override it only when your app has its own language selector:

swift
AlgorithmX.shared.setInAppLanguage("ar")

An empty language override restores the automatic default. Arabic, Hebrew, Persian and Urdu translations use RTL layout; text and placeholder translations are applied from the template's builderState.translations.

First check: publish an active campaign that matches your test customer's segment and language, open the app, and confirm the GET request and impression. Leave the app and return to check another visit. Impressions, clicks, submits, copies and closes are logged through POST /api/v1/Event/Log as inAppViewInteraction; campaign and variation UUIDs remain strings.

The automatic mobile flow supports app-enter campaigns and an optional time delay. Browser URL/scroll/exit/inactivity rules and custom triggers are excluded by the backend from this automatic feed. Display history is stored on the installation; this is not a global cross-device frequency counter.

GET requests follow queued identity/profile POSTs. When identity is still processing (409), the SDK retries up to three times, and it retries again when connectivity returns or the app re-enters the foreground. Normal event/profile requests remain fire-and-forget. The old silent-push algoTriggerWebview is ignored. Visible push notifications retain their separate integration.

Step 8: Test before you release

Keep a test customer and the campaign team ready for this final pass. Check both what the person sees on the phone and what AlgorithmX records. Testing only the screen or only the server leaves half of the journey unchecked.

Use a physical iPhone and a test customer. Then repeat the main checks with a TestFlight build, because store builds use a different Apple push server than debug builds.

  • Update while logged in: install your current App Store version, log in, then update to the new build. The customer is recognized without logging in again.
  • Login, restart, logout, second account: events use the right customer each time. No campaign from the first account appears for the second.
  • Your existing notifications still work exactly as before.
  • AlgorithmX notification with the app open, in the background, and closed: a tap opens the right screen once, also when the tap starts the app.
  • Each deep link, custom action, and button opens the right screen.
  • In-app campaign: the SDK fetches it and it appears when the app opens and closes with its close button.
  • Notifications turned off: in-app campaigns still arrive.
  • Events appear for the customer in AlgorithmX.

While testing, setLoggingEnabled(true) shows each SDK request in the Xcode console. To see it on a phone without the debugger, run:

bash
xcrun devicectl device process launch --console --terminate-existing --device <device-id> <bundle-id>

App Store privacy

  • The SDK includes a privacy manifest (no tracking; device ID, user ID, and product interactions). Xcode adds it to your app's privacy report.
  • Your App Store privacy answers must also cover what you send yourself in identifyUser attributes and trackEvent details, such as names, emails, or purchases.
  • The SDK generates installation and anonymous UUIDs. It does not use an advertising identifier or show the tracking permission prompt.

Step 9 (optional): Images, buttons, and delivery reports

iOS shows basic notifications itself. For rich notifications with AlgorithmX images and action buttons, add a Notification Service Extension. The extension can also report delivery and impressions when configured with a shared App Group. Without it, basic notifications and taps still work.

API-based in-app views use normal SDK startup and foreground handling. Other background pushes use the main app's callback and require Background Modes → Remote notifications. A Notification Service Extension runs before iOS displays a visible alert with mutable-content: 1; it does not process a purely silent push. See Apple's background push guide and service extension requirements.

The same extension requirement applies to the iOS app built with React Native, Expo, or Flutter. The steps below explain how to give that separate target AlgorithmX's helper.

  1. If your app already has a notification service extension, add AlgorithmX handling there. Otherwise, in Xcode choose File → New → Target → Notification Service Extension, and set its iOS version to match your app. Configure the extension's bundle identifier and signing team, and confirm the app embeds it.
  2. Give the extension the SDK:
    • Swift Package Manager: use https://github.com/algorithmx-cloud/algorithmx-ios-sdk with version 1.1.0 or later. Select the extension target, open General → Frameworks and Libraries → +, and add the AlgorithmXSDK product from that package. Keep it linked to the main app target too.
    • CocoaPods, React Native, Expo, or Flutter: add the standalone EngageNotificationService.swift helper to the extension target only. Do not add the React Native bridge or Flutter plugin to this target. Download the helper below and remove the import AlgorithmXSDK line from the example.
Native iOS with Swift Package Manager: link AlgorithmXSDK to the extension target. The screenshot shows 1.0.1; use 1.1.0 or later. React Native, Expo, and Flutter use the standalone helper file described below.
Xcode Notification Service Extension target with AlgorithmXSDK added under Frameworks and Libraries

Native iOS with Swift Package Manager: link AlgorithmXSDK to the extension target. The screenshot shows 1.0.1; use 1.1.0 or later. React Native, Expo, and Flutter use the standalone helper file described below.

Get the helper from AlgorithmX

Download EngageNotificationService.swift for SDK 1.1.0

The download is the unmodified file from the iOS 1.1.0 release source. It is self-contained and can compile in the extension without the full SDK. Flutter 1.1.1 includes the same native helper in ios/algorithmx_flutter/Sources/algorithmx_flutter/NativeSDK/Notifications/ inside the installed plugin.

In Xcode, choose Add Files to your project, select the downloaded file, enable Copy items if needed, and select only the Notification Service Extension target. Confirm its Target Membership in the File inspector. Keep Xcode's NotificationService.swift; the downloaded file is an additional helper, not a replacement for the extension class. When upgrading the SDK, refresh the copied helper from the matching release.

Call the helper from your extension

Add the AlgorithmX branch to NotificationService.swift:

swift
import AlgorithmXSDK // Remove this line with CocoaPods (step 2).
import UserNotifications

final class NotificationService: UNNotificationServiceExtension {
    private var contentHandler: ((UNNotificationContent) -> Void)?
    private var bestAttemptContent: UNMutableNotificationContent?

    override func didReceive(
        _ request: UNNotificationRequest,
        withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void
    ) {
        self.contentHandler = contentHandler
        guard let content = request.content.mutableCopy() as? UNMutableNotificationContent else {
            contentHandler(request.content)
            return
        }
        bestAttemptContent = content

        if EngageNotificationService.isAlgorithmXPush(request) {
            EngageNotificationService.processNotification(
                request: request,
                bestAttemptContent: content,
                appGroup: "group.com.example.shop", // The same group as in main-app initialization.
                contentHandler: contentHandler
            )
            return
        }
        // Your existing code for other notifications.
        contentHandler(content)
    }

    override func serviceExtensionTimeWillExpire() {
        if let contentHandler, let bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }
}

Delivery reports need Signing & Capabilities → App Groups enabled for both the app and extension targets, using the same provisioned group. Pass that group to main-app initialization and processNotification. Without an App Group, call processNotification(request:bestAttemptContent:contentHandler:) instead; images and buttons still work.

Check: a test notification shows its image and buttons.

SDK endpoints

You do not need to write HTTP calls for these endpoints in your app; the SDK sends them when you use its APIs. This reference helps you or your backend team inspect requests during testing.

These paths are relative to your configured apiBaseUrl. SDK API requests include the x-partner-id header.

MethodEndpointPurpose
GET/api/v1/inAppViewsFetch eligible inline campaigns automatically with language, account/anonymous ID and identity headers.
POST/api/v1/Identity/BootstrapCreate or restore the SDK-generated anonymous profile and device.
POST/api/v1/IdentityLink ExternalId and trusted identifiers to the anonymous profile.
POST/api/v1/Customer/IngestReplace supported customer profile fields.
POST/api/v1/Event/LogTrack a custom event or automatic in-app view interaction.
POST/api/v1/tracks/algoViewInteractTrack a manual preview or visible-push interaction.
PUT/api/v1/inAppPushEvents/device/statusUpdate notification status.
POST/api/v1/notificationTokensRegister a push token.

trackEvent posts a one-event array to /api/v1/Event/Log: [{ eventType, data, timestamp }]. data contains the supplied properties or {}; timestamp is ISO 8601 UTC. In SDK 1.1.0, X-Anonymous-Id always contains the SDK-generated anonymous UUID, including after login. Identity requests use anonymousId and trustedIdentifiers, not fingerprintDevice, previousFingerprintDevice, or an attributes object on the wire. The SDK separates profile fields into /Customer/Ingest and adds X-Anonymous-Id and X-Device-Id to that request. All requests include X-Partner-Id.

API-based in-app view interactions use /api/v1/Event/Log with eventType: "inAppViewInteraction". Manual previews, visible-push interactions, token registration and notification status retain their existing transport contracts and need separate backend endpoint support. API templates are inline; manual preview HTML and notification images use GET requests to supplied URLs.

For a custom backend route, trackCampaignInteraction(..., endpoint:) can override the campaign interaction endpoint.

Quick reference

Call on AlgorithmX.sharedWhat it does
initialize(apiBaseUrl:partnerId:) or initialize(apiBaseUrl:partnerId:appGroup:)Starts the SDK. Call it in didFinishLaunchingWithOptions.
setLoggingEnabled(_:)Shows SDK requests in the console. Off by default.
setUserProfile(_:)Replace supported customer fields with the complete current profile.
setInAppLanguage(language)Optional override of automatic device/app language.
getAnonymousId()Read the SDK-generated anonymous UUID.
identifyUser(userId:attributes:)Sets the customer. Call at login and app start.
resetIdentity()Goes back to an anonymous customer. Call at logout.
trackEvent(_:properties:)Sends an event.
registerDeviceToken(_:)Sends the FCM registration token. Call on every launch and token refresh.
isAlgorithmXPush(userInfo:)Tells you if a notification is from AlgorithmX.
handleNotification(userInfo:completionHandler:)Gives a notification to the SDK, from didReceiveRemoteNotification and willPresent.
handleNotificationResponse(actionIdentifier:userInfo:completionHandler:)Gives a tap to the SDK, from didReceive response.
deepLinkHandler, notificationClickListener, actionButtonHandler, campaignInteractionListenerYour handlers. Keep a strong reference to each. Set nil to remove.
clearWebViewQueue()Removes waiting in-app campaigns. Call at logout.
isWebViewCurrentlyShowing()Tells you if a campaign is on screen.
getDeviceFingerprint(), getQueueSize()Show the current customer ID and waiting campaigns, for testing.
EngageNotificationService.processNotification(...)Call from your notification service extension (step 9).

Something not working?

ProblemWhat to check
No events in AlgorithmXinitialize runs in didFinishLaunchingWithOptions with the right HTTPS URL and partner ID, and the phone is online.
The app crashes when sending an eventA value is not an allowed type, for example a Date. Convert it first (step 4).
No AlgorithmX notificationsSend the current FCM token. AlgorithmX needs the service-account JSON for that Firebase project; Firebase needs the matching iOS app's APNs key, Key ID, Team ID, and build environment. Check signing and notification permission too.
Tapping a notification does nothingThe AppDelegate keeps a reference to your handlers. The delegate is set in didFinishLaunchingWithOptions. The AlgorithmX check in didReceive response runs.
A deep link does nothingdeepLinkHandler is set and calls your router. Your router accepts the link and waits for the app to be ready after a launch tap.
A button opens the wrong screenYour button handler returned false, so the main action ran. Check the action text.
No images or buttonsYour notification service extension calls processNotification and has the SDK (step 9).
In-app campaign never appearsCheck SDK startup, connectivity, the partner ID, and the GET response. Publish an active app-enter campaign matching the customer segment and language, then check frequency and expiry.
A campaign cannot be closedThe campaign template needs a close button. Ask your campaign team.
A previous account's campaign appearsCall clearWebViewQueue() at logout and when switching accounts.

Next steps

Create your first campaigns with In-App Push Campaigns and In-App View Campaigns. Go back to the overview for other platforms.