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

> Notifly iOS SDKのインストール、AppDelegateの設定、プッシュ通知の連携方法を説明します。

Notifly iOS SDKは、iOSアプリにNotiflyを組み込むためのSDKです。\
次の機能に対応しています。

* デバイス情報をNotiflyに登録し、プッシュ通知を受信したり、アプリ内ポップアップを表示したりできます。
  （アプリ内ポップアップは、アプリがフォアグラウンドのときにのみ表示されます。）
* イベントとユーザー情報をNotiflyに送信し、キャンペーンのターゲティングと分析に使用できます。
* ユーザー行動をイベントとして記録し、キャンペーンの効果を測定できます。

## 事前準備

1. **Firebaseプロジェクトを連携します。**\
   Notifly iOS SDKは、プッシュ通知の送信に[Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging)を使用します。

> [Firebaseプロジェクトの連携ガイド](https://docs.notifly.tech/ja/developer-guide/firebase-integration.md)

2. **iOSのAPNs認証情報を登録します。**

> [APNs認証情報の登録](https://docs.notifly.tech/ja/developer-guide/firebase-integration.md#1-3-apns-認証キーを登録する)

***

## 1. iOSの設定

### 1. Capabilityの設定

1. Xcodeでターゲットの最小デプロイバージョンをiOS 15.0以降に設定します。CocoaPodsを使う場合は、`Podfile`にも同じバージョンを設定します。

2. **Push Notifications**と**Background Modes**を有効にします。**Background Modes**では、**Remote notifications**と**Background fetch**を有効にしてください。

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

   ![Capabilityの追加](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のインストール

Notifly iOS SDKは、CocoaPodsまたはSwift Package Managerでインストールできます。

> [tab] CocoaPods
>
> 1. XcodeプロジェクトにCocoaPodsが設定されていることを確認します。
>    未設定の場合は、[CocoaPodsの導入ガイド](https://guides.cocoapods.org/using/getting-started.html)を確認してください。
> 2. Podfileの先頭に`platform :ios, '15.0'`を追加します。15.0より新しいiOSバージョンも指定できます。
> 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パッケージの依存関係を追加できることを確認します。
>    手順については、[Xcodeでパッケージの依存関係を追加するガイド](https://developer.apple.com/documentation/xcode/adding_package_dependencies_to_your_app)を確認してください。
> 2. プロジェクトの設定で**Package Dependencies**を開き、「+」をクリックします。
> 3. 次のURLを入力し、**Next**をクリックします。
>    ```
>    https://github.com/team-michael/notifly-ios-sdk
>    ```
> 4. **Add Package**をクリックします。

## 3. AppDelegateの設定

Notifly 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の設定

`AppDelegate.swift`に次のインポートを追加します。

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

SDKの初期化とAPNsの登録を処理するため、`AppDelegate.swift`の`UIApplicationDelegate`メソッドにNotiflyの呼び出しを追加します。

| メソッド | 説明 |
| - | - |
| `application(_:didFinishLaunchingWithOptions:)` | FirebaseとNotifly SDKを初期化します。 |
| `application(_:didRegisterForRemoteNotificationsWithDeviceToken:)` | APNsトークンをNotiflyに登録します。 |
| `application(_:didFailToRegisterForRemoteNotificationsWithError:)` | APNsの登録に失敗したことをNotiflyに通知します。 |

> [!NOTE]
>
> `projectId`と`username`は設定ページで確認できます。`password`は後方互換性のためのプレースホルダーです。`username`と同じ空でない値を渡してください。実際のパスワードや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() // Firebase SDKをまだ初期化していない場合。
        // `password`は後方互換性のためのプレースホルダーです。実際のパスワードや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 */
}

```

プッシュ通知のイベントをNotiflyに転送するため、次の`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 */
}

// UNUserNotificationCenterDelegateプロトコルに準拠するAppDelegateの拡張。
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. ユーザー情報の登録

Notiflyは、ユーザー識別子（`userId`）とユーザー属性（`params`）を使って、マーケティングキャンペーンをパーソナライズします。\
登録したユーザー情報は、セグメントの分類や、プッシュ通知、メール、カカオアリムトークなどの配信対象の設定に使用されます。

### 1. ユーザーIDの登録（`Notifly.setUserId()`）

`userId`には、アプリ内でログインしているユーザーの識別子を設定します。\
Notiflyは、この値を使ってユーザーのイベントを追跡し、キャンペーンをパーソナライズします。

### パラメーター

**userId** `String`

ログインしているユーザーのIDです。ログアウト時に`nil`を渡すと、関連付けが解除されます。

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

#### ユーザーIDの解除

ログアウト時には、`Notifly.setUserId(userId: nil)`を呼び出して、現在のデバイスとユーザーの関連付けを解除することを推奨します。
同じユーザーデータを保持する必要がある場合は、サーバーまたはアプリ内で別途管理してください。

> [tab] iOS
>
> ```swift title="setUserId" highlight={4, 7} theme={null}
> import notifly_sdk
>
> // ユーザーIDを登録します。
> Notifly.setUserId(userId: "exampleUserId")
>
> // ユーザーIDを解除します。
> Notifly.setUserId(userId: nil)
> ```

### 2. ユーザー属性の登録

`setUserProperties`で、ユーザーの属性情報を登録します。\
登録した情報は、**セグメントのターゲティング**、**メッセージのパーソナライズ**、**配信チャネルの選択**などに使用されます。

> [!NOTE]
>
> **機密性の高いユーザー属性を送信する前に**
>
> 氏名や住所など、保護が必要なカスタムユーザー属性を送信する前に、コンソールの**ユーザー管理** > **ユーザー一覧**の**属性管理**で、送信するキーと同じ名前の属性を登録し、暗号化を有効にしてください。
>
> 設定方法と利用上の制約については、[属性管理ガイド](https://docs.notifly.tech/ja/user-guide/users/properties.md)を確認してください。

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

### パラメーター

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

ユーザー属性のキーと値のペアです。`$email`、`$phone_number`、`$line_user_id`などの定義済みキーを使用できます。

> [!NOTE]
>
> * `$email`: メールキャンペーンに使用するメールアドレスです。
> * `$phone_number`: SMSやカカオのキャンペーンに使用する電話番号です。
> * `$line_user_id`: LINEメッセージキャンペーンに使用するLINEユーザー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: eventName,
    eventParams: eventParams,
    segmentationEventParamKeys: segmentationEventParamKeys
)
```

### パラメーター

**eventName** `String` *required*

イベント名です。たとえば、`"ticket_purchase"`を指定します。

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

イベントに付加するパラメーターです。たとえば、`"ticket_name": "premium"`や`"duration": 120`を指定できます。

**segmentationEventParamKeys** `[String]`

セグメントの分類に使用するイベントパラメーターキーのリストです。指定できるキーは最大1つです。

> [!NOTE]
>
> `segmentationEventParamKeys`を指定すると、イベントパラメーター（`eventParams`）を配信対象の設定などに使用できます。指定できるキーは**最大1つ**です。

> [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()`は、Notiflyが内部で管理する一意のユーザーIDを返します。\
このIDは、`setUserId()`で登録するユーザーIDとは**別の識別子**です。通常の連携では使用する必要はありません。\
外部CRMやサードパーティーサービスとの連携で、Notiflyの内部ユーザーIDが必要な場合に使用します。

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

## 7. iOS Notification Service Extensionの設定（推奨）

> [!NOTE]
>
> `notifly-sdk`バージョン1.3.0以降で利用できます。

Notification Service Extensionを設定すると、リッチプッシュ通知を利用できます。[Push Extensionガイド](https://docs.notifly.tech/ja/advanced/rich-push-notification.md)に沿って設定してください。

#### 主な機能

1. プッシュ通知に画像や動画を添付できます。
2. プッシュ通知の受信状況を追跡し、キャンペーンの効果を詳しく分析できます。

> [!WARNING]
>
> Notification Service Extensionを設定しなくてもSDKは動作しますが、リッチプッシュ通知と受信トラッキングは利用できません。

## 8. 連携テスト

SDKのインストール後、連携テストガイドに沿って、イベントの収集とプッシュ通知の受信を確認してください。\
[連携をテストする](https://docs.notifly.tech/ja/integration-test.md)

## 9. 高度な連携

> [card] [プッシュ通知の許可をリクエストする](https://docs.notifly.tech/ja/advanced/push-notification-consent.md)

> [card] [アプリ内ポップアップのイベントリスナー](https://docs.notifly.tech/ja/advanced/inapp-popup-event-listener.md)

> [card] [リッチプッシュ通知](https://docs.notifly.tech/ja/advanced/rich-push-notification.md)

## FAQ

> [accordion] すでにFirebase Cloud Messagingを使用している場合はどうすればよいですか？
>
> Notifly iOS SDKは、アプリで使用中のFirebase Cloud Messagingと併用できます。

> [accordion] SwiftUIプロジェクトでプッシュ通知のトークンが転送されない、またはアプリ内ポップアップが動作しません。
>
> SwiftUI環境では、Firebase SDKのメソッドスウィズリングによって、delegateメソッドの呼び出しが正しく転送されない場合があります。
> （[関連するIssue: firebase-ios-sdk#7473](https://github.com/firebase/firebase-ios-sdk/issues/7473)）
>
> Info.plistで`FirebaseAppDelegateProxyEnabled`をBoolean型の`NO`に設定し、スウィズリングを無効にしてください。
>
> ```xml title="Info.plist" theme={null}
> <key>FirebaseAppDelegateProxyEnabled</key>
> <false/>
> ```
>
> スウィズリングを無効にした後は、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.