> ## 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가 탭한 푸시를 올바른 화면으로 보내고, 액션 버튼과 다시 알림을 처리하고, Universal Links로 앱을 여는 방법입니다.

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

알림은 탭했을 때 올바른 곳으로 이동해야 쓸모가 있습니다. Clean Beans는 앱에 들어오는 네 가지 경로를 처리합니다. 탭한 푸시, 푸시에서 탭한 버튼, 커스텀 스킴 링크, 일반 웹 링크입니다.

## 탭한 푸시 라우팅하기 \\

모든 푸시에는 `data.type` 필드가 있습니다. 앱은 탭을 감지해 유형을 읽고 해당 화면을 엽니다.

```typescript app/_layout.tsx theme={null}
OneSignal.Notifications.addEventListener('click', (event: NotificationClickEvent) => {
  const data = event.notification.additionalData as Record<string, string> | undefined;
  if (!data?.type) return;

  // Mark inbox message as read (best-effort, fire-and-forget)
  const notificationId = event.notification.notificationId;
  if (notificationId) {
    supabase
      .from('inbox_messages')
      .update({ read: true })
      .eq('onesignal_message_id', notificationId)
      .then();
  }

  // Small delay to let the app finish initialising if cold-launched
  setTimeout(() => {
    // A tap on an action button ("Snooze 1h", "Send kudos", ...) carries an
    // actionId. A tap on the notification itself does not.
    const action = handlePushAction(event.result.actionId, data);
    if (action.handled) {
      if (action.route) router.push(action.route as any);
      return;
    }

    switch (data.type) {
      case 'daily_digest':
      case 'upcoming_cleaning':
      case 'overdue_reminder':
      case 'reengagement':
        router.push('/(tabs)/clean');
        break;
      case 'session_completed':
      case 'kudos':
        router.push('/activity');
        break;
      case 'join_approved':
      case 'member_lapsed':
        router.push('/household');
        break;
      default:
        break;
    }
  }, 500);
});
```

| `data.type` | 여는 화면 |
| - | - |
| `daily_digest`, `overdue_reminder`, `upcoming_cleaning` | Clean 탭 |
| `session_completed`, `kudos` | 활동 피드 |
| `join_approved`, `member_lapsed` | 가구 화면 |
| `reengagement` | Clean 탭 |

이 중 두 유형은 이 가이드에서 다루지 않는 Journeys에서 옵니다. `reengagement`는 대시보드에서 만든 재참여 Journey의 푸시에 설정됩니다. `member_lapsed`는 가구의 소유자와 관리자에게 보내는 푸시로, 해당 Journey가 구성원이 청소를 멈췄다고 보고하면 백엔드가 보냅니다. 이들도 다른 푸시처럼 여기서 라우팅됩니다.

> [!TIP]
>
> 직접 관리하는 유형으로 라우팅하는 것이 URL을 파싱하는 것보다 견고합니다. 화면이 옮겨지면 `switch` 문 하나만 바꾸면 되고, 변경 전에 보낸 모든 푸시도 계속 올바르게 열립니다.

## 액션 버튼: 탭할 수 있는 곳 늘리기 \\

푸시에는 버튼을 넣을 수 있습니다. 작업 푸시에는 **Start cleaning**과 **Snooze 1h**가 있고, "하우스메이트가 청소를 마침" 푸시에는 **Send kudos**가 있습니다. 알림을 펼치면 버튼이 나타나며, iOS에서는 길게 누르면 됩니다.

![Start cleaning과 Snooze 1h 버튼이 있는 펼친 푸시 알림](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-action-buttons.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=0a850d439deea8f483c8dfe532fb8e93)

두 개의 액션 버튼이 있는 펼친 알림.

백엔드가 요청에 버튼을 추가합니다. 각 버튼에는 `id`와 레이블이 있습니다.

```typescript supabase/functions/_shared/buttons.ts theme={null}
export const TASK_BUTTONS = [
  { id: ACTION_START_CLEANING, text: 'Start cleaning' },
  { id: ACTION_SNOOZE, text: 'Snooze 1h' },
];
```

버튼을 탭하면 앱이 열리고, 위에 나온 클릭 리스너가 버튼의 `id`를 `event.result.actionId`로 받습니다. 알림 자체를 탭하면 `actionId`가 없습니다. 앱은 먼저 버튼인지 확인하고, 아니면 일반 라우팅으로 넘어갑니다.

```typescript src/lib/pushActions.ts theme={null}
export function handlePushAction(actionId: string | undefined, data: PushData): ActionOutcome {
  if (!actionId) return { handled: false };

  // Record which button was tapped. As a custom event it can branch a
  // Journey (Wait Until this event) or feed a Conversion Metric.
  OneSignal.User.trackEvent('push_action_clicked', {
    action_id: actionId,
    notification_type: data?.type ?? 'unknown',
  });

  switch (actionId) {
    case ACTION_START_CLEANING:
      return { handled: true, route: '/(tabs)/clean' };

    case ACTION_SNOOZE:
      snoozeReminder();
      return { handled: true, route: null };

    case ACTION_SEND_KUDOS:
      sendKudosFromPush(data);
      return { handled: true, route: '/activity' };

    default:
      return { handled: false };
  }
}
```

앱은 푸시를 보낼 수 없으므로 **다시 알림**에는 백엔드가 필요합니다. 앱은 `send_after`로 다음 알림을 예약하는 함수를 호출합니다. OneSignal이 그 시간까지 메시지를 보관하므로 한 시간 동안 무언가를 계속 실행할 필요가 없습니다.

```typescript supabase/functions/snooze-reminder/index.ts theme={null}
const sendAt = new Date(Date.now() + SNOOZE_MINUTES * 60_000);

const onesignalPayload = {
  app_id: ONESIGNAL_APP_ID,
  include_aliases: { external_id: [user.id] },
  target_channel: 'push',
  // OneSignal holds the message and delivers it at this time
  send_after: sendAt.toISOString(),
  // ...
};
```

> [!NOTE]
>
> 모든 버튼 탭은 커스텀 이벤트 `push_action_clicked`로도 기록됩니다. Journey는 버튼에 따라 직접 분기할 수 없지만, 이 이벤트를 기다렸다가 `action_id` 속성으로 분기할 수 있습니다.

> [!NOTE]
>
> 버튼을 탭하면 기본적으로 앱이 열립니다. 앱을 열지 않고 탭을 처리하려면 네이티브 코드가 필요합니다. iOS에서는 알림 카테고리, Android에서는 notification service extension입니다.

## 들어오는 링크 재작성하기 \\

앱 밖에서 오는 링크는 `/clean` 같은 짧은 경로를 사용합니다. Expo Router의 native intent 훅이 이동 전에 이를 앱의 실제 경로로 재작성하므로, 앱 밖의 어떤 것도 화면 구성을 알 필요가 없습니다.

```typescript app/+native-intent.tsx theme={null}
const PATH_REWRITES: Record<string, string> = {
  // Tab screens — simplified path → grouped route
  '/clean': '/(tabs)/clean',
  '/tasks': '/(tabs)/tasks',
  '/rota': '/(tabs)/rota',
  '/settings': '/(tabs)/settings',
  '/dashboard': '/(tabs)',

  // Standalone screens
  '/streaks': '/streaks',
  '/activity': '/activity',

  // Convenience aliases
  '/join': '/join-household',
  '/notifications': '/notification-settings',
};

export function redirectSystemPath({
  path,
  initial,
}: {
  path: string;
  initial: boolean;
}): string {
  try {
    // Parse the incoming URL to extract path and query string
    const url = new URL(path, 'cleaning-rota://app');
    const pathname = url.pathname || '/';
    const search = url.search || '';

    // Check for a rewrite match (exact path without query string)
    const rewritten = PATH_REWRITES[pathname];
    if (rewritten) {
      return rewritten + search;
    }

    // Universal Link / App Link with no rewrite: hand the router just the
    // path, not the full https URL
    if (url.protocol === 'https:' || url.protocol === 'http:') {
      return pathname + search;
    }

    // No rewrite needed — pass through as-is
    return path;
  } catch {
    // Never crash in this function — fall back to home screen
    return '/(tabs)';
  }
}
```

## 일반 웹 링크로 앱 열기 \\

`cleaning-rota://` 같은 커스텀 스킴은 앱이 설치된 경우에만 동작하며, 많은 앱이 이를 탭할 수 있게 만들지 않습니다. iOS의 Universal Links와 Android의 App Links가 이 문제를 해결합니다. 이들은 앱이 설치되어 있으면 앱을, 그렇지 않으면 웹사이트를 여는 일반 `https://` 링크입니다. 그래서 이메일, SMS, 공유 메시지의 링크에 적합합니다.

설정하려면 양쪽에 선언이 필요합니다. 앱은 자신이 속한 도메인을 선언하고, 웹사이트는 어떤 앱이 자신의 링크를 열 수 있는지 선언합니다.

**1. 앱에 도메인 선언하기**

```json app.json theme={null}
{
  "expo": {
    "ios": {
      "associatedDomains": ["applinks:cleanbeansapp.com"]
    },
    "android": {
      "intentFilters": [
        {
          "action": "VIEW",
          "autoVerify": true,
          "data": [
            { "scheme": "https", "host": "cleanbeansapp.com", "pathPrefix": "/join" },
            { "scheme": "https", "host": "cleanbeansapp.com", "pathPrefix": "/clean" }
          ],
          "category": ["BROWSABLE", "DEFAULT"]
        }
      ]
    }
  }
}
```

**2. Apple 연결 파일 게시하기**

`/.well-known/apple-app-site-association`에 HTTPS로, JSON 형식으로 호스팅하세요. 앱 ID는 Apple Team ID 뒤에 번들 식별자를 붙인 것입니다.

```json website/.well-known/apple-app-site-association theme={null}
{
  "applinks": {
    "details": [
      {
        "appIDs": ["YOUR_TEAM_ID.com.onesignal.cleaningapp"],
        "components": [
          { "/": "/join", "comment": "Opens /join in the Clean Beans app" },
          { "/": "/clean", "comment": "Opens /clean in the Clean Beans app" }
        ]
      }
    ]
  }
}
```

**3. Android 연결 파일 게시하기**

`/.well-known/assetlinks.json`에 호스팅하세요. 지문은 앱의 서명 인증서에서 가져옵니다. EAS에서는 `eas credentials -p android`를 실행해 확인할 수 있습니다.

```json website/.well-known/assetlinks.json theme={null}
[
  {
    "relation": ["delegate_permission/common.handle_all_urls"],
    "target": {
      "namespace": "android_app",
      "package_name": "com.onesignal.cleaningapp",
      "sha256_cert_fingerprints": ["YOUR_SHA256_FINGERPRINT"]
    }
  }
]
```

**4. 링크 사용하기**

가구 화면은 초대 링크를 공유합니다. 링크를 탭하면 코드가 미리 입력된 상태로 가입 화면이 열립니다.

```typescript app/household.tsx theme={null}
message: `Join my household "${activeHousehold.name}" on Clean Beans! Tap https://cleanbeansapp.com/join?code=${encodeURIComponent(activeHousehold.inviteCode)} or use invite code: ${activeHousehold.inviteCode}`,
```

```typescript app/join-household.tsx theme={null}
const params = useLocalSearchParams<{ code?: string }>();
const [code, setCode] = useState(typeof params.code === 'string' ? params.code : '');
```

> [!NOTE]
>
> Clean Beans는 앱이 보여줄 수 있는 경로만 처리합니다. 홈페이지는 대상에서 제외하므로 마케팅 사이트는 계속 브라우저에서 열립니다. iOS는 앱을 설치하거나 업데이트할 때 연결 파일을 읽으므로, 빌드를 출시하기 전에 파일을 게시하세요.

> [card] [딥 링크](https://documentation.onesignal.com/docs/ko/deep-linking.md)
>
> OneSignal이 플랫폼별로 URL을 처리하는 방식.

> [card] [알림 페이로드](https://documentation.onesignal.com/docs/ko/osnotification-payload.md)
>
> 클릭 리스너에서 사용할 수 있는 모든 필드.

> [card] [액션 버튼](https://documentation.onesignal.com/docs/ko/action-buttons.md)
>
> 플랫폼 제한, 아이콘, 탭 처리.


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