expo-live-activity

repository·main·Indexed 19 days ago

https://github.com/software-mansion-labs/expo-live-activity

A React Native module for managing iOS Live Activities (iOS 16.2+), allowing developers to display real-time, dynamic updates on the iOS lock screen and Dynamic Island. It provides APIs to start, update, and stop activities, supports deep linking, and includes a Config Plugin for Expo DevClient to handle App Extension registration, entitlements, and push notification configuration.

Tokens
7.9K
Snippets
27
Records
30
Agent score
65%

What's inside expo-live-activity

  1. Using Images in Live Activities

    main

    Live Activity views support image display via two specific fields in the state (or content-state) object:

    1. imageName
    2. dynamicIslandImageName

    Supported Values:

    • Asset Name: A string mapping to a local asset name.
    • Remote URL: A URL to a remote image.

    Important Requirements for Remote URLs:

    • Currently, remote URLs are only supported via the API (push notification support for remote URLs is planned).
    • Using remote URLs requires adding the "App Groups" capability to both the "main app" and "Live Activity" targets.
  2. Implement deep linking in Live Activities

    main

    You can pass a deepLinkUrl in the config object when calling startActivity. This allows users to tap the Live Activity to navigate to a specific screen in your app.

    If using @react-navigation, it is recommended to use Linking.createURL('') to handle prefixes. The URL scheme is automatically pulled from the scheme field in app.json or falls back to the ios.bundleIdentifier.

    import { Linking } from 'react-native';
    import * as LiveActivity from 'expo-live-activity';
    
    const prefix = Linking.createURL('');
    
    // ... inside your component
    LiveActivity.startActivity(state, {
      deepLinkUrl: '/order',
    });
  3. Enable Push Notifications for Live Activities

    main

    By default, Live Activities can only be started or updated via the local API. To enable starting or updating Live Activities via push notifications, you must add the enablePushNotifications flag to your plugin configuration in app.json or app.config.ts.

    Note: The PushToStart feature requires iOS 17.2 or higher.

    {
      "plugins": [
        [
          "expo-live-activity",
          {
            "enablePushNotifications": true
          }
        ]
      ]
    }
  4. Install expo-live-activity

    main

    To use expo-live-activity, you must use Expo DevClient as it is not supported in Expo Go. This module is intended for iOS devices only (iOS 16.2+).

    1. Install the package:
    npm install expo-live-activity
    1. Configure the Config Plugin in your app.json or app.config.js:
    {
      "expo": {
        "plugins": ["expo-live-activity"]
      }
    }
    1. If you need to update Live Activities via push notifications, enable the option:
    {
      "expo": {
        "plugins": [
          [
            "expo-live-activity",
            {
              "enablePushNotifications": true
            }
          ]
        ]
      }
    }
    1. Place images for Live Activities in the assets/liveActivity folder. Note that images must be smaller than 4KB due to iOS limitations.

    2. Run prebuild to generate the necessary iOS targets:

    npx expo prebuild --clean
  5. Define Live Activity content with LiveActivityState

    main

    The LiveActivityState object defines the content displayed in the Live Activity.

    Fields include:

    • title: The main heading.
    • subtitle: Optional secondary text.
    • progressBar: An object representing progress. It can be one of several shapes:
      • { date: number } (for a countdown/timer based on a timestamp)
      • { progress: number } (a 0.0 to 1.0 value)
      • { elapsedTimer: { startDate: number } } (timer based on start time)
      • { currentStep: number, totalSteps: number } (step-based progress)
    • imageName: Name of the image to display.
    • dynamicIslandImageName: Specific image for the Dynamic Island.
    • smallImageName: Specific image for small views.
  6. Handle push notification tokens

    main

    To support remote updates via push notifications, subscribe to token changes using these listeners:

    • addActivityPushToStartTokenListener(listener): Listens for the token used to start activities via push.
    • addActivityTokenListener(listener): Listens for the token associated with an active Live Activity.

    Note: Testing push tokens typically requires a physical iOS device; it may not work on simulators.

    useEffect(() => {
      const updateTokenSubscription = LiveActivity.addActivityTokenListener(
        ({ activityID: newActivityID, activityName: newName, activityPushToken: newToken }) => {
          // Send token to a remote server
        }
      )
      const startTokenSubscription = LiveActivity.addActivityPushToStartTokenListener(
        ({ activityPushToStartToken: newActivityPushToStartToken }) => {
          // Send token to a remote server
        }
      )
    
      return () => {
        updateTokenSubscription?.remove()
        startTokenSubscription?.remove()
      }
    }, [])
  7. Start, update, and stop Live Activities

    main

    Use the following functions to manage the lifecycle of a Live Activity. All functions accept an optional relevanceScore (a number between 0.0 and 1.0) to determine the display order on the lock screen.

    • startActivity(state, config?, relevanceScore?): Starts a new activity. Returns the activityId (string) which you must store to manage the activity later. Returns undefined if the platform is unsupported.
    • updateActivity(id, state, relevanceScore?): Updates an existing activity using its id.
    • stopActivity(id, state, relevanceScore?): Terminates an ongoing activity.
    const state: LiveActivity.LiveActivityState = {
      title: 'Title',
      subtitle: 'Subtitle',
      progressBar: {
        date: new Date(Date.now() + 60 * 1000 * 5).getTime(),
      },
      imageName: 'live_activity_image',
      dynamicIslandImageName: 'dynamic_island_image',
    }
    
    const config: LiveActivity.LiveActivityConfig = {
      backgroundColor: '#FFFFFF',
      titleColor: '#000000',
      deepLinkUrl: '/dashboard',
    }
    
    const activityId = LiveActivity.startActivity(state, config)
  8. Enable Push Notifications via withPushNotifications config plugin

    main

    To enable push notification support for Live Activities in your Expo project, use the withPushNotifications config plugin. This plugin performs two critical configuration steps during the prebuild process:

    1. Sets the aps-environment entitlement to development in your Entitlements.plist.
    2. Sets the ExpoLiveActivity_EnablePushNotifications key to true in your Info.plist.

    This is required to allow the native iOS code to receive push updates for Live Activities.

    // In your app.config.js or app.json
    export default {
      expo: {
        plugins: [
          [
            'expo-live-activity',
            // ... other plugin options
          ],
          'withPushNotifications' // Add this to enable push support
        ],
      },
    };
  9. Configure expo-live-activity platform modules

    main

    The expo-module.config.json defines the native module entry points for different platforms. For expo-live-activity, the following native modules are registered:

    • Apple (iOS): ExpoLiveActivityModule
    • Android: expo.modules.liveactivity.ExpoLiveActivityModule
    {
      "platforms": ["apple", "android", "web"],
      "apple": {
        "modules": ["ExpoLiveActivityModule"]
      },
      "android": {
        "modules": ["expo.modules.liveactivity.ExpoLiveActivityModule"]
      }
    }
  10. Configure silent behavior on unsupported OS via withUnsupportedOS

    main

    The withUnsupportedOS config plugin allows you to control how the library behaves on unsupported operating systems by setting a boolean flag in the Info.plist.

    When silentOnUnsupportedOS is set to true, the library will suppress warnings or errors related to unsupported OS versions. This value is written to the ExpoLiveActivity_SilentOnUnsupportedOS key in your app's Info.plist during the Expo prebuild process.

    // Example usage in app.config.js or app.json
    export default {
      expo: {
        plugins: [
          [
            "expo-live-activity",
            {
              silentOnUnsupportedOS: true
            }
          ]
        ]
      }
    };
  11. Configure Live Activity appearance with LiveActivityConfig

    main

    The LiveActivityConfig object allows you to customize the visual properties of the Live Activity.

    Key configuration options include:

    • Colors: backgroundColor, titleColor, subtitleColor, progressViewTint, progressViewLabelColor, progressSegmentActiveColor, progressSegmentInactiveColor.
    • Layout: padding (can be a number or an object), imagePosition ('left' | 'right' | 'leftStretch' | 'rightStretch'), imageAlign ('top' | 'center' | 'bottom').
    • Images: imageSize and smallImageSize (supports number or percentage strings like '50%'), contentFit ('cover' | 'contain' | 'fill' | 'none' | 'scale-down').
    • Other: deepLinkUrl, timerType ('circular' | 'digital').
  12. Configure the expo-live-activity Config Plugin

    main

    When using the expo-live-activity Config Plugin in your app.json or app.config.js, you can provide an options object to customize its behavior.

    Supported options:

    • enablePushNotifications: (boolean, optional) Enables support for push notification tokens used to update Live Activities.
    • silentOnUnsupportedOS: (boolean, optional) If true, the plugin will fail silently on operating systems that do not support Live Activities (e.g., Android) instead of throwing an error during prebuild.
    {
      "expo": {
        "plugins": [
          [
            "expo-live-activity",
            {
              "enablePushNotifications": true,
              "silentOnUnsupportedOS": true
            }
          ]
        ]
      }
    }