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

# サンプルアプリ：Live Activities

> サンプルアプリClean BeansがバックエンドからiOSのLive Activitiesを開始、更新、終了する方法を、ウィジェットのコードとAPIリクエストとともに紹介します。

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

Live Activityは、iOSのロック画面とDynamic Islandに表示される、リアルタイムで更新される小さなビューです。Clean Beansは2つ使っています。ユーザーの掃除時間帯までのカウントダウンと、連続記録が途切れそうなときの警告です。

![iOSのロック画面に表示された掃除リマインダーのLive Activity](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-LiveActivity-countdown.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=d3e51363076f6271d5f47cfec850e5e2)

ロック画面でカウントダウンする掃除リマインダー。

通常、Live Activitiesはアプリが開始します。Clean Beansは、アプリが開いているかどうかに関係なく決まった時刻に表示する必要があるため、バックエンドから開始します。これを可能にするのがOneSignalの**push-to-start**です。

## アプリを設定する \\

クロスプラットフォームアプリでは、Live Activityのライフサイクル管理をOneSignalに任せられます。必要なJavaScriptは、起動時の1回の呼び出しだけです。

```typescript app/_layout.tsx theme={null}
// Enable Live Activities with the default attributes type
OneSignal.LiveActivities.setupDefault({
  enablePushToStart: true,
  enablePushToUpdate: true,
});
```

書く必要があるネイティブコードは、SwiftUIでのウィジェットのレイアウトだけです。Clean Beansは小さなExpo設定プラグインでウィジェット拡張をiOSプロジェクトに追加するため、ビルドのたびにプロジェクトをゼロから生成できます。

```javascript plugins/withLiveActivityWidget.js theme={null}
const WIDGET_TARGET_NAME = "CleanBeansWidgetExtension";
const WIDGET_BUNDLE_ID_SUFFIX = ".CleanBeansWidgetExtension";
const DEPLOYMENT_TARGET = "16.2";
```

## ウィジェットを描画する \\

ウィジェットは、自由形式のデータを持つOneSignalの`DefaultLiveActivityAttributes`を使います。1つのウィジェットが`type`の値を読み取ってレイアウトを選ぶことで、両方のアクティビティに対応します。

```swift plugins/widget/CleanBeansWidgetLiveActivity.swift theme={null}
struct CleanBeansWidgetLiveActivity: Widget {
    var body: some WidgetConfiguration {
        ActivityConfiguration(for: DefaultLiveActivityAttributes.self) { context in
            // Dispatch based on activity type
            let activityType = context.attributes.data["type"]?.asString() ?? "streak-warning"

            if activityType == "cleaning-reminder" {
                CleaningReminderLockScreen(context: context)
            } else {
                StreakWarningLockScreen(context: context)
            }

        } dynamicIsland: { context in
            let activityType = context.attributes.data["type"]?.asString() ?? "streak-warning"

            if activityType == "cleaning-reminder" {
                return cleaningReminderDynamicIsland(context: context)
            } else {
                return streakWarningDynamicIsland(context: context)
            }
        }
    }
}
```

各レイアウトは、バックエンドが送ったデータから値を読み取ります。`attributes`はアクティビティの開始時に固定されます。`state`は更新のたびに変わる可能性があります。

```swift plugins/widget/CleanBeansWidgetLiveActivity.swift theme={null}
let title = context.attributes.data["title"]?.asString() ?? "Streak Warning"
let message = context.state.data["message"]?.asDict()?["en"]?.asString()
    ?? "Your streak is at risk!"
let streakCount = context.state.data["streakCount"]?.asInt() ?? 0
let midnightTs = context.state.data["midnightTs"]?.asInt() ?? 0
let midnightDate = Date(timeIntervalSince1970: Double(midnightTs))
```

カウントダウンはSwiftUIのタイマースタイルで描画され、サーバーからの追加の更新なしにデバイス上で時間が進みます。

## 連続記録の警告：バックエンドからアクティビティを開始する \\

現地時間の午後7時に、連続記録があり今日まだ掃除をしていない人に、深夜0時までのカウントダウンが表示されます。1時間ごとの関数が、プッシュのリマインダーと同じタイムゾーンの照合で対象者を見つけ、それぞれにアクティビティを開始します。

```typescript supabase/functions/streak-warning/index.ts theme={null}
const payload = {
  event: 'start',
  activity_id: activityId,
  include_aliases: {
    external_id: [user.id],
  },
  target_channel: 'push',
  event_attributes: {
    data: {
      title: 'Streak Warning',
    },
  },
  event_updates: {
    data: {
      message: {
        en: `Your ${user.streakCount}-day streak ends at midnight!`,
      },
      streakCount: user.streakCount,
      midnightTs: user.midnightTs,
      userName: user.name,
    },
  },
  name: 'Streak Warning',
  contents: {
    en: `Your ${user.streakCount}-day streak ends at midnight!`,
  },
  headings: {
    en: 'Streak at risk!',
  },
  priority: 10,
};

const res = await fetch(
  `https://api.onesignal.com/apps/${ONESIGNAL_APP_ID}/activities/activity/DefaultLiveActivityAttributes`,
  {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Key ${ONESIGNAL_REST_API_KEY}`,
    },
    body: JSON.stringify(payload),
  }
);
```

![深夜0時までカウントダウンする連続記録警告のLive Activity](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-LA-warning.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=586ca54b6a57f7d1647d5e9bb5aa874f)

深夜0時までカウントダウンする連続記録の警告。

## 掃除リマインダー：開始、更新、終了 \\

掃除リマインダーは3つのフェーズを経ます。それぞれが同じアクティビティに対する個別のリクエストです。

| フェーズ | タイミング | リクエスト | ウィジェットの表示 |
| - | - | - | - |
| カウントダウン | 時間帯の1時間前 | `start` | 開始時刻までのカウントダウンタイマー |
| アクティブ | 時間帯の開始 | `update` | 「It's your scheduled cleaning time, jump to it!」 |
| 終了 | 時間帯の終了 | `end` | 5秒後に消える |

関数は、各ユーザーがどのフェーズにいるべきかを判定します。

```typescript supabase/functions/cleaning-activity/index.ts theme={null}
function getDesiredPhase(
  currentHour: number,
  window: CleaningWindow,
): 'countdown' | 'active' | null {
  const reminderHour = (window.start - 1 + 24) % 24;

  // Active: inside the cleaning window
  if (isHourInRange(currentHour, window.start, window.end)) return 'active';

  // Countdown: the single hour before the window starts
  if (currentHour === reminderHour) return 'countdown';

  return null;
}
```

現在のフェーズはユーザーのプロフィールに保存し、目標とするフェーズが異なる場合にだけリクエストを送ります。これにより、1時間ごとのジョブを繰り返し実行しても安全です。

更新と終了には、開始とは異なるエンドポイントを使います。アクティビティはURLで指定されるため、これらのリクエストにはターゲティングが含まれません。

```typescript supabase/functions/cleaning-activity/index.ts theme={null}
async function updateCleaningActivity(activityId: string): Promise<boolean> {
  const payload = {
    event: 'update',
    event_updates: {
      data: {
        message: { en: "It's your scheduled cleaning time, jump to it!" },
        phase: 'active',
        targetTs: 0,
      },
    },
    name: 'Cleaning Active',
    contents: { en: "It's your scheduled cleaning time!" },
    priority: 10,
  };

  // ...
}

async function endCleaningActivity(activityId: string): Promise<boolean> {
  const payload = {
    event: 'end',
    event_updates: {
      data: {
        message: { en: 'Cleaning window ended' },
        phase: 'ended',
      },
    },
    name: 'Cleaning Ended',
    dismissal_date: Math.floor(Date.now() / 1000) + 5, // dismiss after 5s
    priority: 10,
  };

  // ...
}
```

> [!NOTE]
>
> これらのリクエストで`priority: 10`を使うのは、それぞれがすぐに表示すべきフェーズの変化であり、1人が受け取るのは1日に数回程度だからです。優先度`10`は、AppleがデバイスごとにLive Activityの更新に割り当てる予算を消費します。スコアやプログレスバーのように頻繁に更新するものには、`5`から始めてください。

> [!WARNING]
>
> 更新と終了は、開始のエンドポイントではなく`/apps/{app_id}/live_activities/{activity_id}/notifications`に送信してください。Clean Beansは当初3つすべてを開始のエンドポイントに送っていたため、更新と終了はすべて「Missing required parameter - event\_attributes」で拒否されていました。

> [!NOTE]
>
> アクティビティごとに固有の`activity_id`を付け、アクティビティの開始時に保存してください。OneSignalは終了したアクティビティの`activity_id`への更新を受け付けないため、ユーザーごとに固定のIDを使うと2日目以降は機能しなくなります。

> [card] [クロスプラットフォームのセットアップ](https://documentation.onesignal.com/docs/ja/cross-platform-live-activity-setup.md)
>
> `setupDefault`とウィジェット拡張。

> [card] [Live Activityの開始](https://documentation.onesignal.com/reference/start-live-activity.md)
>
> push-to-start API。

> [card] [Live Activityの更新](https://documentation.onesignal.com/reference/update-live-activity-api.md)
>
> 更新と終了のリクエスト。


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