# Unity SDK 기본 통합 가이드

이 가이드는 Pushwoosh Unity SDK를 애플리케이션에 통합하는 과정을 안내합니다.

## 전제 조건

<Aside type="note" title="요구 사항">
 - [Pushwoosh 계정](https://sso.pushwoosh.com/login).
 - 계정에 설정된 [Pushwoosh 프로젝트](/ko/product/first-steps/start-with-your-project/create-your-project).
 - Unity 2021.3 이상.
 - **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 프로젝트의 `project number`(Sender ID라고도 함), `google-services.json` 파일 및 `package name`.
    - Android 애플리케이션에 연결된 Firebase 프로젝트. 필요한 경우 [Firebase 설정 가이드](https://firebase.google.com/docs/android/setup#manually_add_firebase)를 따르세요.
 - Pushwoosh 제어판의 `Pushwoosh Application Code` 및 [Pushwoosh Device API Token](/ko/developer/api-reference/api-access-token/#device-api-token).
</Aside>

## 통합 단계

### 1. Pushwoosh Unity SDK 추가

<Tabs>
  <TabItem label="UPM (Scoped Registry 사용, 권장)">

`Packages/manifest.json`에 다음을 추가하세요:

```json title="Packages/manifest.json"
{
  "dependencies": {
    "com.pushwoosh.unity.core": "6.2.7",
    "com.pushwoosh.unity.android": "6.2.7",
    "com.pushwoosh.unity.ios": "6.2.7"
  },
  "scopedRegistries": [
    {
      "name": "npmjs",
      "url": "https://registry.npmjs.org",
      "scopes": ["com.pushwoosh"]
    }
  ]
}
```

필요한 플랫폼 패키지만 추가하세요. 예를 들어, iOS만 타겟팅하는 경우 `com.pushwoosh.unity.android`를 생략하세요.

  </TabItem>
  <TabItem label="UPM (Git URL 사용)">

Unity에서 **Window > Package Manager > + > Add package from git URL**로 이동하여 다음 URL을 하나씩 추가하세요:

```
https://github.com/Pushwoosh/pushwoosh-unity.git?path=com.pushwoosh.unity.core
https://github.com/Pushwoosh/pushwoosh-unity.git?path=com.pushwoosh.unity.android
https://github.com/Pushwoosh/pushwoosh-unity.git?path=com.pushwoosh.unity.ios
```

  </TabItem>
  <TabItem label=".unitypackage">

[GitHub Releases](https://github.com/Pushwoosh/pushwoosh-unity/releases)에서 `Pushwoosh.unitypackage`를 다운로드하고 **Assets > Import Package > Custom Package**를 통해 가져오세요.

  </TabItem>
</Tabs>

### 2. External Dependency Manager 설치

SDK는 네이티브 Android 및 iOS 종속성을 해결하기 위해 [External Dependency Manager for Unity (EDM4U)](https://github.com/googlesamples/unity-jar-resolver)가 필요합니다.

`Packages/manifest.json`에 다음 scoped registry를 추가하세요:

```json
{
  "scopedRegistries": [
    {
      "name": "package.openupm.com",
      "url": "https://package.openupm.com",
      "scopes": ["com.google.external-dependency-manager"]
    }
  ]
}
```

그런 다음 종속성에 패키지를 추가하세요:

```json
"com.google.external-dependency-manager": "1.2.183"
```

### 3. SDK 초기화

`PushNotificator.cs` 스크립트를 생성하고 씬의 모든 GameObject에 연결하세요:

```csharp title="PushNotificator.cs"
using UnityEngine;
using System.Collections.Generic;

public class PushNotificator : MonoBehaviour
{
    void Start()
    {
        Pushwoosh.ApplicationCode = "XXXXX-XXXXX";
        Pushwoosh.FcmProjectNumber = "XXXXXXXXXXXX";

        Pushwoosh.Instance.OnRegisteredForPushNotifications += (token) => {
            Debug.Log("Push token: " + token);
        };

        Pushwoosh.Instance.OnFailedToRegisteredForPushNotifications += (error) => {
            Debug.Log("Registration failed: " + error);
        };

        Pushwoosh.Instance.RegisterForPushNotifications();
    }
}
```

다음을 교체하세요:
- `XXXXX-XXXXX`를 Pushwoosh Application Code로.
- `XXXXXXXXXXXX`를 Firebase 프로젝트 번호로 (Android 전용).

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

#### 4.1 Capabilities

Unity에서 iOS 프로젝트를 빌드한 후, 생성된 Xcode 프로젝트를 열고 **Signing & Capabilities**에서 다음 capabilities를 추가하세요:

- **Push Notifications**
- **Background Modes**에서 **Remote notifications** 체크

Time Sensitive Notifications(iOS 15 이상)의 경우, **Time Sensitive Notifications** capability도 추가하세요.

#### 4.2 Info.plist

`Info.plist`에 [Pushwoosh Device API Token](/ko/developer/api-reference/api-access-token/#device-api-token)을 추가하세요:

```xml title="Info.plist"
<key>Pushwoosh_API_TOKEN</key>
<string>__PUSHWOOSH_DEVICE_API_TOKEN__</string>
```

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

Xcode 프로젝트에 Notification Service Extension 타겟을 추가하세요. 이는 iOS에서 정확한 전송 추적 및 Rich Media에 필요합니다.

[네이티브 가이드](/ko/developer/pushwoosh-sdk/ios-sdk/setting-up-pushwoosh-ios-sdk/basic-integration-guide/#4-message-delivery-tracking)에 따라 extension 타겟을 추가하세요.

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

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

`google-services.json` 파일을 Unity 프로젝트의 **Assets** 디렉토리에 넣으세요.

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

`Assets/Plugins/Android/AndroidManifest.xml`의 `<application>` 태그 내에 [Pushwoosh Device API Token](/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__" />
```

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

### 6. 프로젝트 실행

1. 대상 플랫폼에서 프로젝트를 빌드하고 실행하세요.
2. 메시지가 표시되면 푸시 알림 권한을 부여하세요.
3. Pushwoosh 제어판으로 이동하여 [푸시 알림을 보내세요](/ko/product/messaging-channels/push-notifications/send-push-notifications/one-time-push).

## 확장된 통합

이 단계에서는 푸시 알림을 보내고 받을 수 있습니다. 아래 섹션에서는 핵심 SDK 기능에 대해 설명합니다.

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

SDK는 푸시 알림 처리를 위한 두 가지 이벤트 리스너를 제공합니다:

- `OnPushNotificationsReceived` — 푸시 알림이 도착했을 때 트리거됩니다.
- `OnPushNotificationsOpened` — 사용자가 알림을 탭했을 때 트리거됩니다.

SDK 초기화 중에 이러한 리스너를 설정하세요:

```csharp title="PushNotificator.cs"
void Start()
{
    Pushwoosh.ApplicationCode = "XXXXX-XXXXX";
    Pushwoosh.FcmProjectNumber = "XXXXXXXXXXXX";

    Pushwoosh.Instance.OnPushNotificationsReceived += (payload) => {
        Debug.Log("Push received: " + payload);
    };

    Pushwoosh.Instance.OnPushNotificationsOpened += (payload) => {
        Debug.Log("Push opened: " + payload);
    };

    Pushwoosh.Instance.RegisterForPushNotifications();
}
```

### 사용자 구성

사용자를 식별하고 속성을 설정하여 푸시 알림을 개인화하세요:

```csharp
// 교차 기기 추적을 위해 사용자 ID 설정
Pushwoosh.Instance.SetUserId("user-123");

// 사용자 이메일 설정
Pushwoosh.Instance.SetEmail("user@example.com");

// ID와 이메일 모두로 사용자 설정
Pushwoosh.Instance.SetUser("user-123", new List<string> { "user@example.com" });

// 선호 언어 설정
Pushwoosh.Instance.SetLanguage("en");
```

### 태그

태그는 기기에 할당된 키-값 쌍으로, 사용자 세분화 및 타겟 메시징을 가능하게 합니다:

```csharp
// 문자열 태그
Pushwoosh.Instance.SetStringTag("favorite_category", "electronics");

// 정수 태그
Pushwoosh.Instance.SetIntTag("purchase_count", 5);

// 리스트 태그
Pushwoosh.Instance.SetListTag("interests", new List<object> { "sports", "music", "tech" });

// 모든 태그 가져오기
Pushwoosh.Instance.GetTags((tags, error) => {
    if (error != null) {
        Debug.Log("Error: " + error.Message);
        return;
    }
    foreach (var tag in tags) {
        Debug.Log(tag.Key + ": " + tag.Value);
    }
});
```

### 이벤트

사용자 행동을 추적하여 행동을 분석하고 자동화된 메시지를 트리거하세요:

```csharp
// 로그인 이벤트 추적
Pushwoosh.Instance.PostEvent("login", new Dictionary<string, object> {
    { "username", "user-123" },
    { "login_type", "email" }
});

// 구매 이벤트 추적
Pushwoosh.Instance.PostEvent("purchase", new Dictionary<string, object> {
    { "product_id", "SKU-001" },
    { "price", 29.99 },
    { "currency", "USD" }
});
```

### 통신 환경설정

사용자가 프로그래밍 방식으로 푸시 알림을 수신하거나 거부하도록 허용하세요:

```csharp
// 통신 활성화
Pushwoosh.Instance.SetCommunicationEnabled(true);

// 통신 비활성화
Pushwoosh.Instance.SetCommunicationEnabled(false);

// 현재 상태 확인
bool isEnabled = Pushwoosh.Instance.IsCommunicationEnabled();
```

### 배지 관리

지원되는 플랫폼에서 앱 배지 번호를 제어하세요:

```csharp
// 배지를 특정 숫자로 설정
Pushwoosh.Instance.SetBadgeNumber(3);

// 배지 증가
Pushwoosh.Instance.AddBadgeNumber(1);

// 배지 지우기
Pushwoosh.Instance.SetBadgeNumber(0);
```

## 문제 해결

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