> ## 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

> 노티플라이 iOS SDK 설치와 AppDelegate 설정, 푸시 알림 연동 방법을 안내합니다.

노티플라이 iOS SDK는 iOS 앱에 노티플라이 서비스를 연동하기 위한 SDK입니다.\
다음 기능을 지원합니다:

* 기기 정보를 노티플라이에 등록하여 푸시 알림 수신 및 인앱 팝업 노출
  (인앱 팝업은 Foreground 상태에서만 표시됩니다)
* 이벤트 및 유저 정보를 노티플라이와 연동하여 캠페인 타깃팅 및 분석 활용
* 유저 행동 데이터를 기반으로 한 이벤트 로깅 및 성과 측정

## 시작하기 전에

1. **Firebase 프로젝트 연동 완료**\
   노티플라이 iOS SDK는 푸시 발송을 위해 [Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging)을 사용합니다.

> 👉 [Firebase 프로젝트 연동 가이드](https://docs.notifly.tech/ko/developer-guide/firebase-integration.md)

2. **iOS APNs 인증 등록**

> 👉 [APNs 인증서 등록](https://docs.notifly.tech/ko/developer-guide/firebase-integration.md#1-3-apns-%EC%9D%B8%EC%A6%9D%EC%84%9C-%EB%93%B1%EB%A1%9D)

\--

## 1. iOS 설정

### 1. Capability 설정

1. iOS Deployment Target/Target의 Minimum Deployments을 13.0 이상으로 설정하고, Podfile의 최소 버전도 동일하게 지정합니다.

2. Push Notification 및 Background Mode (Remote notification, 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. iOS SDK 설치

노티플라이 iOS SDK는 CocoaPods 또는 Swift Package Manager를 통해 설치할 수 있습니다.

> [tab] CocoaPods
>
> 1. Xcode 프로젝트에 CocoaPods 설치가 되어있는지 확인합니다.
>    설치가 되어있지 않은 경우 [CocoaPods 설치 가이드](https://guides.cocoapods.org/using/getting-started.html)를 참고해 주세요.
> 2. Podfile 파일의 상단에 **platform :ios, '13.0'** 또는 그 이상의 버전으로 입력해 주세요.
> 3. Podfile 파일에 다음 코드를 추가해 주세요.
>
> ```swift title="Podfile" highlight={3} theme={null}
> target 'YOUR_PROJECT_NAME' do
>
>  pod 'notifly_sdk'
>
> end
> ```

> [tab] Swift Package Manager
>
> 1. Xcode 프로젝트에 Swift Package Manager 설치가 되어있는지 확인합니다.
>    설치가 되어있지 않은 경우 [Swift Package Manager 설치 가이드](https://developer.apple.com/documentation/xcode/adding_package_dependencies_to_your_app)를 참고해 주세요.
> 2. Project's Settings > Package Dependencies > + 버튼을 클릭합니다.
> 3. 다음 URL을 입력하고 Next를 클릭합니다.
>    ```
>    https://github.com/team-michael/notifly-ios-sdk
>    ```
> 4. Add Package를 클릭합니다.

## 3. AppDelegate 설정

노티플라이 SDK가 iOS 알림 시스템과 통신할 수 있도록 AppDelegate 파일을 수정합니다.

### 1. SwiftUI 프로젝트에서 `AppDelegate` 생성

SwiftUI 프로젝트에는 기본적으로 AppDelegate 파일이 없을 수 있습니다.
이 경우, 아래와 같이 생성합니다.

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

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

App.swift 파일에는 ` @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate`을 추가합니다:

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

### 2. Notifly 초기화 및 Delegate 설정

노티플라이 SDK를 사용하려면 `AppDelegate.swift`에 다음 코드를 추가하세요.

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

앱 초기화와 APNs 등록을 위해 `AppDelegate.swift`의 `UIApplicationDelegate` 함수 내 노티플라이 관련 코드를 추가합니다.

| 함수 이름 | 설명 |
| - | - |
| `application(_:didFinishLaunchingWithOptions:)` | Firebase 초기화 및 노티플라이 SDK 초기화 |
| `application(_:didRegisterForRemoteNotificationsWithDeviceToken:):` | APNs 토큰을 노티플라이에 등록 |
| `application(_:didFailToRegisterForRemoteNotificationsWithError:)` | APNs 등록 실패 시 노티플라이에 알림 |

> [!NOTE]
>
> `projectId`, `username`은 설정 페이지에서 확인할 수 있습니다. `password`는 과거 호환용 placeholder이므로 실제 비밀번호나 API Secret Key를 입력하지 말고, `username`과 동일한 비어 있지 않은 값을 전달하세요.

```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`는 과거 호환용 placeholder입니다. 실제 비밀번호나 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 */
}

```

앱 푸시 알림 트래픽을 노티플라이에 전달하기 위해 `UNUserNotificationCenterDelegate` 프로토콜에 다음 코드를 추가합니다.

| 함수 이름 | 설명 |
| - | - |
| `userNotificationCenter(_:willPresent:withCompletionHandler:)` | 포그라운드 알림 표시 |
| `userNotificationCenter(_:didReceive:withCompletionHandler:)` | 앱 푸시 알림 클릭 이벤트 전달 |

```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. 유저 정보 등록

노티플라이는 유저 식별자(`userId`)와 유저 프로퍼티(`params`)를 기반으로 개인화 마케팅 캠페인을 수행합니다.\
등록된 유저 정보는 세그먼트 분류, 푸시 발송, 이메일 및 카카오 알림톡 등의 타깃팅에 활용됩니다.

### 1. 유저 ID 등록 (`Notifly.setUserId()`)

`userId`는 앱 내부의 로그인 유저 식별자와 매핑됩니다.\
노티플라이는 이 값을 기준으로 유저 이벤트를 추적하고 캠페인을 개인화합니다.

### Parameters

**userId** `String`

로그인 유저 ID. 로그아웃 시 `nil`로 설정하여 해제

```js theme={null}
notifly.setUserId(userId);
```

#### 유저 ID 해제

로그아웃 시에는 `setUserId(null)`을 호출하여 유저 등록을 해제하는 것이 권장됩니다. 이 호출은 현재 기기와 유저 간 연결을 해제합니다.
따라서, 동일한 유저 데이터를 유지하려면 서버 또는 앱 내부에서 별도로 관리해야 합니다.

> [tab] iOS
>
> ```swift title="setUserId" highlight={4, 7} theme={null}
> import notifly_sdk
>
> // userId 등록
> Notifly.setUserId(userId: "exampleUserId")
>
> // userId 등록 해지
> Notifly.setUserId(userId: nil)
> ```

### 2. 유저 프로퍼티 등록

`setUserProperties`는 유저의 속성 정보를 등록합니다.\
이 정보는 **세그먼트 타깃팅**, **메시지 개인화**, **발송 채널 선택** 등에 사용됩니다.

> [!NOTE]
>
> **민감한 유저 속성을 전송하기 전에**
>
> 이름이나 주소처럼 보호가 필요한 커스텀 유저 속성은 데이터를 보내기 전에 콘솔의 **유저 리스트 > 속성 관리**에서 전송할 키와 같은 이름으로 등록하고 암호화를 활성화해 주세요.
>
> 설정 방법과 사용 시 제약은 [속성 관리 가이드](https://docs.notifly.tech/ko/user-guide/users/properties.md)를 확인해 주세요.

```swift theme={null}
notifly.setUserProperties(params);
```

### Parameters

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

유저 속성 key-value 쌍. `$email`, `$phone_number`, `$line_user_id` 등 사전 정의된 키 지원

> [!NOTE]
>
> * `$email` : 이메일 캠페인용 주소
> * `$phone_number` : 문자/카카오 캠페인용 전화번호
> * `$line_user_id` : LINE 메시지 캠페인용 LINE User ID
> * 기타 커스텀 필드: `"plan"`, `"tier"`, `"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. 이벤트 로깅

유저 행동을 기록하여 **캠페인 트리거**, **세그먼트 조건**, **성과 분석** 등에 활용할 수 있습니다.\
예를 들어 버튼 클릭, 페이지 진입, 구매 완료 같은 유저 행동을 이벤트로 수집합니다.

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

### Parameters

**eventName** `String` *required*

이벤트 이름 (예: "ticket\_purchase")

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

이벤트에 대한 추가 속성. (예: "ticket\_name": "premium", "duration": 120)

**segmentationEventParamKeys** `[String]`

세그먼트 분류 시 기준으로 사용할 키 목록 (최대 1개까지 지원)

> [!NOTE]
>
> `segmentationEventParamKeys`를 활용하여 이벤트 변수 (eventParams)를 발송 대상 설정 등에 활용할 수 있습니다. **최대 1개의 Key**만 지정할 수 있습니다.

> [tab] Swift
>
> ```swift title="trackEvent" highlight={5, 17-25} theme={null}
> import notifly_sdk
>
> ...
>     Button(action: {
>         Notifly.trackEvent(eventName: "click_button_1")
>     }) {
>     Text("버튼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("티켓 구매하기")
>         .padding(5)
>         .background(Color.black)
>         .foregroundColor(.white)
>         .cornerRadius(10)
>     }
> ...
> ```

## 6. 내부 유저 ID 확인

`getNotiflyUserId()` 메서드는 노티플라이가 내부적으로 관리하는 고유 User ID를 반환합니다.\
이는 `setUserId()` 로 등록한 유저 ID와는 **별개의 식별자**이며, 일반적인 상황에서는 사용할 필요가 없습니다.\
다만 외부 CRM 또는 서드파티 서비스와의 연동 과정에서 내부 User ID 값이 필요한 경우 활용할 수 있습니다.

```kotlin theme={null}
Notifly.getNotiflyUserId(context)
```

## 7. (권장) iOS Notification Service Extension 설정

> [!NOTE]
>
> `notifly-sdk` 버전 1.3.0 이상부터 지원됩니다.

Notification Service Extension을 설정하면 리치 푸시(Rich Push) 기능을 사용할 수 있습니다. 노티플라이의 [Push Extension 가이드](https://docs.notifly.tech/ko/advanced/rich-push-notification.md)를 참고해 설정하세요.

#### 주요 기능

1. 푸시 알림에 이미지 및 비디오 첨부 가능
2. 유저의 푸시 수신 여부를 추적하여 캠페인 성과를 세부적으로 분석 가능

> [!WARNING]
>
> Notification Service Extension 설정을 하지 않아도 SDK는 정상 동작하지만, 리치 푸시 및 수신 트래킹은 사용할 수 없습니다.

## 8. 연동 테스트

SDK 설치 후 아래 페이지에서 실제 이벤트 및 푸시 수신 여부를 테스트하세요.\
👉 [SDK 연동 테스트](https://docs.notifly.tech/ko/integration-test.md)

## 9. 심화 연동

> [card] [푸시 알림 사전 동의](https://docs.notifly.tech/ko/advanced/push-notification-consent.md)

> [card] [인앱 팝업 이벤트 리스너](https://docs.notifly.tech/ko/advanced/inapp-popup-event-listener.md)

> [card] [리치 푸시 알림](https://docs.notifly.tech/ko/advanced/rich-push-notification.md)

## FAQ

> [accordion] 이미 Firebase Cloud Messaging을 사용 중인데 어떻게 해야 할까요?
>
> 노티플라이 Android SDK는 기존 앱에서 사용하고 있을 수 있는 Firebase Cloud Messaging과 함께 사용하실 수 있습니다.

> [accordion] SwiftUI 프로젝트에서 푸시 알림 토큰이 전달되지 않거나 인앱 팝업이 작동하지 않습니다.
>
> SwiftUI 환경에서 Firebase SDK의 method swizzling이 delegate 메서드를 올바르게 전달하지 못할 수 있습니다.
> ([관련 이슈: firebase-ios-sdk#7473](https://github.com/firebase/firebase-ios-sdk/issues/7473))
>
> Info.plist에 `FirebaseAppDelegateProxyEnabled`를 `NO`(Boolean)로 설정하여 swizzling을 비활성화하세요.
>
> ```xml title="Info.plist" theme={null}
> <key>FirebaseAppDelegateProxyEnabled</key>
> <false/>
> ```
>
> Swizzling 비활성화 후에는 APNs 토큰을 Firebase에 수동으로 전달해야 합니다:
>
> ```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.