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

# Push Notifications

> Set up and customize push notifications with the Userpilot iOS SDK

Configure push notifications to receive, display, and handle Userpilot push notifications on iOS.

The Userpilot SDK supports push notifications to help you deliver targeted messages and enhance user engagement.

***

## Prerequisites

Configure your iOS push settings in the [Userpilot Settings Studio](https://run.userpilot.io/settings/mobile) before setting up push notifications in your app.

To obtain the required keys and configuration details, refer to the [iOS Push Notification Guide](../ios-push-notification-setup-guide).

***

## Setup

In Xcode, navigate to the **Signing & Capabilities** section of your main app target and add the **Push Notifications** capability.

There are two options for configuring push notifications: automatic or manual.

Automatic configuration is the quickest and simplest way to configure push notifications and is recommended for most customers.

### Automatic Configuration

Automatic configuration takes advantage of swizzling to automatically provide the necessary implementations of the required `UIApplicationDelegate` and `UNUserNotificationCenterDelegate` methods.

To enable automatic configuration, call `Userpilot.enableAutomaticPushConfig()` from `UIApplicationDelegate.application(_:didFinishLaunchingWithOptions:)`.

<CodeGroup>
  ```swift Swift theme={null}
  func application(
      _ application: UIApplication,
      didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
      // Automatically configure for push notifications
      Userpilot.enableAutomaticPushConfig()

      // Override point for customization after application launch
      return true
  }
  ```

  ```c Obj-c theme={null}
  - (BOOL)application:(UIApplication *)application
      didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

      // Automatically configure for push notifications
      [Userpilot enableAutomaticPushConfig];

      // Override point for customization after application launch
      return YES;
  }
  ```
</CodeGroup>

Automatic configuration seamlessly integrates with your app's existing push notification handling. It processes only Userpilot notifications, while ensuring that all other notifications continue to be handled by your app's original logic.

### Manual Configuration

**Step 1. Register for Push Notifications**

```swift theme={null}
// AppDelegate.swift

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

    // ...
    return true
}
```

**Step 2. Set Push Token for Userpilot**

To enable push notifications, your app **must explicitly request permission from the user**.

```swift theme={null}
private func requestPushNotificationPermission() {
    let options: UNAuthorizationOptions = [.alert, .sound, .badge]

    // Check if the app has already been authorized
    UNUserNotificationCenter.current().getNotificationSettings { settings in
        if settings.authorizationStatus == .authorized {
            // App is already authorized for push notifications
            // Register for remote notifications again to get the device token
            DispatchQueue.main.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        } else {
            // If not authorized, request permission
            UNUserNotificationCenter.current().requestAuthorization(options: options) { granted, error in
                if granted {
                    DispatchQueue.main.async {
                        UIApplication.shared.registerForRemoteNotifications()
                    }
                } else if let errorDescription = error?.localizedDescription {
                    print("Permission denied or failed to request: \(errorDescription)")
                } else {
                    print("Permission denied or failed to request: Unknown error")
                }
            }
        }
    }
}
```

Call `Userpilot.setPushToken(_:)` from `UIApplicationDelegate.application(_:didRegisterForRemoteNotificationsWithDeviceToken:)` to pass the APNs token from calling `registerForRemoteNotifications()` to Userpilot.

```swift theme={null}
// AppDelegate.swift

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

**Step 3. Enable Push Response Handling**

Update your `AppDelegate` to conform to the `UNUserNotificationCenterDelegate` protocol and assign `self` as the delegate in `application(_:didFinishLaunchingWithOptions:)`.

Implement `userNotificationCenter(_:didReceive:withCompletionHandler:)` and pass the received notification response to `Userpilot.didReceiveNotification(response:completionHandler:)`.

```swift theme={null}
// AppDelegate.swift

@main
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    func application(
        _ application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    ) -> Bool {
        application.registerForRemoteNotifications()
        UNUserNotificationCenter.current().delegate = self
        return true
    }

    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        didReceive response: UNNotificationResponse,
        withCompletionHandler completionHandler: @escaping () -> Void
    ) {
        if userpilotInstance.didReceiveNotification(response: response, completionHandler: completionHandler) {
            // NOTE: Userpilot calls the completion handler if the notification is a Userpilot notification
            return
        }
        completionHandler()
    }
}
```

**Step 4. Configure Foreground Handling**

Configure handling of push notifications received while your app is in the foreground by implementing `userNotificationCenter(_:willPresent:withCompletionHandler:)`.

```swift theme={null}
// AppDelegate.swift

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

For more details, refer to the `AppDelegate+PushNotification.swift` file in the [sample app](https://github.com/Userpilot/ios-sdk).

<Frame>
  [**For any questions or concerns please reach out to support@userpilot.com**](mailto:support@userpilot.com)
</Frame>
