> ## 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から起動する方法。

このページは、1つの実在アプリを最初から最後まで追う[サンプルアプリ：OneSignalの完全な統合](https://documentation.onesignal.com/docs/ja/example-full-integration-overview.md)の一部です。アプリは**Clean Beans**という共同生活の家のための掃除当番表アプリで、Expo（React Native）とSupabaseバックエンドで構築されています。

通知は、タップしたときに正しい場所へ移動できて初めて役に立ちます。Clean Beansは、アプリに入る4つの経路を処理します。プッシュのタップ、プッシュ上のボタンのタップ、カスタムスキームのリンク、通常のWebリンクです。

## タップされたプッシュを振り分ける \\

すべてのプッシュには`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タブ |

このうち2つの種類は、このガイドでは扱わないJourneysから送られます。`reengagement`は、ダッシュボードで作成した休眠ユーザー復帰用Journeyのプッシュに設定されます。`member_lapsed`は世帯のオーナーと管理者向けのプッシュで、メンバーが掃除をやめたことをそのJourneyが報告したときにバックエンドが送信します。これらもほかのプッシュと同様にここで振り分けられます。

> [!TIP]
>
> 自分で管理する種類で振り分けるほうが、URLを解析するよりも堅牢です。画面が移動しても、`switch`文を1つ変更するだけで、変更前に送信したすべてのプッシュも正しく開きます。

## アクションボタン：タップできる場所を増やす \\

プッシュにはボタンを付けられます。タスクのプッシュには**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)

2つのアクションボタンがある展開されたリマインダー。

バックエンドがボタンをリクエストに追加します。各ボタンには`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がその時刻までメッセージを保持するため、1時間何かを動かし続ける必要はありません。

```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)';
  }
}
```

## 通常のWebリンクからアプリを開く \\

`cleaning-rota://`のようなカスタムスキームはアプリがインストールされている場合にしか機能せず、多くのアプリはそれをタップ可能にしません。iOSのUniversal LinksとAndroidのApp Linksがこれを解決します。これらは通常の`https://`リンクで、アプリがインストールされていればアプリを、そうでなければWebサイトを開きます。そのため、メール、SMS、共有メッセージ内のリンクに適しています。

設定には双方での宣言が必要です。アプリは自分が属するドメインを宣言し、Webサイトはどのアプリがそのリンクを開けるかを宣言します。

**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の後にバンドル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/ja/deep-linking.md)
>
> 各プラットフォームでOneSignalがURLを処理する方法。

> [card] [通知ペイロード](https://documentation.onesignal.com/docs/ja/osnotification-payload.md)
>
> クリックリスナーで使用できるすべてのフィールド。

> [card] [アクションボタン](https://documentation.onesignal.com/docs/ja/action-buttons.md)
>
> プラットフォームの制限、アイコン、タップの処理。


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