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

# 예제 앱: 안정적이고 올바르게 동작하는 푸시

> 예제 앱 Clean Beans가 멱등성 키로 중복 푸시를 막고, 푸시 유형별로 전송을 조정하고, 앱 아이콘 배지를 설정하는 방법입니다.

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

푸시를 도착하게 하는 것은 첫 단계일 뿐입니다. 이 페이지는 푸시를 믿을 수 있게 만드는 세부 결정을 다룹니다. 같은 푸시를 두 번 보내지 않고, 오래된 푸시는 만료되게 하며, 각 유형이 그에 맞게 동작하도록 하는 것입니다.

## 같은 알림을 두 번 보내지 않기 \\

예약된 작업은 재시도됩니다. 실수로 두 번 실행될 수도 있습니다. 보호 장치가 없으면 반복될 때마다 푸시가 한 번 더 전송됩니다.

OneSignal의 `idempotency_key`가 이 문제를 해결합니다. 두 요청이 같은 키를 가지면 두 번째 요청은 전송되지 않습니다. 키는 UUID여야 하며 OneSignal은 이를 30일 동안 기억합니다.

예약된 함수에는 실행 사이에 무작위 키를 보관할 곳이 없으므로, Clean Beans는 전송의 성격, 즉 유형, 수신자, 날짜에서 키를 만듭니다. 같은 전송은 항상 같은 키를 생성합니다.

```typescript supabase/functions/_shared/idempotency.ts theme={null}
/** Name-based UUID (version 5) per RFC 9562. */
export async function uuidV5(name: string, namespace: string): Promise<string> {
  const ns = uuidToBytes(namespace);
  const nameBytes = new TextEncoder().encode(name);
  const input = new Uint8Array(ns.length + nameBytes.length);
  input.set(ns);
  input.set(nameBytes, ns.length);

  const digest = new Uint8Array(await crypto.subtle.digest('SHA-1', input));
  const bytes = digest.slice(0, 16);
  bytes[6] = (bytes[6] & 0x0f) | 0x50; // version 5
  bytes[8] = (bytes[8] & 0x3f) | 0x80; // RFC variant

  const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}

export function idempotencyKey(...parts: string[]): Promise<string> {
  return uuidV5(parts.join(':'), CLEAN_BEANS_NAMESPACE);
}
```

| 푸시 | 키 구성 요소 | 결과 |
| - | - | - |
| 일일 요약 | 유형, 사용자 ID, 사용자의 현지 날짜 | 사용자당 하루 한 번의 요약 |
| 기한 초과 알림 | 유형, 사용자 ID, 사용자의 현지 날짜 | 사용자당 하루 한 번의 알림 |
| 청소 알림 | 유형, 시간, 정렬된 수신자 ID | 매시간 실행당 배치마다 한 번의 알림 |
| 주간 이메일 | 유형, 가구 ID, 실행 날짜 | 실행당 가구마다 한 통의 이메일 |
| 가입 승인 | 유형, 사용자 ID, 가구 ID, 승인 시간 | 승인당 한 번의 푸시 |

배치 전송에서는 키가 배치 전체를 대상으로 합니다.

```typescript supabase/functions/send-cleaning-reminder/index.ts theme={null}
const batchKey = await idempotencyKey(
  'upcoming_cleaning',
  utcHourSlot(now),
  [...batch].sort().join(','),
);
```

> [!NOTE]
>
> 멱등성 키는 Create message 및 Create custom events 엔드포인트에서 동작합니다. Live Activity 요청은 이를 받지 않습니다. Live Activity는 `activity_id`로 식별됩니다.

## 푸시 유형마다 고유한 동작 부여하기 \\

두 시간 늦게 도착한 청소 알림은 알림이 없는 것보다 나쁩니다. Kudos는 받으면 기쁘지만 급하지 않습니다. Clean Beans는 이러한 차이를 전송 프로필 집합에 한 번만 정의하고, 각 요청에 알맞은 프로필을 펼쳐 넣습니다.

```typescript supabase/functions/_shared/delivery.ts theme={null}
export const DELIVERY: Record<
  'daily_digest' | 'overdue_reminder' | 'upcoming_cleaning' | 'session_completed' | 'kudos' | 'join_approved' | 'member_lapsed',
  DeliveryProfile
> = {
  // Morning digest. Expires after 6h — by then the overdue nudge has taken
  // over. Grouped with the nudge under the same thread.
  daily_digest: {
    ttl: 6 * HOUR,
    thread_id: 'tasks',
    android_group: 'tasks',
    ios_interruption_level: 'active',
    ios_relevance_score: 0.6,
  },

  // Afternoon nudge. Arrives as its own alert, grouped with the digest.
  overdue_reminder: {
    ttl: 6 * HOUR,
    thread_id: 'tasks',
    android_group: 'tasks',
    ios_interruption_level: 'active',
    ios_relevance_score: 0.8,
  },

  // "Cleaning time in 1 hour". Only meaningful until the window starts,
  // so it expires after 1h. Time-sensitive: it is tied to a time the user
  // scheduled themselves, so it may break through Focus modes.
  upcoming_cleaning: {
    ttl: 1 * HOUR,
    thread_id: 'schedule',
    android_group: 'schedule',
    ios_interruption_level: 'time_sensitive',
    ios_relevance_score: 0.9,
  },

  // ...
};
```

| 푸시 | 오프라인 기기를 위한 보관 기간 | 그룹 | iOS 중단 수준 | 관련성 |
| - | - | - | - | - |
| 일일 요약 | 6시간 | `tasks` | Active | 0.6 |
| 기한 초과 알림 | 6시간 | `tasks` | Active | 0.8 |
| 청소 알림 | 1시간 | `schedule` | Time Sensitive | 0.9 |
| 세션 완료 | 24시간 | `household` | Active | 0.4 |
| Kudos | 3일 | `household` | Passive | 0.7 |
| 가입 승인 | 3일 | `household` | Active | 0.8 |

유형 목록의 `member_lapsed` 프로필은 Journey 웹훅에서 보내는 푸시용이며, 이 가이드에서는 다루지 않습니다.

각 설정의 역할:

* **`ttl`** 은 오프라인 기기를 위해 푸시를 보관하는 기간입니다. 청소 알림은 "1시간 후"라고 알리므로 1시간이 지나면 폐기됩니다.
* **`thread_id`** 와 **`android_group`** 은 관련 푸시를 알림 목록에서 함께 묶습니다.
* **`ios_interruption_level`** 은 푸시가 얼마나 강하게 알리는지 제어합니다. `time_sensitive`는 집중 모드를 뚫고 표시될 수 있습니다. `passive`는 조용히 도착합니다.
* **`ios_relevance_score`** 는 iOS 알림 요약에서 푸시의 순위를 정합니다. Clean Beans는 `1.0`을 중요한 메시지용으로 남겨 두며, 그런 메시지는 보내지 않습니다.

**앱 설정.** iOS는 앱이 capability를 선언한 경우에만 `time_sensitive`를 적용합니다.

```json app.json theme={null}
{
  "expo": {
    "ios": {
      "entitlements": {
        "com.apple.developer.usernotifications.time-sensitive": true
      }
    }
  }
}
```

> [!WARNING]
>
> **얻은 교훈: `collapse_id`.** Clean Beans는 처음에 알림이 요약을 대체하도록 요약과 기한 초과 알림에 같은 `collapse_id`를 주었습니다. iOS에서는 알림 목록에 아직 남아 있는 푸시를 대체하는 푸시가 배너나 소리 없이 그 자리에서 바뀝니다. 알림이 눈에 띄지 않아 목적을 이루지 못했으므로 이 설정을 제거했습니다. `collapse_id`는 실시간 점수처럼 조용한 업데이트가 필요할 때만 사용하세요.

## 앱 아이콘에 개수 표시하기 \\

두 작업 푸시는 앱 아이콘 배지를 제목에 있는 숫자로 설정합니다.

```typescript supabase/functions/send-overdue-reminders/index.ts theme={null}
// App icon badge = number of overdue tasks. The OneSignal SDK clears the
// badge automatically the next time the app is opened.
ios_badgeType: 'SetTo',
ios_badgeCount: taskCount,
```

![배지 숫자가 표시된 Clean Beans 앱 아이콘](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-badge.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=08c9bc46b557e4e15819cd0ec42488cf)

앱 아이콘 배지는 기한이 지난 작업 수를 보여줍니다.

배지는 읽지 않은 알림 수가 아니라 작업 수이므로 `Increase`가 아닌 `SetTo`를 사용합니다. 오후 알림이 오전의 숫자를 대체합니다.

> [!NOTE]
>
> OneSignal SDK는 앱이 열릴 때마다 배지를 자동으로 지우므로 앱에 재설정 코드가 필요하지 않습니다. 앱이 열려 있을 때 도착한 푸시는 배지를 표시하지 않습니다. Android에는 API로 설정할 수 있는 숫자 배지가 없습니다.

> [card] [멱등 요청](https://documentation.onesignal.com/reference/idempotent-notification-requests.md)
>
> 키의 동작 방식과 유지 기간.

> [card] [중단 수준](https://documentation.onesignal.com/docs/ko/ios-focus-modes-and-interruption-levels.md)
>
> 집중 모드와 네 가지 수준.

> [card] [배지](https://documentation.onesignal.com/docs/ko/badges.md)
>
> 플랫폼별 배지 동작.


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