# React Native SDK 기본 통합 가이드

이 섹션에서는 Pushwoosh React Native SDK를 애플리케이션에 통합하는 방법에 대한 정보를 제공합니다.

## 사전 요구 사항

Pushwoosh React Native SDK를 앱에 통합하려면 다음이 필요합니다:

<Aside type="note" title="요구 사항">
 - [Pushwoosh 계정](https://sso.pushwoosh.com/login).
 - 계정에 설정된 [Pushwoosh 프로젝트](/ko/product/first-steps/start-with-your-project/create-your-project).
 - **iOS 통합의 경우:**
    - 푸시 알림을 보내도록 구성된 iOS 플랫폼. 가장 간단한 방법으로 [토큰 기반 인증 구성](/ko/developer/first-steps/connect-messaging-services/ios-configuration/ios-token-based-configuration/)을 사용하는 것을 권장합니다.
    - 시뮬레이터로 푸시를 보내려면 게이트웨이를 `Sandbox`로 설정하세요.
 - **Android 통합의 경우:**
    - [구성된 Android 플랫폼](/ko/developer/first-steps/connect-messaging-services/android-configuration/android-firebase-configuration)
    - Firebase 프로젝트의 `google-services.json` 파일 및 `패키지 이름`.
    - Android 애플리케이션에 연결된 Firebase 프로젝트. 필요한 경우 [Firebase 설정 가이드](https://firebase.google.com/docs/android/setup#manually_add_firebase)를 따르세요.
 - 애플리케이션의 Pushwoosh 제어판에서 받은 `Pushwoosh 애플리케이션 코드` 및 [Pushwoosh Device API 토큰](/ko/developer/api-reference/api-access-token/#device-api-token).
</Aside>

## 통합 단계

### 1. Pushwoosh React Native SDK 의존성 추가

프로젝트에 Pushwoosh React Native SDK 의존성을 추가합니다:

```bash
npm install pushwoosh-react-native-plugin --save
```

### 2. React Native SDK 초기화

`index.js` 파일의 루트 컴포넌트에서:
- `pushwoosh-react-native-plugin`을 가져옵니다.
- Pushwoosh SDK를 초기화합니다.
- 초기화 로직에서 `register()`를 호출하여 푸시 알림을 등록합니다.

```javascript title="index.js"
import Pushwoosh from 'pushwoosh-react-native-plugin';

AppRegistry.registerComponent(appName, () => App);

Pushwoosh.init({
    "pw_appid" : "__YOUR_APP_ID__"
});

Pushwoosh.register();
```

여기서:
- `__YOUR_APP_ID__`는 Pushwoosh 제어판의 애플리케이션 코드입니다.


### 3. iOS 네이티브 설정

#### 3.1 기능(Capabilities)

프로젝트에서 푸시 알림을 활성화하려면 특정 기능을 추가해야 합니다.

서명 및 기능(Signing & Capabilities) 섹션에서 다음 기능을 추가합니다:
- `푸시 알림(Push Notifications)`
- `백그라운드 모드(Background Modes)`. 이 기능을 추가한 후 `원격 알림(Remote notifications)` 확인란을 선택합니다.

긴급 알림(Time Sensitive Notifications, iOS 15 이상)을 사용하려는 경우 `긴급 알림(Time Sensitive Notifications)` 기능도 추가하세요.

#### 3.2 Info.plist

`Runner/Info.plist`에서 `__PUSHWOOSH_DEVICE_API_TOKEN__` 키를 [Pushwoosh Device API 토큰](/ko/developer/api-reference/api-access-token/#device-api-token)으로 설정합니다:
```swift title="info.plist"
<key>Pushwoosh_API_TOKEN</key>
<string>__PUSHWOOSH_DEVICE_API_TOKEN__</string>
```

#### 3.3 메시지 전송 추적

프로젝트에 알림 서비스 확장(Notification Service Extension) 타겟을 추가해야 합니다. 이는 정확한 전송 추적 및 iOS의 리치 미디어와 같은 기능에 필수적입니다.

[네이티브 가이드의 단계](/ko/developer/pushwoosh-sdk/ios-sdk/setting-up-pushwoosh-ios-sdk/basic-integration-guide/#4-message-delivery-tracking)에 따라 확장 타겟과 그 안에 필요한 Pushwoosh 코드를 추가하세요.

#### 3.4 iOS React Native 프로젝트의 의존성 설치

iOS React Native 프로젝트의 의존성을 설치하려면 터미널에서 `ios` 폴더로 이동하여 다음을 실행합니다:

```bash
pod install --repo-update
```

### 4. Android 네이티브 설정

#### 4.1 의존성 설치

필요한 의존성과 플러그인이 Gradle 스크립트에 추가되었는지 확인하세요:

프로젝트 수준의 `build.gradle` 의존성에 Google Services Gradle 플러그인을 추가합니다:

```groovy title="android/build.gradle"
buildscript {
  dependencies {
    classpath 'com.google.gms:google-services:4.3.15'
  }
}
```

앱 수준의 `build.gradle` 파일에 플러그인을 적용합니다:

```groovy title="app/build.gradle"
apply plugin: 'com.google.gms.google-services'
```

#### 4.2 Firebase 구성 파일 추가

프로젝트 디렉토리의 `android/app` 폴더에 `google-services.json` 파일을 넣습니다.

#### 4.3 Pushwoosh 메타데이터 추가

`main/AndroidManifest.xml`의 `<application>` 태그 안에 [Pushwoosh Device API 토큰](/ko/developer/api-reference/api-access-token/#device-api-token)을 추가합니다:

```xml title="AndroidManifest.xml"
<meta-data android:name="com.pushwoosh.apitoken" android:value="__YOUR_DEVICE_API_TOKEN__" />
```

> **중요:** Pushwoosh 제어판에서 토큰이 올바른 앱에 접근할 수 있도록 권한을 부여해야 합니다. [자세히 알아보기](/ko/developer/api-reference/api-access-token/#edit-token)

### 5. 프로젝트 실행

1. 프로젝트를 빌드하고 실행합니다.
2. Pushwoosh 제어판으로 이동하여 [푸시 알림을 보냅니다](/ko/product/messaging-channels/push-notifications/send-push-notifications/one-time-push).
3. 앱에서 알림을 볼 수 있어야 합니다.

## 확장 통합

이 단계에서는 이미 SDK를 통합하여 푸시 알림을 보내고 받을 수 있습니다. 이제 핵심 기능을 살펴보겠습니다.

### 푸시 알림 이벤트 리스너

Pushwoosh SDK에는 푸시 알림 처리를 위해 설계된 두 개의 이벤트 리스너가 있습니다:

- `pushReceived` 이벤트는 푸시 알림을 수신했을 때 트리거됩니다.
- `pushOpened` 이벤트는 사용자가 알림을 열었을 때 트리거됩니다.

애플리케이션 시작 시 SDK 초기화 직후에 이러한 이벤트 리스너를 설정해야 합니다:

```javascript
import {DeviceEventEmitter} from 'react-native'
import Pushwoosh from 'pushwoosh-react-native-plugin';

class PushwooshNotificationHandler {
  setupPushListeners() {

    DeviceEventEmitter.addListener('pushReceived', (e) => {
      console.warn("Push received: " + JSON.stringify(e));
    });

    DeviceEventEmitter.addListener('pushOpened', (e) => {
      console.warn("Push accepted: " + JSON.stringify(e));
    });

  }
}
```

### 사용자 구성

개별 사용자 행동 및 선호도에 집중함으로써 개인화된 콘텐츠를 제공하여 사용자 만족도와 충성도를 높일 수 있습니다.

```javascript
import Pushwoosh from 'pushwoosh-react-native-plugin';

class Registration {
  afterUserLogin(user: User) {

    // 사용자 ID 설정
    Pushwoosh.setUserId(user.getId());

    // 사용자 이메일 설정
    Pushwoosh.setEmails(user.getEmailList());

    // 사용자 SMS 번호 설정
    Pushwoosh.registerSMSNumber(user.getPhoneNumber());

    // 사용자 WhatsApp 번호 설정
    Pushwoosh.registerWhatsappNumber(user.getWhatsAppNumber());

    // Pushwoosh 태그로 추가 사용자 정보 설정
    Pushwoosh.setTags({
      "age": user.getAge(),
      "name": user.getName(),
      "last_login": user.getLastLoginDate()
    });
  }
}
```

### 태그

태그는 사용자나 기기에 할당된 키-값 쌍으로, 선호도나 행동과 같은 속성을 기반으로 세분화를 가능하게 하여 타겟 메시징을 할 수 있습니다.

```javascript
import Pushwoosh from 'pushwoosh-react-native-plugin';

class UpdateUser {
  afterUserUpdateProfile(user: User) {

    // 선호 카테고리 목록 설정
    Pushwoosh.setTags({
      "favorite_categories": user.getFavoriteCategoriesList()
    });

    // 결제 정보 설정
    Pushwoosh.setTags({
      "is_subscribed": user.isSubscribed(),
      "payment_status": user.getPaymentStatus(),
      "billing_address": user.getBillingAddress()
    });
  }
}
```

### 이벤트

이벤트는 앱 내에서 발생하는 특정 사용자 행동이나 사건으로, 행동을 분석하고 해당 메시지나 작업을 트리거하기 위해 추적할 수 있습니다.

```javascript
import Pushwoosh from 'pushwoosh-react-native-plugin';

class Registration {

  // 로그인 이벤트 추적
  afterUserLogin(user: User) {
    Pushwoosh.postEvent("login", {
      "name": user.getName(),
      "last_login": user.getLastLoginDate()
    });
  }

  // 구매 이벤트 추적
  afterUserPurchase(product: Product) {
    Pushwoosh.postEvent("purchase", {
      "product_id": product.getId(),
      "product_name": product.getName(),
      "price": product.getPrice(),
      "quantity": product.getQuantity()
    });
  }
}
```

## 문제 해결

통합 과정에서 문제가 발생하면 [지원 및 커뮤니티](/ko/developer/pushwoosh-sdk/support-and-community) 섹션을 참조하세요.