> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hightouch.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Set up in-app messages on iOS

> The HightouchPush library syncs each user's in-app messages to your iOS app. Your app shows them in its own views and reports impressions, clicks, and dismissals back to Hightouch.

Setting up Android too? See [Set up in-app messages on Android](https://docs.hightouch.com/native-delivery/in-app/android.md).

## Overview

In-app messages arrive in your app as data, not as finished screens. The SDK keeps a local inbox of each user's messages up to date and calls your code when it changes. Your app picks the messages for a screen, lays them out with its own views, and reports what the user did with them.

Each message carries the fields from its template, such as a headline, an image URL, and a button label, keyed by the names your marketing team agreed with you. See [What your app receives](https://docs.hightouch.com/native-delivery/in-app/templates.md#what-your-app-receives).

## Before you begin

* **Push setup:** Complete [Set up iOS push notifications](https://docs.hightouch.com/native-delivery/push-ios.md) through **Identify users on login and logout**. The SDK fetches a user's messages only for a device that has registered a push token and called `identify`.
* **iOS 13 or later:** In-app messages need `HightouchPush` version 1.1.0 or later.
* **A template:** Agree with your marketing team on the templates your app supports, and the key of each field. See [Build an in-app template](https://docs.hightouch.com/native-delivery/in-app/templates.md).

## Turn on in-app messages

Add a `HightouchMessagesConfig` to the `HightouchPushConfig` you already pass to `HightouchPush.initialize`, in `application(_:didFinishLaunchingWithOptions:)`:

```swift theme={null}
import Hightouch
import HightouchPush

final class InAppMessagesObserver: HightouchMessagesDelegate {
    func hightouchMessagesDidChange(_ change: HightouchMessagesChange) {
        // Reload any screen that shows in-app messages.
    }
}

class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    // The SDK keeps only a weak reference to the delegate, so hold it here.
    static let messagesObserver = InAppMessagesObserver()

    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
    ) -> Bool {
        UNUserNotificationCenter.current().delegate = self

        let configuration = Configuration(writeKey: "YOUR_WRITE_KEY")
            .apiHost("YOUR_API_HOST/v1")
            .cdnHost("YOUR_API_HOST/v1")

        var messagesConfig = HightouchMessagesConfig()
        messagesConfig.delegate = AppDelegate.messagesObserver
        messagesConfig.syncOnForeground = true

        var pushConfig = HightouchPushConfig(appId: "YOUR_HIGHTOUCH_APP_ID")
        pushConfig.messages = messagesConfig

        HightouchPush.initialize(configuration: configuration, config: pushConfig)
        return true
    }
}
```

Call `initialize` synchronously in `didFinishLaunchingWithOptions`. If a silent push launches the app before `initialize` runs, the SDK ignores the push.

`HightouchMessagesConfig` takes these options:

| Option | What it does | Default |
| - | - | - |
| **`delegate`** | Receives a `HightouchMessagesChange` whenever the inbox gains, changes, or loses a message. | `nil` |
| **`syncOnLaunch`** | Fetches messages each time the SDK initializes. | `true` |
| **`syncOnForeground`** | Fetches messages when the app returns to the foreground, at most once per cooldown. | `false` |
| **`foregroundSyncCooldown`** | Seconds between foreground syncs. The minimum is 60. | `900` |
| **`maxStoredMessages`** | The most messages the SDK keeps on the device. | `500` |

Turn on `syncOnForeground` unless your app relies on silent pushes alone. Without it, the SDK doesn't fetch new messages for a user who keeps the app in the background until the next launch or silent push.

## Keep the inbox up to date

The SDK fetches messages:

* When the app launches, if `syncOnLaunch` is on.
* When the app returns to the foreground, if `syncOnForeground` is on.
* When a user logs in with `HightouchPush.identify`.
* When a silent push arrives from Hightouch, if the message has push apps selected. See [Refresh inboxes right away](https://docs.hightouch.com/native-delivery/in-app/messages.md#refresh-inboxes-right-away).

Each sync replaces the device's inbox with the user's current messages. The SDK removes messages that left the user's inbox in Hightouch, such as when a campaign ends. It stores messages on the device, so your app can show them without a network connection.

The silent push uses the same forwarding you set up in [Receive silent pushes](https://docs.hightouch.com/native-delivery/push-ios.md#receive-silent-pushes). Keep `HightouchAppIntegration.application(_:didReceiveRemoteNotification:fetchCompletionHandler:)` in your app delegate, and keep the **Remote notifications** background mode turned on.

To fetch messages yourself, such as on pull to refresh, call `sync`:

```swift theme={null}
HightouchMessages.sync(force: true) { outcome in
    // outcome is .changed(messageCount:), .unchanged, or .failed(Error)
}
```

## Show messages in your app

Load the messages for a screen with `loadMessages`, which calls back on the main thread. Filter by the template's Location ID to get the messages for one placement:

```swift theme={null}
HightouchMessages.loadMessages(
    matching: HightouchMessageQuery(locationId: "home_banner", limit: 1)
) { messages in
    guard let message = messages.first else {
        hideBanner()
        return
    }
    showBanner(for: message)
}
```

The SDK returns messages sorted by priority, then by most recent, and leaves out expired messages. A `HightouchMessageQuery` also takes `variantSlug`, the template's key, to load only messages built from one template. To read synchronously, call `HightouchMessages.messages(matching:)`. It can block while the store opens, so prefer `loadMessages` on the main thread.

Read the fields from the message's `content`. Each element's `tag` is a field key from the template:

```swift theme={null}
func element(_ key: String, in message: HightouchMessage) -> JSON? {
    guard case .array(let elements)? = message.content?["elements"] else { return nil }
    return elements.first { $0["tag"]?.stringValue == key }
}

let headline = element("headline", in: message)?["text"]?.stringValue
let imageURL = element("hero", in: message)?["mediaUrl"]?.stringValue
```

A field the marketer left empty, with no default, isn't in `elements`. Give your views a fallback for every optional field.

## Report impressions, clicks, and dismissals

The SDK doesn't know when your app shows a message, so report each interaction yourself. These events power the **Impressions**, **Clicked**, and **Dismissed** metrics in Hightouch, and they're written to your warehouse.

```swift theme={null}
// When the message is on screen, not when it's loaded.
HightouchMessages.trackImpression(messageId: message.messageId)

// When the user taps the message or one of its buttons.
HightouchMessages.trackClick(messageId: message.messageId, identifier: "cta")

// When the user closes the message.
HightouchMessages.trackDismissed(messageId: message.messageId)
```

Your app performs the tap's action itself, such as opening a screen. Pass an `identifier` to `trackClick` to tell buttons apart in your warehouse data. It defaults to `default`.

`trackDismissed` removes the message from the device, and Hightouch removes it from the user's other devices. The user doesn't receive that message again, even if they leave and rejoin the audience.

## Tips and troubleshooting

### No messages arrive

The SDK skips a sync when the user isn't identified or the device has no push token. Check that:

* Your app calls `HightouchPush.register(token:)` with the APNs device token, and `HightouchPush.identify` after the user logs in. Users who aren't logged in don't receive in-app messages.
* The user ID matches the primary key of the profile in your Delivery parent model.
* The profile is in the campaign's audience, or has reached the journey's **Send in-app** tile, and the campaign or journey is running.

Then call `HightouchMessages.sync(force: true)` and check the outcome. If it returns `.unchanged`, the SDK either found no changes or skipped the sync because the user isn't identified or the device has no push token.

### A new message takes a while to appear

Without a push app on the message, a device picks it up on its next sync. Turn on `syncOnForeground`, or ask your marketing team to [select push apps](https://docs.hightouch.com/native-delivery/in-app/messages.md#refresh-inboxes-right-away) on the message.

### Messages stop updating after a while

The SDK keeps a weak reference to your delegate. If nothing else holds it, it's released and your app stops hearing about changes. Store the delegate in a static or long-lived property.

## Next steps

* [Build an in-app template](https://docs.hightouch.com/native-delivery/in-app/templates.md): the fields and keys your app reads.
* [Send an in-app campaign](https://docs.hightouch.com/native-delivery/in-app/campaigns.md): send a message to your test profile to check the integration end to end.
