> ## 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 iOS push notifications

> The HightouchPush library connects your iOS app to Hightouch Delivery so campaigns and journeys can send it push notifications. Register your app in Hightouch, add the SDK to your app, and send yourself a test.

Setting up Android too? See [Set up Android push notifications](https://docs.hightouch.com/native-delivery/push-android.md).

## Before you begin

* **Delivery** — Delivery must be enabled in your workspace.
* **Parent model** — Delivery must have a parent model selected in the **Data source** card on **Delivery > Settings > Profiles**. Push notifications are addressed to users by its primary key.
* **Apple Developer access** — You need the Account Holder or Admin role to create an APNs key.
* **Physical device** — The iOS Simulator can't receive push notifications. Test on a device running a debug build from Xcode or a TestFlight build.
* **iOS 13 or later** — The SDK supports iOS 13.0 and later.

## Collect your Apple credentials

Hightouch sends notifications through Apple Push Notification service (APNs) on your behalf, using four values from your Apple Developer account.

| Credential | Where to find it |
| - | - |
| **Bundle ID** | In Xcode, on your app target's **General** tab. |
| **APNs authentication key (.p8)** | In [Apple Developer](https://developer.apple.com/account), go to **Certificates, Identifiers & Profiles > Keys** and create a key with **Apple Push Notifications service (APNs)** enabled. |
| **Key ID** | Next to the key name on the same **Keys** page. |
| **Team ID** | In [Apple Developer](https://developer.apple.com/account), go to **Account > Membership details**. |

Apple lets you download a `.p8` file only once, when you create the key. One key works for every app on your team, so check whether your team already has one before you create another.

## Create an iOS event source

The SDK sends device registrations and notification opens to a Hightouch event source of type iOS. Skip this section if your workspace already has one.

1. Go to **Event Collection > Event sources** and click **Create source**.
2. Click **iOS** and finish creating the source.
3. On the source's **Setup** tab, copy the **Write key** and the **API Host**.

A workspace can have only one iOS event source for push.

## Register your app in Hightouch

1. Go to **Delivery > Settings > Apps**. If you already registered this app for Android, open it and skip to the next step. Otherwise, click **Add**, enter a **Name**, and click **Add**. The name appears on every notification.
2. On the **iOS (APNs)** card, click **Enable**.
3. Enter your [Apple credentials](#collect-your-apple-credentials), then save.
4. Copy the **App ID** from the top of the **iOS (APNs)** card.

Hightouch connects the app to your event source when you enable it.

> [!WARNING]
>
> You can't disable a platform after you enable it. To delete an app, contact Hightouch support.

> [!NOTE]
>
> The App ID isn't your app's package name or bundle ID. It's an ID that Hightouch assigns.

### Match the APNs environment to your build

Apple runs separate push environments for development and production, and a device receives pushes only from the environment its build was signed for.

| Build | APNs environment |
| - | - |
| Debug build run from Xcode onto a device | Development |
| TestFlight or App Store build | Production |

Apps use Production by default. To test a debug build from Xcode, ask your Hightouch team to switch your app to Development, and to switch it back when you move to TestFlight. After each switch, call `identify` again on your test device.

## Configure your Xcode project

### Add capabilities

On your app target's **Signing & Capabilities** tab, add these capabilities:

* **Push Notifications**
* **Background Modes**, with **Remote notifications** selected

### Install the SDK

Add `https://github.com/ht-sdks/events-sdk-swift` with Swift Package Manager, and add both the `Hightouch` and `HightouchPush` libraries to your app target. In Xcode, go to **File > Add Package Dependencies**.

If you manage dependencies in `Package.swift`, add the package and both libraries:

```swift theme={null}
dependencies: [
    .package(url: "https://github.com/ht-sdks/events-sdk-swift", from: "1.1.1")
],
targets: [
    .target(
        name: "YourApp",
        dependencies: [
            .product(name: "Hightouch", package: "events-sdk-swift"),
            .product(name: "HightouchPush", package: "events-sdk-swift"),
        ]
    )
]
```

### Add a Notification Service Extension

A Notification Service Extension lets notifications show images and action buttons. Without one, notifications still arrive as plain text.

1. Go to **File > New > Target** and select **Notification Service Extension**.
2. Add the `HightouchPush` library to the new target.
3. Replace the generated `NotificationService.swift` with the Hightouch base class:

```swift theme={null}
import HightouchPush

class NotificationService: HightouchNotificationServiceExtension {}
```

## Initialize the SDK

Initialize `HightouchPush` in `application(_:didFinishLaunchingWithOptions:)` with your write key, API host, and App ID. Set the notification center delegate in the same place so the app doesn't miss a tap that launches it.

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

class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    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")

        HightouchPush.initialize(
            configuration: configuration,
            config: HightouchPushConfig(appId: "YOUR_HIGHTOUCH_APP_ID")
        )

        return true
    }
}
```

Replace `YOUR_API_HOST` with the **API Host** from your event source's **Setup** tab, such as `eu-west-1.hightouch-events.com`, and keep `/v1` at the end.

If you already use the [iOS SDK](https://docs.hightouch.com/events/sdks/ios.md) to track events, pass your existing instance with `HightouchPush.initialize(analytics: analytics, config: ...)` instead. Its write key must belong to your iOS event source.

In a SwiftUI app, attach the app delegate with `@UIApplicationDelegateAdaptor(AppDelegate.self)`. For a complete app delegate, see the [PushTestApp sample](https://github.com/ht-sdks/events-sdk-swift/tree/main/Examples/apps/PushTestApp) in the SDK repository.

`HightouchPushConfig` takes these options:

| Option | What it does | Default |
| - | - | - |
| **`appId`** | The App ID from your app's **iOS (APNs)** card. Required. | |
| **`urlDelegate`** | Handles links from notification taps. See [Handle deep links](#handle-deep-links). | `nil` |
| **`customActionDelegate`** | Handles action buttons that don't open a URL. | `nil` |
| **`silentPushDelegate`** | Receives data from silent pushes. See [Receive silent pushes](#receive-silent-pushes). | `nil` |
| **`allowedProtocols`** | URL schemes other than `https` that the SDK can open, such as `["myapp"]`. | `[]` |
| **`autoClearBadgeOnForeground`** | Clears the app icon badge whenever the app opens. | `false` |

## Register the device for push

Ask the user for permission, register with APNs, and pass the device token to the SDK. You decide when to ask; many apps wait until after onboarding.

Request permission and register:

```swift theme={null}
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, _ in
    guard granted else { return }
    DispatchQueue.main.async {
        UIApplication.shared.registerForRemoteNotifications()
    }
}
```

Then pass the token to the SDK in your app delegate:

```swift theme={null}
func application(
    _ application: UIApplication,
    didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
    HightouchPush.register(token: deviceToken)
}
```

## Identify users on login and logout

Call `identify` when a user logs in and `logout` when they log out:

```swift theme={null}
HightouchPush.identify(userId: "USER_ID")

HightouchPush.logout()
```

The user ID must match the user's primary key in your Delivery parent model. Delivery uses it to find each user's devices. `identify` links the device to that user, and `logout` unlinks it so the device stops receiving their notifications.

If you also track events with the iOS SDK, call `HightouchPush.identify` instead of `analytics.identify` so the device stays linked to the right user.

## Handle notification taps

Forward notification taps to the SDK, which records the open and follows the notification's link:

```swift theme={null}
func userNotificationCenter(
    _ center: UNUserNotificationCenter,
    didReceive response: UNNotificationResponse,
    withCompletionHandler completionHandler: @escaping () -> Void
) {
    HightouchAppIntegration.userNotificationCenter(
        center, didReceive: response, withCompletionHandler: completionHandler
    )
}
```

If your app also receives notifications from another provider, forward only the ones whose `userInfo` contains a `hightouch` key.

iOS hides notifications that arrive while your app is open. To show them, implement `willPresent`:

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

### Handle deep links

By default, the SDK opens `https` links as Universal Links when they match your app's Associated Domains, and in the default browser otherwise. To route links yourself, set a `urlDelegate` and return `true` for links you handle:

```swift theme={null}
final class PushLinkHandler: HightouchURLDelegate {
    func handle(url: URL, inContext context: HightouchActionContext) -> Bool {
        return Router.shared.open(url)
    }
}
```

To let the SDK open links with a custom scheme, such as `myapp://`, add the scheme to `allowedProtocols`.

## Receive silent pushes

A silent push wakes your app in the background without showing a notification, and delivers custom data to your `silentPushDelegate`. Silent pushes need the **Remote notifications** background mode.

Forward background notifications to the SDK:

```swift theme={null}
func application(
    _ application: UIApplication,
    didReceiveRemoteNotification userInfo: [AnyHashable: Any],
    fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
) {
    HightouchAppIntegration.application(
        application, didReceiveRemoteNotification: userInfo, fetchCompletionHandler: completionHandler
    )
}
```

Then implement the delegate and set it on your config before you call `initialize`:

```swift theme={null}
final class SilentPushHandler: HightouchSilentPushDelegate {
    func receive(customData: [String: String]) async {
        // Refresh content or sync state.
    }
}
```

The SDK keeps only a weak reference to its delegates, so hold your own reference, for example in a static property.

To set or clear the app icon badge yourself, call `await HightouchPush.setBadge(3)` or `await HightouchPush.resetBadge()`.

## Send yourself a test push

Run your app on a device and log in so that `identify` runs, then send a test from Hightouch. In both places, **Validate** checks that a device is registered for the user ID you enter.

**From app settings:** Go to **Delivery > Settings > Apps**, open your app, and click **Test**. Enter your user ID, click **Validate**, then click **Send test**. The test includes an image, so it also checks your Notification Service Extension.

**From the campaign editor:** Go to **Delivery > Campaigns**, click **Add campaign**, and select **Push**. In the **Create a new campaign** dialog, select your app under **Choose apps to target**, choose a brand if asked, and click **Continue**. Under **Content**, click **Edit** and write your message. On the **Preview** tab, click **Send test**, enter your user ID, click **Validate**, then click **Send test**.

If **Validate** finds no device, you can enter a device token instead. A test that arrives this way means your push credentials work and the device isn't linked to that user.

## Troubleshooting

#### No active devices found

**Validate** shows this when no device is registered for the user ID. Check that:

* `appId` is the App ID from your app's **iOS (APNs)** card.
* Your app calls `identify` after the user logs in, with the parent model's primary key.
* The API host in your SDK setup matches the **API Host** on your iOS event source's **Setup** tab.

After you fix any of these, call `identify` again on the device. To see what your app sends, open your iOS event source's **Debugger** tab. After `identify`, you see a `CEP Push Token Events` event with your user ID and an `app_id` that matches your App ID.

#### Validate passes, but no notification arrives

Your app's APNs environment doesn't match your build. See [Match the APNs environment to your build](#match-the-apns-environment-to-your-build).

#### No ios event source found for this workspace

You see this when you enable the **iOS (APNs)** card before your workspace has an iOS event source. [Create an iOS event source](#create-an-ios-event-source), then click **Enable** again. If your workspace has more than one iOS event source, contact Hightouch support.

#### Notifications arrive without images or buttons

Check that your project has a [Notification Service Extension](#add-a-notification-service-extension) and that the extension target links `HightouchPush`.

## Next steps

* [Preview and test](https://docs.hightouch.com/native-delivery/preview-and-test.md) to render a message against real profiles before you send it.
* [Send a campaign](https://docs.hightouch.com/native-delivery/campaigns.md) to schedule your first push to an audience.
