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

# iOS

> Install the Notifly iOS SDK, configure AppDelegate, and integrate push notifications.

The Notifly iOS SDK connects your iOS app to Notifly.\
The SDK supports the following features:

* Register devices with Notifly to receive push notifications and display in-app popups.
  (In-app popups appear only while the app is in the foreground.)
* Send event and user data to Notifly for campaign targeting and analysis.
* Log user behavior as events and measure campaign performance.

## Prerequisites

1. **Connect your Firebase project.**\
   The Notifly iOS SDK uses [Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging) to send push notifications.

> [Connect Firebase](https://docs.notifly.tech/en/developer-guide/firebase-integration.md)

2. **Register your APNs credentials for iOS.**

> [Register APNs credentials](https://docs.notifly.tech/en/developer-guide/firebase-integration.md#1-3-register-an-apns-authentication-key)

***

## 1. Configure iOS

### 1. Configure capabilities

1. Set the target's minimum iOS version to 15.0 or later. If you use CocoaPods, set the same minimum version in your Podfile.

2. Enable **Push Notifications** and **Background Modes**, including **Remote notifications** and **Background fetch**.

   ![Add Capabilities](https://mintcdn.com/notifly/QWigoXWbDguqzkH4/ko/developer-guide/image/ios_setting_add_capability1.png?fit=max\&auto=format\&n=QWigoXWbDguqzkH4\&q=85\&s=53445279fef5364a29715d9a887eff48)

   ![Add Capabilities](https://mintcdn.com/notifly/umP8GQfcNYrXNUqj/ko/developer-guide/image/ios_setting_add_capability2.png?fit=max\&auto=format\&n=umP8GQfcNYrXNUqj\&q=85\&s=aa12e246d24cf9eb015ea2aef2656c09)

## 2. Install the iOS SDK

Install the Notifly iOS SDK with CocoaPods or Swift Package Manager.

> [tab] CocoaPods
>
> 1. Make sure your Xcode project uses CocoaPods.
>    If it does not, follow the [CocoaPods setup guide](https://guides.cocoapods.org/using/getting-started.html).
> 2. At the top of your Podfile, add `platform :ios, '15.0'` or specify a later iOS version.
> 3. Add the following code to your Podfile.
>
> ```swift title="Podfile" highlight={3} theme={null}
> target 'YOUR_PROJECT_NAME' do
>
>  pod 'notifly_sdk'
>
> end
> ```

> [tab] Swift Package Manager
>
> 1. Make sure you can add Swift package dependencies in your Xcode project.
>    For setup instructions, see [Add package dependencies in Xcode](https://developer.apple.com/documentation/xcode/adding_package_dependencies_to_your_app).
> 2. In the project settings, open **Package Dependencies** and click **+**.
> 3. Enter the following URL and click **Next**.
>    ```
>    https://github.com/team-michael/notifly-ios-sdk
>    ```
> 4. Click **Add Package**.

## 3. Configure AppDelegate

Update AppDelegate so that the Notifly SDK can communicate with the iOS notification system.

### 1. Create an `AppDelegate` in a SwiftUI project

Your SwiftUI project may not have an AppDelegate file.
If the file is missing, create it as follows.

```swift title="AppDelegate.swift" theme={null}
import UIKit

class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        return true
    }
}
```

Add `@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate` to your App.swift file:

```swift title="<YOUR_PROJECT_NAME>App.swift" highlight={2} theme={null}
struct <YOUR_PROJECT_NAME>App: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
}
```

### 2. Initialize Notifly and configure delegates

Add the following import to `AppDelegate.swift`.

```swift theme={null}
import notifly_sdk
```

Add the Notifly calls to the `UIApplicationDelegate` methods in `AppDelegate.swift` to initialize the SDK and handle APNs registration.

| Method | Description |
| - | - |
| `application(_:didFinishLaunchingWithOptions:)` | Initialize Firebase and the Notifly SDK. |
| `application(_:didRegisterForRemoteNotificationsWithDeviceToken:)` | Register the APNs token with Notifly. |
| `application(_:didFailToRegisterForRemoteNotificationsWithError:)` | Notify Notifly if APNs registration fails. |

> [!NOTE]
>
> Find `projectId` and `username` on the settings page. `password` is a placeholder for backward compatibility. Pass the same nonempty value as `username`. Do not pass a real password or API Secret Key.

```swift title="AppDelegate.swift" highlight={8-10, 18-19, 26-27} theme={null}
import notifly_sdk

class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_: UIApplication,
                didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        /* ...YOUR CODE */

        FirebaseApp.configure() // if you don't configure Firebase SDK yet.
        // `password` is a legacy compatibility placeholder. Do not pass a real password or API Secret Key.
        Notifly.initialize(projectId: "YOUR_PROJECT_NAME", username: "YOUR_USERNAME", password: "YOUR_USERNAME")
        UNUserNotificationCenter.current().delegate = self
        return true
    }

    func application(_ application: UIApplication,
        didFailToRegisterForRemoteNotificationsWithError error: Error) {
        /* ...YOUR CODE */

        Notifly.application(application,
                            didFailToRegisterForRemoteNotificationsWithError: error)
    }

    func application(_ application: UIApplication,
        didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        /* ...YOUR CODE */

        Notifly.application(application,
            didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
    }

    /* ...YOUR CODE */
}

```

Implement the following `UNUserNotificationCenterDelegate` methods to forward push notification events to Notifly.

| Method | Description |
| - | - |
| `userNotificationCenter(_:willPresent:withCompletionHandler:)` | Display notifications in the foreground. |
| `userNotificationCenter(_:didReceive:withCompletionHandler:)` | Forward push notification click events. |

```swift title="UNUserNotificationCenterDelegate" highlight={14-15, 26-28} theme={null}
import notifly_sdk

class AppDelegate: UIResponder, UIApplicationDelegate {
    /* ...YOUR CODE */
}

// Extension of AppDelegate conforming to the UNUserNotificationCenterDelegate protocol
extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ notificationCenter: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completion: () -> Void) {
        /* ...YOUR CODE */

        Notifly.userNotificationCenter(notificationCenter,
                                    didReceive: response)

        /* ...YOUR CODE */
        completion()
    }

    func userNotificationCenter(_ notificationCenter: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completion: (UNNotificationPresentationOptions) -> Void) {
        /* ...YOUR CODE */

        Notifly.userNotificationCenter(notificationCenter,
                                    willPresent: notification,
                                    withCompletionHandler: completion)
    }
}
```

## 4. Register user information

Notifly uses user identifiers (`userId`) and user properties (`params`) to personalize marketing campaigns.\
Registered user information supports segmentation and targeting for channels such as push notifications, email, and Kakao AlimTalk.

### 1. Set the user ID (`Notifly.setUserId()`)

Map `userId` to the identifier of the signed-in user in your app.\
Notifly uses this value to track user events and personalize campaigns.

### Parameters

**userId** `String`

The signed-in user's ID. Pass `nil` on sign-out to clear the association.

```swift theme={null}
Notifly.setUserId(userId: userId)
```

#### Clear the user ID

On sign-out, call `Notifly.setUserId(userId: nil)` to clear the association between the current device and the user.
To retain the same user data, manage it separately on your server or in your app.

> [tab] iOS
>
> ```swift title="setUserId" highlight={4, 7} theme={null}
> import notifly_sdk
>
> // Set the user ID.
> Notifly.setUserId(userId: "exampleUserId")
>
> // Clear the user ID.
> Notifly.setUserId(userId: nil)
> ```

### 2. Set user properties

`setUserProperties` registers properties for the user.\
These properties support **segment targeting**, **message personalization**, and **delivery channel selection**.

> [!NOTE]
>
> **Before you send sensitive user properties**
>
> Before you send a custom user property that needs protection, such as a name or address, register it with the exact key you plan to send and enable encryption under **User Management > User List > Property management** in the console.
>
> See [Manage user properties](https://docs.notifly.tech/en/user-guide/users/properties.md) for setup instructions and limitations.

```swift theme={null}
Notifly.setUserProperties(userProperties: params)
```

### Parameters

**userProperties** `[String:Any]` *required*

Key-value pairs of user properties. Supports predefined keys such as `$email`, `$phone_number`, and `$line_user_id`.

> [!NOTE]
>
> * `$email`: Email address for email campaigns.
> * `$phone_number`: Phone number for SMS and Kakao campaigns.
> * `$line_user_id`: LINE user ID for LINE message campaigns.
> * Custom fields: Define your own fields, such as `"plan"`, `"tier"`, and `"country"`.

> [tab] iOS
>
> ```swift title="setUserProperties" highlight={9} theme={null}
> import notifly_sdk
>
> let sampleUserProperties = [
>     "age": 15,
>     "sex": "male",
>     "push_allowed": true
> ] as [String : Any]
>
> Notifly.setUserProperties(userProperties: sampleUserProperties)
> ```

## 5. Log events

Record user behavior to use in **campaign triggers**, **segment conditions**, and **performance analysis**.\
For example, collect button clicks, page visits, and completed purchases as events.

```swift theme={null}
Notifly.trackEvent(
    eventName: eventName,
    eventParams: eventParams,
    segmentationEventParamKeys: segmentationEventParamKeys
)
```

### Parameters

**eventName** `String` *required*

Event name, such as `"ticket_purchase"`.

**eventParams** `[String: Any]`

Additional event parameters, such as `"ticket_name": "premium"` or `"duration": 120`.

**segmentationEventParamKeys** `[String]`

List of event parameter keys to use for segmentation. Supports at most one key.

> [!NOTE]
>
> Use `segmentationEventParamKeys` to make an event parameter (`eventParams`) available for targeting. You can specify **at most one key**.

> [tab] Swift
>
> ```swift title="trackEvent" highlight={5, 17-25} theme={null}
> import notifly_sdk
>
> ...
>     Button(action: {
>         Notifly.trackEvent(eventName: "click_button_1")
>     }) {
>     Text("Button 1")
>         .padding(5)
>         .background(Color.red)
>         .foregroundColor(.white)
>         .cornerRadius(10)
>     }
>
> ...
>
>     Button(action: {
>         Notifly.trackEvent(
>             eventName: "ticket_purchase",
>             eventParams: [
>                 "ticket_name": "exampleTicket",
>                 "ticket_price": 10000,
>                 "ticket_purchase_date": "2021-01-01"
>             ],
>             segmentationEventParamKeys: ["ticket_name"]
>         )
>     }) {
>     Text("Buy tickets")
>         .padding(5)
>         .background(Color.black)
>         .foregroundColor(.white)
>         .cornerRadius(10)
>     }
> ...
> ```

## 6. Get the internal user ID

`getNotiflyUserId()` returns the unique user ID that Notifly manages internally.\
This ID is **separate from the user ID set with `setUserId()`**. Most integrations do not need it.\
Use it when an external CRM or third-party integration requires Notifly's internal user ID.

```swift theme={null}
Notifly.getNotiflyUserId()
```

## 7. Configure an iOS Notification Service Extension (recommended)

> [!NOTE]
>
> Requires `notifly-sdk` version 1.3.0 or later.

Configure a Notification Service Extension to use rich push notifications. Follow the [Push Extension guide](https://docs.notifly.tech/en/advanced/rich-push-notification.md).

#### Supported features

1. Attach images and videos to push notifications.
2. Track push notification delivery to analyze campaign performance in more detail.

> [!WARNING]
>
> The SDK works without a Notification Service Extension, but rich push notifications and delivery tracking are unavailable.

## 8. Test the integration

After you install the SDK, follow [Test your integration](https://docs.notifly.tech/en/integration-test.md) to verify event collection and push notification delivery.

## 9. Advanced integration

> [card] [Request push notification permission](https://docs.notifly.tech/en/advanced/push-notification-consent.md)

> [card] [In-app popup event listener](https://docs.notifly.tech/en/advanced/inapp-popup-event-listener.md)

> [card] [Rich push notifications](https://docs.notifly.tech/en/advanced/rich-push-notification.md)

## FAQ

> [accordion] Can I use Notifly with an existing Firebase Cloud Messaging integration?
>
> The Notifly iOS SDK can work alongside Firebase Cloud Messaging that your app already uses.

> [accordion] Push tokens are not forwarded or in-app popups do not work in a SwiftUI project.
>
> In a SwiftUI app, the Firebase SDK's method swizzling may fail to forward delegate calls correctly.
> ([Related issue: firebase-ios-sdk#7473](https://github.com/firebase/firebase-ios-sdk/issues/7473))
>
> In Info.plist, set `FirebaseAppDelegateProxyEnabled` to the Boolean value `NO` to disable swizzling.
>
> ```xml title="Info.plist" theme={null}
> <key>FirebaseAppDelegateProxyEnabled</key>
> <false/>
> ```
>
> After disabling swizzling, forward the APNs token to Firebase manually:
>
> ```swift title="AppDelegate.swift" theme={null}
> func application(_ application: UIApplication,
>                  didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
>     Messaging.messaging().apnsToken = deviceToken
>     Notifly.application(application, didRegisterForRemoteNotificationsWithDeviceToken: deviceToken)
> }
> ```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.