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

# Example app: Live Activities

> How the Clean Beans example app starts, updates, and ends iOS Live Activities from its backend, with the widget code and API requests.

This page is part of [Example app: a full OneSignal integration](https://documentation.onesignal.com/docs/en/example-full-integration-overview.md), which follows one real app from end to end. The app is **Clean Beans**, a cleaning rota for shared homes, built with Expo (React Native) and a Supabase backend.

A Live Activity is a small, live-updating view on the iOS Lock Screen and in the Dynamic Island. Clean Beans uses two: a countdown to the user's cleaning window, and a warning when a streak is about to end.

![A cleaning reminder Live Activity on the iOS Lock Screen](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-LiveActivity-countdown.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=d3e51363076f6271d5f47cfec850e5e2)

The cleaning reminder counting down on the Lock Screen.

Live Activities are normally started by the app. Clean Beans starts them from the backend, because they need to appear at a set time whether or not the app is open. OneSignal's **push-to-start** makes that possible.

## Set up the app

A cross-platform app can let OneSignal manage the Live Activity's lifecycle. One call at startup is all the JavaScript needed.

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

The only native code you write is the widget's layout, in SwiftUI. Clean Beans adds the widget extension to the iOS project with a small Expo config plugin, so the project can still be generated from scratch on every build.

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

## Draw the widget

The widget uses OneSignal's `DefaultLiveActivityAttributes`, which carries free-form data. One widget serves both activities by reading a `type` value and choosing a layout.

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

Each layout reads its values from the data the backend sent. `attributes` are fixed when the activity starts. `state` can change with each update.

```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))
```

A countdown is drawn with SwiftUI's timer style, which ticks on the device without any further updates from the server.

## Streak warning: start an activity from the backend

At 7 PM local time, anyone with a streak who has not cleaned today gets a countdown to midnight. The hourly function finds them using the same time zone matching as the push reminders, then starts an activity for each.

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

![A streak warning Live Activity counting down to midnight](https://mintcdn.com/onesignal/XdN288-p34EfpfHk/images/tutorials/cleanbeans-LA-warning.png?fit=max\&auto=format\&n=XdN288-p34EfpfHk\&q=85\&s=586ca54b6a57f7d1647d5e9bb5aa874f)

The streak warning counts down to midnight.

## Cleaning reminder: start, update, end

The cleaning reminder moves through three phases. Each is a separate request for the same activity.

| Phase | When | Request | What the widget shows |
| - | - | - | - |
| Countdown | One hour before the window | `start` | A timer counting down to the start time |
| Active | The window opens | `update` | "It's your scheduled cleaning time, jump to it!" |
| Ended | The window closes | `end` | Dismissed after five seconds |

The function works out which phase each user should be in.

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

It stores the current phase on the user's profile and only sends a request when the desired phase is different. That makes the hourly job safe to run repeatedly.

Updating and ending use a different endpoint from starting. The activity is named in the URL, so these requests carry no targeting.

```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]
>
> These requests use `priority: 10` because each one is a change of phase that should appear immediately, and a person gets at most a few in a day. Priority `10` counts against the budget Apple allows each device for Live Activity updates. For anything that updates often, such as a score or a progress bar, start with `5`.

> [!WARNING]
>
> Send updates and ends to `/apps/{app_id}/live_activities/{activity_id}/notifications`, not to the start endpoint. Clean Beans originally sent all three to the start endpoint, and every update and end was rejected with "Missing required parameter - event\_attributes".

> [!NOTE]
>
> Give each activity its own `activity_id` and store it when the activity starts. OneSignal does not accept further updates to an `activity_id` once that activity has ended, so a fixed ID per user would stop working after the first day.

> [card] [Cross-platform setup](https://documentation.onesignal.com/docs/en/cross-platform-live-activity-setup.md)
>
> `setupDefault` and the widget extension.

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

> [card] [Update Live Activity](https://documentation.onesignal.com/reference/update-live-activity-api.md)
>
> Update and end requests.


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