> ## Documentation Index
> Fetch the complete documentation index at: https://documentation.onesignal.com/llms.txt
> Use this file to discover all available pages before exploring further.

# 예제 앱: SDK 설정 및 사용자 ID

> 예제 앱 Clean Beans가 Expo에 OneSignal SDK를 설치하고, External ID로 각 기기를 사용자와 연결하고, 이메일을 추가하는 방법입니다.

이 페이지는 실제 앱 하나를 처음부터 끝까지 따라가는 [예제 앱: OneSignal 전체 통합](https://documentation.onesignal.com/docs/ko/example-full-integration-overview.md)의 일부입니다. 앱은 공유 주택을 위한 청소 당번표 앱인 **Clean Beans**이며, Expo(React Native)와 Supabase 백엔드로 만들어졌습니다.

다른 모든 것은 네 가지가 올바르게 되어 있어야 동작합니다. SDK가 설치되어 있고, 앱이 시작될 때 SDK도 시작되고, 각 기기가 사용자와 연결되어 있고, 사람들이 받을 내용을 직접 제어할 수 있어야 합니다.

## Expo 플러그인으로 설치하기 \\

`onesignal-expo-plugin`은 빌드 시점에 네이티브 iOS 및 Android 프로젝트를 구성합니다. 이미지, 배지, 전송 확인을 위해 OneSignal에 필요한 푸시 capability, App Group, Notification Service Extension을 추가합니다.

```json app.json theme={null}
{
  "expo": {
    "plugins": [
      ["onesignal-expo-plugin", { "mode": "production" }],
      "expo-router",
      "./plugins/withLiveActivityWidget"
    ],
    "ios": {
      "bundleIdentifier": "com.onesignal.cleaningapp",
      "infoPlist": {
        "UIBackgroundModes": ["remote-notification"],
        "NSSupportsLiveActivities": true
      },
      "entitlements": {
        "aps-environment": "production",
        "com.apple.security.application-groups": [
          "group.com.onesignal.cleaningapp.onesignal"
        ]
      }
    }
  }
}
```

## 루트에서 한 번만 초기화하기 \\

Clean Beans는 루트 레이아웃에서 OneSignal을 초기화하므로, 앱을 실행할 때마다 어떤 화면보다도 먼저 한 번 실행됩니다.

```typescript app/_layout.tsx theme={null}
// Verbose logging is for debugging during the beta. Remove it, or lower
// the level, before a public release.
OneSignal.Debug.setLogLevel(LogLevel.Verbose);
OneSignal.initialize('YOUR_ONESIGNAL_APP_ID');
OneSignal.Notifications.requestPermission(true);
```

> [!TIP]
>
> 첫 실행 시 권한을 요청하는 것이 가장 간단한 방법입니다. 먼저 이점을 설명하려면 시스템 프롬프트보다 앞서 인앱 메시지를 표시하세요. Clean Beans에는 바로 사용할 수 있는 메시지가 있습니다. [푸시 권한 사전 안내](https://documentation.onesignal.com/docs/ko/example-full-integration-in-app-messages.md#push-permission-pre-prompt)를 참조하세요.

## 각 기기를 사용자와 연결하기 \\

누군가 로그인하면 앱은 Supabase 사용자 ID를 `OneSignal.login()`에 전달합니다. 이 ID가 External ID가 됩니다. 로그아웃하면 `logout()`이 기기 연결을 해제하므로, 다음에 로그인하는 사람이 이전 사용자의 메시지를 이어받지 않습니다.

```typescript app/_layout.tsx theme={null}
// Link OneSignal identity to authenticated user and sync timezone
//
// Wait until the saved session has been restored. On a cold start `user`
// is null for a moment while it loads; calling logout() then, followed by
// login() a moment later, can leave this device's push subscription on an
// anonymous OneSignal user, so pushes sent to the External ID never reach
// the phone. logout() is only called on a real sign-out.
const wasSignedIn = useRef(false);
useEffect(() => {
  if (loading) return;

  if (user) {
    wasSignedIn.current = true;
    OneSignal.login(user.id);
    syncDeviceTimezone();
    // Add email subscription and sync data tags to OneSignal
    if (user.email) syncOneSignalEmail(user.email);
    // Add the SMS subscription if the user has a verified phone number
    syncOneSignalSms();
    syncOneSignalTags();
  } else if (wasSignedIn.current) {
    wasSignedIn.current = false;
    OneSignal.logout();
  }
}, [user, loading]);
```

> [!WARNING]
>
> 두 메서드 중 어느 것을 호출하든 저장된 세션이 로드될 때까지 기다리세요. 콜드 스타트 시에는 로그인한 사용자를 잠시 알 수 없습니다. 이때 앱이 `logout()`을 호출하고 잠시 후 `login()`을 호출하면 기기의 푸시 구독이 익명 사용자에게 남아 External ID로 보낸 푸시가 휴대폰에 도달하지 않을 수 있습니다. `logout()`은 실제로 로그아웃할 때만 호출하세요.

이 한 번의 호출 덕분에 이 가이드의 모든 백엔드 전송이 가능합니다. 사용자의 데이터베이스 ID를 아는 함수는 그 사용자의 기기에 대해 아무것도 몰라도 메시지를 보낼 수 있습니다.

## 이메일 채널 추가하기 \\

앱은 가입 시점부터 각 사용자의 이메일 주소를 알고 있으므로, 로그인할 때 이를 이메일 구독으로 등록합니다. OneSignal은 같은 주소로 반복되는 호출을 무시합니다.

```typescript src/lib/onesignalSync.ts theme={null}
export function syncOneSignalEmail(email: string): void {
  try {
    if (!email) return;
    OneSignal.User.addEmail(email);
    console.log('[onesignalSync] Email subscription added');
  } catch (e) {
    console.warn('[onesignalSync] syncOneSignalEmail error:', e);
  }
}
```

SMS도 `addSms()`로 같은 방식으로 추가하지만, 번호를 인증한 후에만 추가합니다. [SMS: 인증 코드와 초대](https://documentation.onesignal.com/docs/ko/example-full-integration-sms.md)를 참조하세요.

## 받을 내용을 사용자가 제어하게 하기 \\

알림 설정 화면에는 마스터 스위치와 메시지 유형별 스위치가 있습니다.

![마스터 토글과 유형별 토글이 있는 알림 설정 화면](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-notifications.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=57fef32f8987a51e7bdf8c40a6273087)

알림 설정: 마스터 스위치, 유형별 스위치, 일일 알림 시간.

마스터 스위치는 푸시 구독에서 `optOut()`과 `optIn()`을 호출하므로, OneSignal이 해당 기기로의 전송을 중지하거나 재개합니다.

```typescript app/notification-settings.tsx theme={null}
const handlePushMasterToggle = async (enabled: boolean) => {
  try {
    if (enabled) {
      OneSignal.User.pushSubscription.optIn();
    } else {
      OneSignal.User.pushSubscription.optOut();
    }
  } catch (e) {
    console.warn('OneSignal subscription toggle failed:', e);
  }
  save({ ...prefs, pushEnabled: enabled });
};
```

모든 스위치는 사용자의 프로필 행에도 저장됩니다. 백엔드는 무언가를 보내기 전에 이 열을 읽으며, 이렇게 유형별 설정이 적용됩니다.

```typescript src/lib/database.ts theme={null}
  const { error } = await supabase
    .from('profiles')
    .update({
      notifications_enabled: prefs.pushEnabled,
      push_daily_reminders: prefs.pushDailyReminders,
      push_streak_reminders: prefs.pushStreakReminders,
      push_cleaning_done: prefs.pushCleaningDone,
      push_leaderboard_updates: prefs.pushLeaderboardUpdates,
      push_upcoming_cleaning: prefs.pushUpcomingCleaning,
      push_overdue_reminders: prefs.pushOverdueReminders,
      email_weekly_summary: prefs.emailWeeklySummary,
      notification_hour: prefs.notificationHour,
      timezone: prefs.timezone,
    })
    .eq('id', user.id);
```

> [!NOTE]
>
> 설정을 자체 데이터베이스에 저장하고 매번 보내기 전에 확인하면 로직을 한곳에 둘 수 있습니다. 다른 방법은 설정을 태그로 저장하고 OneSignal에서 태그로 필터링하는 것입니다. 세그먼트로 보낼 때는 이 방법이 잘 맞습니다. Clean Beans는 특정 사용자에게 보내므로 데이터베이스를 확인하는 편이 더 간단합니다.

> [card] [모바일 SDK 레퍼런스](https://documentation.onesignal.com/docs/ko/mobile-sdk-reference.md)
>
> 이 가이드에서 사용하는 모든 클라이언트 메서드.

> [card] [사용자 및 External ID](https://documentation.onesignal.com/docs/ko/users.md)
>
> ID가 채널과 기기 간에 구독을 연결하는 방식.


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