# iOS setup

> Connect Herald to Apple Push Notification service with an APNs auth key, register device tokens and handle notification taps.

This guide connects Herald to Apple Push Notification service (APNs) and wires your app to register for push and report opens.

## Before you start

- An Apple Developer Program membership with access to **Certificates, Identifiers & Profiles**.
- The SDK installed and configured. See [Quickstart: iOS](/docs/overview/quickstart-ios).
- Admin access to the Herald sending connection your agents use.

## 1. Create an APNs auth key

1. In your Apple Developer account, open **Certificates, Identifiers & Profiles > Keys** and add a key with **Apple Push Notifications service (APNs)** enabled.
2. Download the `.p8` file. Apple lets you download it once, so store it in your secrets manager.
3. Note the **Key ID** (10 characters) and your **Team ID** (10 characters, under **Membership details**).

One auth key works for every app on your team and for both the sandbox and production APNs environments.

## 2. Add the key to Herald

In Herald, open **Settings > Sending**, open the connection and fill the APNs section:

| Field | Value |
|---|---|
| Key (`.p8`) | The file from step 1 |
| Key ID | 10 characters |
| Team ID | 10 characters |
| Bundle ID | Your app's bundle identifier, such as `com.lumen.app` |

Herald stores the key encrypted and uses it to sign short-lived tokens for APNs.

## 3. Turn on the capability

In Xcode, select your app target, open **Signing & Capabilities** and add **Push Notifications**. Visible alerts do not need the **Remote notifications** background mode. Herald also sends silent sync pushes that refresh content cards and in-app messages, and those need it; see [Silent push](/docs/push-notifications/silent-push).

## 4. Register the device token

Set the notification delegate at launch, register with APNs on every launch once the user has allowed notifications, and pass the token to the SDK. Device tokens can change, so registering each launch keeps Herald current.

```swift
final class AppDelegate: NSObject, UIApplicationDelegate, @preconcurrency UNUserNotificationCenterDelegate {
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil
    ) -> Bool {
        Herald.configure(appKey: "YOUR_APP_KEY", endpoint: URL(string: "https://YOUR_HERALD_HOST")!)
        UNUserNotificationCenter.current().delegate = self
        Task {
            let settings = await UNUserNotificationCenter.current().notificationSettings()
            if settings.authorizationStatus == .authorized {
                application.registerForRemoteNotifications()
            }
        }
        return true
    }

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        Herald.shared.setPushToken(deviceToken)
    }
}
```

The first time, ask with `requestPushAuthorization()`. It shows the system prompt and registers with APNs when the user allows notifications. See [Permission prompts](/docs/push-notifications/permission-prompts) for when to ask.

The SDK picks the APNs environment for each token: `sandbox` on the simulator and in development-signed builds, `production` for App Store and TestFlight builds. Herald sends to the matching APNs host.

## 5. Handle taps and foreground display

Forward notification responses to the SDK. It logs the open, evaluates in-app messages with a push open trigger, and opens the push's deep link. It returns `false` for notifications that did not come from Herald, so you can handle your own.

iOS does not show a banner while your app is in the foreground unless you return presentation options.

```swift
extension AppDelegate {
    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        didReceive response: UNNotificationResponse,
        withCompletionHandler completionHandler: @escaping () -> Void
    ) {
        if !Herald.shared.handleNotificationResponse(response) {
            // Not a Herald push: handle your other notifications here.
        }
        completionHandler()
    }

    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        willPresent notification: UNNotification,
        withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
    ) {
        completionHandler([.banner, .list, .sound])
    }
}
```

The SDK counts each push open once, even if iOS delivers the same response again.

## What Herald sends

Each message push is a visible alert with high priority that expires after 24 hours. The payload carries:

| Key | Contents |
|---|---|
| `aps.alert` | The title (optional) and body |
| `aps.sound` | `default` |
| `aps.mutable-content` | `1`, only when the message has an image or buttons |
| `nexus_decision_id` | The Herald decision ID. The SDK uses it to recognize Herald pushes and credit the open. |
| `deeplink` | The message's deep link, when it has one |
| `image_url` | The message's iOS image, when it has one. See [Rich push](/docs/push-notifications/rich-push). |
| `herald_message_id` | The message ID, when the push comes from a campaign message |
| `herald_actions` | The buttons, when the message has them: each with an `id`, a `title` and an optional `deeplink` |
| `herald_test` | `"1"` on a test send |

Repeated sends for the same decision collapse into one notification on the device.

## Verify it works

1. Run the app on a device, sign in so the user is identified, and allow notifications.
2. With `options.logLevel = .debug`, confirm the console shows no `Herald rejected a batch` line after the token is sent.
3. Send a test push. See [Testing push](/docs/push-notifications/testing).

## Troubleshooting

- **APNs returns `BadDeviceToken`.** The token belongs to the other APNs environment than the one used. Rebuild with the signing you intend to test (development or distribution); the SDK sends the environment with each new token.
- **APNs returns `DeviceTokenNotForTopic`.** The bundle ID on the connection does not match the app that produced the token.
- **APNs returns `InvalidProviderToken`.** The Key ID or Team ID does not match the `.p8` key.
- **No pushes, no APNs errors.** Herald stores tokens only for identified, verified users. Check that the app calls `identify` and `setUserToken`, and that verification is not **Optional** with a missing token.

## Next

- [Permission prompts](/docs/push-notifications/permission-prompts)
- [Deep links](/docs/push-notifications/deep-links)
- [Rich push](/docs/push-notifications/rich-push)
