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

# React Native

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

Notifly React Native SDKは、React NativeアプリにNotiflyを組み込むためのSDKです。
次の機能を利用できます。

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

## 始める前に

SDKをインストールする前に、次の手順を完了してください。

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-認証キーを登録する)

> [!NOTE]
>
> * iOSで正常にビルドするには、必ず`.xcworkspace`ファイルをXcodeで開いてください。

## 1. SDKをインストールする

### パッケージをインストールする

[npmのnotifly-sdk](https://www.npmjs.com/package/notifly-sdk)をインストールします。

最新バージョンは次のとおりです。[![Npm](https://img.shields.io/npm/v/notifly-sdk.svg)](https://www.npmjs.com/package/notifly-sdk)

> [tab] npm
>
> ```shell theme={null}
> npm install notifly-sdk@latest --save
> cd ios && pod install
> ```

> [tab] yarn
>
> ```shell theme={null}
> yarn add notifly-sdk@latest
> cd ios && pod install
> ```

> [!NOTE]
>
> `package.json`に`notifly-sdk`が追加されます。

### iOSを設定する

#### 1. Capabilityを設定する

1. Xcodeで`{Your_Project_Name}.xcworkspace`を開きます。`.xcodeproj`ではNotifly SDKを使用できません。

2. Xcodeで、iOS Deployment TargetまたはMinimum Deploymentsを15.0以降に設定します。`Podfile`にも同じバージョンを指定します。

3. **Push Notifications**と**Background Modes**を有効にし、**Remote notifications**と**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. `AppDelegate.mm`を設定する

1. ファイルの場所を確認する

`AppDelegate.mm`は次のパスにあります。

```
ios/{ProjectName}/AppDelegate.mm
```

2. `notifly_sdk`をインポートする

```JavaScript theme={null}
#import "notifly_sdk-Swift.h"
```

3. `UNUserNotificationCenterDelegate`プロトコルを追加する

`AppDelegate.h`で、`AppDelegate`クラスが`UNUserNotificationCenterDelegate`を実装するように変更します。

> [tab] AppDelegate.h
>
> ```swift title="ヘッダー" theme={null}
> #import <RCTAppDelegate.h>
> #import <UIKit/UIKit.h>
> #import <UserNotifications/UNUserNotificationCenter.h>
>
> @interface AppDelegate : RCTAppDelegate <UNUserNotificationCenterDelegate>
>
> @end
> ```

4. `AppDelegate`のメソッドを変更する

`AppDelegate.mm`のメソッドに、Notifly連携用のコードを追加します。

| メソッド名 | 説明 |
| - | - |
| `application:didFinishLaunchingWithOptions:` | Firebaseを初期化し、Notification Centerのdelegateを設定します。 |
| `application:didRegisterForRemoteNotificationsWithDeviceToken:` | APNsトークンをNotiflyに登録します。 |
| `application:didFailToRegisterForRemoteNotificationsWithError:` | APNsへの登録に失敗した場合、Notiflyに通知します。 |
| `userNotificationCenter:didReceiveNotificationResponse:` | プッシュ通知のクリックイベントを渡します。 |
| `userNotificationCenter:willPresentNotification:` | フォアグラウンドでのプッシュ通知の表示を処理します。 |

> [tab] AppDelegate.mm
>
> ```swift title="AppDelegate.mm" theme={null}
> #import <Firebase.h>
> #import <React/RCTBundleURLProvider.h>
> #import "AppDelegate.h"
> #import "notifly_sdk-Swift.h"
>
> @implementation AppDelegate
>
> - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
>     /* Your Code */
>     [FIRApp configure];
>     UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
>     center.delegate = self;
>     [[UIApplication sharedApplication] registerForRemoteNotifications];
>     /* Your Code */
> }
>
> - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
>     /* Your Code */
>     [Notifly application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
>     /* Your Code */
> }
>
> - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
>     /* Your Code */
>     [Notifly application:application didFailToRegisterForRemoteNotificationsWithError:error];
>     /* Your Code */
> }
>
> - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
>     /* Your Code */
>     [Notifly userNotificationCenter:center didReceive:response];
>     completionHandler();
>     /* Your Code */
> }
>
> - (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
>     /* Your Code */
>    [Notifly userNotificationCenter:center willPresent:notification withCompletionHandler:completionHandler];
>     /* Your Code */
> }
>
> /* Your Code */
> @end
> ```

### iOS Notification Service Extensionを設定する（推奨）

> [!NOTE]
>
> `notifly-sdk` 1.3.0以降で利用できます。

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

#### 主な機能

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

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

### 初期化コードを追加する

アプリのエントリーポイント（`index.js`または`App.js`）に初期化コードを追加します。

```js title="index.js" highlight={2, 6} theme={null}
...
import notifly from 'notifly-sdk';

/* Your Code */

notifly.initialize({
  projectId: 'myProjectId',
  username: 'myUserName',
  // `password`は後方互換性のためのプレースホルダーです。実際のパスワードやAPI Secret Keyを入力しないでください。
  password: 'myUserName',
});

/* Your Code */

AppRegistry.registerComponent(...);
```

> [!NOTE]
>
> `projectId`と`username`は設定ページで確認できます。`password`は後方互換性のためのプレースホルダーです。実際のパスワードやAPI Secret Keyは入力せず、`username`と同じ空でない値を渡してください。

***

## 2. ユーザー情報を登録する

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

### 1. ユーザーIDを設定する（`Notifly.setUserId()`）

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

### パラメーター

**userId** `String` *required*

ログインしているユーザーのIDです。ログアウト時は`null`を設定して解除します。

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

#### ユーザーIDを解除する

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

> [tab] JavaScript
>
> ```JavaScript title="setUserId" theme={null}
> const handleLogin = () => {
>     ...
>     notifly.setUserId('example_user_id'); // ユーザーIDを設定します。
>     ...
> }
>
> const handleLogout = () => {
>     ...
>     notifly.setUserId(); // ユーザーIDを解除します。
>     ...
> }
> ```

### 2. ユーザー属性を設定する

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

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

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

**param** `Object` *required*

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

> [!NOTE]
>
> * `$email`はメールキャンペーン用のアドレスです。
> * `$phone_number`はSMSやカカオのキャンペーンに使用する電話番号です。
> * `$line_user_id`はLINEメッセージキャンペーン用のLINEユーザーIDです。
> * `"plan"`、`"tier"`、`"country"`などのカスタムフィールドも自由に設定できます。

> [tab] JavaScript
>
> ```js title="setUserProperties" theme={null}
> const handleRejectPushNotification = () => {
>     ...
>     notifly.setUserProperties({
>         "push_subscription_channel1": false,
>         "push_subscription_channel2": false,
>         "push_subscription_channel3": false,
>     });
>     ...
> }
> ```

***

## 3. イベントを記録する

ユーザーの行動を記録し、**キャンペーンのトリガー**、**セグメント条件**、**効果分析**などに利用できます。\
たとえば、ボタンのクリック、ページへのアクセス、購入完了などの行動をイベントとして収集します。

```js theme={null}
notifly.trackEvent(eventName, eventParams, segmentationEventParamKeys);
```

### パラメーター

**eventName** `String` *required*

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

**eventParams** `Object`

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

**segmentationEventParamKeys** `List\<String\>`

セグメント分けの基準に使用するキーのリストです。指定できるキーは最大1つです。

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

> [tab] JavaScript
>
> ```js title="trackEvent" theme={null}
> const handlePurchaseTicket = () => {
>     ...
>     notifly.trackEvent(
>       "ticket_purchase",
>       {
>         "show_id": "sample_show_id",
>         "performance_start_time": 1674104659
>       },
>       ["show_id"]
>     );
>     ...
> }
>
> const handleLogin = () => {
>     ...
>     notifly.trackEvent("login");
>     ...
> }
> ```

***

## 4. 連携をテストする

SDKのインストール後、以下のページで実際のイベント収集とプッシュ通知の受信をテストしてください。\
[連携をテストする](https://docs.notifly.tech/ja/integration-test.md)

## 5. 高度な連携

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

> [card] [プッシュ通知のクリックイベントを購読する](https://docs.notifly.tech/ja/advanced/push-notification-click-events.md)

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

## よくある質問

> [accordion] すでにFirebase Cloud Messagingを使用している場合も利用できますか？
>
> Notifly Android SDKは、既存のアプリで使用しているFirebase Cloud Messagingと併用できます。

> [accordion] ビルド時にAppDelegate.mmでNotiflyクラスに関するエラーが発生します。
>
> Podfileに`use_frameworks! :linkage => :static`を追加して、静的リンクを試してください。すでに`use_frameworks!`がある場合は、`:linkage => :static`オプションのみを追加します。

> [accordion] iOSでアプリがフォアグラウンドにあるときにプッシュ通知が表示されません。
>
> すでにFirebase Messagingを使用している場合は、以下の手順に従って`firebase.json`を設定してください。
>
> [React Native FirebaseのForeground Presentation Optionsガイド](https://rnfirebase.io/messaging/usage#foreground-presentation-options-ios)に従い、`firebase.json`に次のコードを追加します。
>
> ```json theme={null}
> {
>   "react-native": {
>     "messaging_ios_foreground_presentation_options": [
>       "badge",
>       "sound",
>       "list",
>       "banner"
>     ]
>   }
> }
> ```

> [accordion] `notifly_sdk-Swift.h`が見つからないというエラーが発生します。
>
> * iOSの`notifly_sdk`はSwiftで記述されています。Objective-Cから利用できるように、ビルド時にSwift互換ヘッダー`notifly_sdk-Swift.h`が生成されます。ビルド対象のターゲットのビルド設定で、**Header Search Paths**に`"${PODS_CONFIGURATION_BUILD_DIR}"`を追加してください。
> * [SwiftをObjective-Cから利用する](https://developer.apple.com/documentation/swift/importing-swift-into-objective-c)


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