### LiveActivitySetupOptions Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/types.md Configuration options for default live activity setup. These options control whether push tokens for starting and updating live activities are enabled. ```APIDOC ## LiveActivitySetupOptions ### Description Configuration options for default live activity setup. These options control whether push tokens for starting and updating live activities are enabled. ### Fields - **enablePushToStart** (boolean) - Required - Enable pushToStart tokens for live activities - **enablePushToUpdate** (boolean) - Required - Enable pushToUpdate tokens for live activities ### Usage Parameter for `OneSignal.LiveActivities.setupDefault()` ``` -------------------------------- ### Install JavaScript Dependencies and iOS Pods Source: https://github.com/onesignal/react-native-onesignal/blob/main/examples/build-ios.md Run these commands from the `examples/demo/` directory to install JavaScript dependencies and then the iOS CocoaPods. Always open the `.xcworkspace` file after installing pods. ```bash bun install cd ios && bundle exec pod install ``` -------------------------------- ### setupDefault Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/LiveActivities.md Enables OneSignal's default live activity setup, allowing the SDK to manage the entire lifecycle of the widget attributes. This is particularly useful for single-widget setups or when avoiding cross-platform bindings. Only applies to iOS. ```APIDOC ## setupDefault() ### Description Enables OneSignal's default live activity setup. The SDK handles the entire lifecycle of the widget attributes. ### Method `LiveActivities.setupDefault(options?: LiveActivitySetupOptions): void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (LiveActivitySetupOptions) - Optional - Optional setup configuration. - **enablePushToStart** (boolean) - Optional - When true, OneSignal will listen for pushToStart tokens for the `OneSignalLiveActivityAttributes` structure. - **enablePushToUpdate** (boolean) - Optional - When true, OneSignal will listen for pushToUpdate tokens for each start live activity that uses the `OneSignalLiveActivityAttributes` structure. ### Request Example ```javascript import { OneSignal } from 'react-native-onesignal'; import { Platform } from 'react-native'; if (Platform.OS === 'ios') { OneSignal.LiveActivities.setupDefault({ enablePushToStart: true, enablePushToUpdate: true }); } ``` ### Response #### Success Response (void) This function does not return a value. #### Response Example None ``` -------------------------------- ### Copy Environment File Source: https://github.com/onesignal/react-native-onesignal/blob/main/examples/demo-no-location/README.md Copy the example environment file to create your own configuration file. ```sh cp .env.example .env ``` -------------------------------- ### Package Scripts for React Native Demo Source: https://github.com/onesignal/react-native-onesignal/blob/main/examples/build.md Defines scripts in `package.json` for setup, native builds, cleaning, and starting the React Native development server. ```json { "scripts": { "setup": "../setup.sh", "preandroid": "vp run setup", "preios": "vp run setup", "android": "bash ../run-android.sh", "ios": "bash ../run-ios.sh", "update:pods": "(cd ios && pod update OneSignalXCFramework --no-repo-update)", "clean:android": "rm -rf android/app/build android/app/.cxx android/build && adb uninstall com.onesignal.example >/dev/null 2>&1 || true", "clean:ios": "rm -rf ios/build ios/Pods", "start": "react-native start" }, "packageManager": "bun@1.3.13" } ``` -------------------------------- ### Complete Foreground Notification Handling Example Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/NotificationWillDisplayEvent.md This example demonstrates comprehensive handling of foreground notifications, including conditional display logic, custom alerts, and silent notification processing. ```javascript import { OneSignal } from 'react-native-onesignal'; import { Alert } from 'react-native'; export function setupNotificationHandlers() { // Handle foreground notifications with custom display OneSignal.Notifications.addEventListener('foregroundWillDisplay', (event) => { const notification = event.getNotification(); // Decide whether to prevent default display if (notification.additionalData?.type === 'urgent') { // Show immediately with default display notification.display(); } else if (notification.additionalData?.type === 'silent') { // Prevent default, handle silently event.preventDefault(); console.log('Silent notification received:', notification.title); } else { // Show custom alert instead of banner event.preventDefault(); Alert.alert( notification.title || 'Notification', notification.body, [ { text: 'Open', onPress: () => { // Handle custom action if (notification.launchURL) { // Navigate to URL } } }, { text: 'Dismiss', onPress: () => {}, style: 'cancel' } ] ); } }); // Handle notification clicks OneSignal.Notifications.addEventListener('click', (event) => { console.log('Notification clicked:', event.notification.title); }); } ``` -------------------------------- ### Setup Default Live Activity Source: https://github.com/onesignal/react-native-onesignal/blob/main/examples/build.md Initializes Live Activities with push-to-start and push-to-update enabled. This should be called during OneSignal initialization. ```typescript OneSignal.LiveActivities.setupDefault({ enablePushToStart: true, enablePushToUpdate: true }) ``` -------------------------------- ### Start Metro Bundler Source: https://github.com/onesignal/react-native-onesignal/blob/main/examples/demo/README.md Starts the Metro JavaScript bundler, which is essential for React Native development. Use either npm or Yarn. ```sh # Using npm npm start # OR using Yarn yarn start ``` -------------------------------- ### Start Default Live Activity Source: https://github.com/onesignal/react-native-onesignal/blob/main/examples/build.md Starts a default Live Activity with a given activity ID, attributes, and content. This function is typically called via a hook. ```typescript OneSignal.LiveActivities.startDefault(activityId, attributes, content) ``` -------------------------------- ### Setup Default Live Activity Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/LiveActivities.md Enables OneSignal's default live activity setup, allowing the SDK to manage the widget attributes and lifecycle. This is useful for single Live Activity widgets or when avoiding cross-platform bindings. Only applies to iOS. ```typescript export namespace LiveActivities { export function setupDefault(options?: LiveActivitySetupOptions): void; } ``` ```typescript type LiveActivitySetupOptions = { /** * When true, OneSignal will listen for pushToStart tokens for the * `OneSignalLiveActivityAttributes` structure. */ enablePushToStart: boolean; /** * When true, OneSignal will listen for pushToUpdate tokens for each * start live activity that uses the `OneSignalLiveActivityAttributes` structure. */ enablePushToUpdate: boolean; }; ``` ```javascript import { OneSignal } from 'react-native-onesignal'; import { Platform } from 'react-native'; if (Platform.OS === 'ios') { OneSignal.LiveActivities.setupDefault({ enablePushToStart: true, enablePushToUpdate: true }); } ``` -------------------------------- ### Start Default Live Activity Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/LiveActivities.md Starts a new live activity using the default `DefaultLiveActivityAttributes` structure with provided dynamic attributes and content. This function is applicable only to iOS. ```typescript export namespace LiveActivities { export function startDefault( activityId: string, attributes: object, content: object, ): void; } ``` ```javascript import { OneSignal } from 'react-native-onesignal'; import { Platform } from 'react-native'; if (Platform.OS === 'ios') { // Start a live activity for an order OneSignal.LiveActivities.startDefault( 'order_12345', // Static attributes { storeName: 'My Store', storeIcon: 'store_icon_url' }, // Dynamic content { orderId: 'ORD-12345', estimatedDelivery: '2:30 PM', status: 'In Transit', progress: 0.65 } ); } ``` -------------------------------- ### Install CocoaPods Dependencies Source: https://github.com/onesignal/react-native-onesignal/blob/main/examples/demo/README.md Installs the necessary CocoaPods dependencies for iOS development. This command should be run after cloning the project or updating native dependencies. ```sh bundle install bundle exec pod install ``` -------------------------------- ### startDefault Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/LiveActivities.md Starts a new default LiveActivity with dynamic content, modeled by the default `DefaultLiveActivityAttributes` structure. The activity is initialized with the provided dynamic attributes and content. Only applies to iOS. ```APIDOC ## startDefault() ### Description Starts a new default LiveActivity with dynamic content. ### Method `LiveActivities.startDefault(activityId: string, attributes: object, content: object): void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **activityId** (string) - Required - The activity identifier to track and update the live activity. - **attributes** (object) - Required - Dynamic type containing static attributes for the activity. - **content** (object) - Required - Dynamic type containing content attributes for the activity. ### Request Example ```javascript import { OneSignal } from 'react-native-onesignal'; import { Platform } from 'react-native'; if (Platform.OS === 'ios') { // Start a live activity for an order OneSignal.LiveActivities.startDefault( 'order_12345', // Static attributes { storeName: 'My Store', storeIcon: 'store_icon_url' }, // Dynamic content { orderId: 'ORD-12345', estimatedDelivery: '2:30 PM', status: 'In Transit', progress: 0.65 } ); } ``` ### Response #### Success Response (void) This function does not return a value. #### Response Example None ``` -------------------------------- ### Example: Listen for InAppMessage Events Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/InAppMessages.md Demonstrates how to add event listeners for various in-app message events like clicks, display, and dismissals. ```javascript // Listen for message clicks OneSignal.InAppMessages.addEventListener('click', (event) => { console.log('Message clicked:', event.message.messageId); console.log('Closing message:', event.result.closingMessage); console.log('Action ID:', event.result.actionId); console.log('URL:', event.result.url); }); // Listen for display events OneSignal.InAppMessages.addEventListener('willDisplay', (event) => { console.log('Message about to display:', event.message.messageId); }); OneSignal.InAppMessages.addEventListener('didDisplay', (event) => { console.log('Message displayed:', event.message.messageId); }); // Listen for dismiss events OneSignal.InAppMessages.addEventListener('willDismiss', (event) => { console.log('Message about to dismiss:', event.message.messageId); }); OneSignal.InAppMessages.addEventListener('didDismiss', (event) => { console.log('Message dismissed:', event.message.messageId); }); ``` -------------------------------- ### CI/CD Setup for Disabling Location (GitHub Actions) Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/configuration.md Configure the `ONESIGNAL_DISABLE_LOCATION` environment variable at the job or step level in GitHub Actions to exclude the native location module during builds. This ensures the variable is available for dependency installation and build commands. ```yaml jobs: build: runs-on: ubuntu-latest env: ONESIGNAL_DISABLE_LOCATION: true steps: - uses: actions/checkout@v3 - name: Install iOS dependencies run: cd ios && pod install - name: Build Android run: cd android && ./gradlew assembleDebug ``` -------------------------------- ### Example: Add Multiple Triggers at Once Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/InAppMessages.md Shows how to add several triggers simultaneously using an object. This is an efficient way to set multiple conditions for in-app messages. ```javascript OneSignal.InAppMessages.addTriggers({ viewed_onboarding: 'true', user_premium: 'false', user_level: '10', last_purchase_days: '5' }); ``` -------------------------------- ### Example: Add Triggers for In-App Messages Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/InAppMessages.md Demonstrates how to add multiple triggers to control the display of in-app messages. Triggers are evaluated as key-value pairs. ```javascript // Add triggers to enable/disable messages OneSignal.InAppMessages.addTrigger('viewed_onboarding', 'true'); OneSignal.InAppMessages.addTrigger('user_premium', 'false'); OneSignal.InAppMessages.addTrigger('purchase_amount', '99.99'); ``` -------------------------------- ### Install iOS Pods with Location Disabled Source: https://github.com/onesignal/react-native-onesignal/blob/main/examples/demo-no-location/README.md Install or update iOS pods while ensuring the location module is excluded by setting the ONESIGNAL_DISABLE_LOCATION environment variable. ```sh ONESIGNAL_DISABLE_LOCATION=true bundle exec pod install ``` -------------------------------- ### Install React Native OneSignal SDK Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/README.md Use npm or yarn to add the OneSignal SDK to your React Native project. ```bash npm install react-native-onesignal # or yarn add react-native-onesignal ``` -------------------------------- ### Get Opted-In Status (Deprecated) Source: https://github.com/onesignal/react-native-onesignal/blob/main/MIGRATION_GUIDE.md This method is deprecated. Use `getOptedInAsync` instead. ```javascript OneSignal.User.pushSubscription.getOptedIn() ``` -------------------------------- ### Replace Old Initialization with New Source: https://github.com/onesignal/react-native-onesignal/blob/main/MIGRATION_GUIDE.md Replace the old `setAppId` method with the new `initialize` method for SDK setup. Ensure this is done in your app's entry point file. ```typescript OneSignal.initialize('YOUR_ONESIGNAL_APP_ID'); ``` -------------------------------- ### Example: Remove Multiple Triggers Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/InAppMessages.md Shows how to remove several triggers at once by providing an array of keys. This is efficient for clearing multiple targeting conditions. ```javascript OneSignal.InAppMessages.removeTriggers(['temporary_promo', 'flash_sale']); ``` -------------------------------- ### Get All Tags Source: https://github.com/onesignal/react-native-onesignal/blob/main/MIGRATION_GUIDE.md Retrieves all locally stored tags associated with the current user. ```APIDOC ## `OneSignal.User.getTags` ### Description Returns the local tags for the current user. ### Method Signature `OneSignal.User.getTags(): Promise>` ### Returns A promise that resolves to an object containing the user's tags. ``` -------------------------------- ### Example: Clear All Triggers Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/InAppMessages.md Demonstrates how to remove all active triggers. This resets the in-app message display logic to its default state. ```javascript OneSignal.InAppMessages.clearTriggers(); ``` -------------------------------- ### API Reference Documentation Structure Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Each API Reference file includes full method signatures with TypeScript types, parameter tables, return type documentation, behavior descriptions, code examples, source file references, and platform-specific notes. ```APIDOC ## API Reference File Structure ### Description Each API Reference file contains detailed documentation for methods and their usage within the SDK. ### Details - Full method signatures with TypeScript types - Parameter tables (name | type | required | default | description) - Return type documentation - Behavior descriptions - Real-world code examples - Source file path and line references - Platform-specific notes where applicable - Deprecation notices for legacy methods ``` -------------------------------- ### Set Push to Start Token for Live Activities Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/LiveActivities.md Call this function to indicate that the device can receive pushToStart live activity tokens for a specific activity type. This is only applicable to iOS. Ensure the activity type matches your ActivityAttributes structure. ```typescript export namespace LiveActivities { export function setPushToStartToken( activityType: string, token: string, ): void; } ``` ```javascript import { OneSignal } from 'react-native-onesignal'; import { Platform } from 'react-native'; if (Platform.OS === 'ios') { OneSignal.LiveActivities.setPushToStartToken( 'OrderActivityAttributes', 'pushtostart_token_123' ); } ``` -------------------------------- ### Run iOS App Source: https://github.com/onesignal/react-native-onesignal/blob/main/examples/demo/README.md Builds and runs the React Native application on an iOS simulator or device. Ensure Metro is running and CocoaPods dependencies are installed. ```sh # Using npm npm run ios # OR using Yarn yarn ios ``` -------------------------------- ### Add Multiple User Aliases Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/User.md Efficiently set multiple aliases for the user in one call. Existing aliases with the same label will be overwritten. Ideal for bulk updates or initial user setup. ```javascript OneSignal.User.addAliases({ email: 'user@example.com', username: 'john_doe', phone: '+1234567890' }); ``` -------------------------------- ### Handle OneSignal Initialization Errors Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/README.md Always check for initialization before calling OneSignal methods. This example demonstrates how to use a try-catch block to handle potential errors during the retrieval of the OneSignal ID. ```typescript try { const onesignalId = await OneSignal.User.getOnesignalId(); if (!onesignalId) { console.log('OneSignal ID not yet assigned'); } } catch (error) { console.error('Error:', error.message); } ``` -------------------------------- ### Handle Native Notification Permission Status Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/Notifications.md Example of how to use the permissionNative() function and handle the different OSNotificationPermission enum values in a switch statement. Includes error handling for the promise. ```javascript import { OneSignal, OSNotificationPermission } from 'react-native-onesignal'; try { const permission = await OneSignal.Notifications.permissionNative(); switch (permission) { case OSNotificationPermission.NotDetermined: console.log('Not yet determined'); break; case OSNotificationPermission.Denied: console.log('Denied'); break; case OSNotificationPermission.Authorized: console.log('Authorized'); break; case OSNotificationPermission.Provisional: console.log('Provisional (iOS 12+)'); break; case OSNotificationPermission.Ephemeral: console.log('Ephemeral (iOS 14+)'); break; } } catch (error) { console.error('Error:', error.message); } ``` -------------------------------- ### Initialize React Native Project Source: https://github.com/onesignal/react-native-onesignal/blob/main/examples/build.md Use the React Native CLI to create a new TypeScript-enabled project. ```bash npx @react-native-community/cli init demo --template react-native-template-typescript mv demo examples/demo ``` -------------------------------- ### getOptedInAsync() Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/PushSubscription.md Gets whether the user is currently opted in to push notifications. Returns true if the app has notifications permission and optOut() has not been called. It does not take into account the existence of the subscription ID and push token. This boolean may return true but push notifications may still not be received by the user if there are platform-level permission issues. ```APIDOC ## getOptedInAsync() ### Description Gets whether the user is currently opted in to push notifications. ### Method `async` ### Returns `Promise` — True if the user is opted in, false otherwise. ### Description Returns true when the app has notifications permission and `optOut()` has not been called. Does not take into account the existence of the subscription ID and push token. This boolean may return true but push notifications may still not be received by the user if there are platform-level permission issues. ### Example ```javascript try { const isOptedIn = await OneSignal.User.pushSubscription.getOptedInAsync(); console.log('User is opted in:', isOptedIn); } catch (error) { console.error('Error:', error.message); } ``` ``` -------------------------------- ### Initialization and Authentication Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/README.md Methods for initializing the SDK with your App ID and logging in users with an external ID. ```APIDOC ## Initialize ### Description Initializes the OneSignal SDK with your application ID. ### Method `OneSignal.initialize(appId)` ### Parameters - **appId** (string) - Required - Your OneSignal application ID. ## Login ### Description Logs in a user with an external ID. This is useful for associating OneSignal user data with your own user accounts. ### Method `OneSignal.login(externalId)` ### Parameters - **externalId** (string) - Required - The unique identifier for the external user. ## Logout ### Description Logs out the current user. This will clear OneSignal data associated with the logged-in user. ### Method `OneSignal.logout()` ``` -------------------------------- ### LiveActivitySetupOptions Type Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/types.md Defines configuration options for setting up default live activities. Use this to control whether push-to-start and push-to-update tokens are enabled. ```typescript export type LiveActivitySetupOptions = { enablePushToStart: boolean; enablePushToUpdate: boolean; }; ``` -------------------------------- ### Initialize OneSignal SDK Source: https://github.com/onesignal/react-native-onesignal/blob/main/MIGRATION_GUIDE.md Initializes the OneSignal SDK. This should be called during application startup. ```javascript OneSignal.initialize("YOUR_ONESIGNAL_APP_ID") ``` -------------------------------- ### Initialize OneSignal SDK Source: https://github.com/onesignal/react-native-onesignal/blob/main/examples/build.md Configure SDK logging, consent settings, and initialize the SDK with your application ID. This should be done early in your application's lifecycle. ```typescript OneSignal.Debug.setLogLevel(LogLevel.Verbose); OneSignal.setConsentRequired(cachedConsentRequired); OneSignal.setConsentGiven(cachedPrivacyConsent); OneSignal.initialize(appId); ``` -------------------------------- ### Disable Location Module with Pod Install (iOS) Source: https://github.com/onesignal/react-native-onesignal/blob/main/README.md Use this command to disable the native location module for iOS builds when installing pods. Ensure the environment variable is set before running. ```sh ONESIGNAL_DISABLE_LOCATION=true pod install # iOS, from the ios directory ``` -------------------------------- ### Run the Demo Source: https://github.com/onesignal/react-native-onesignal/blob/main/examples/demo-no-location/README.md Execute these commands to run the OneSignal no-location demo on iOS and Android. ```sh vp run ios vp run android ``` -------------------------------- ### Initialize OneSignal and Add Listeners Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/README.md Initialize the SDK with your App ID and set up a listener for notification clicks. Ensure initialization happens during app startup. For user-specific features, log in the user after initialization. ```typescript import { OneSignal, LogLevel } from 'react-native-onesignal'; // Initialize during app startup OneSignal.initialize('your-app-id'); // Add listeners OneSignal.Notifications.addEventListener('click', (event) => { console.log('Notification clicked:', event.notification.title); }); // For user-centric apps, login the user OneSignal.login('user-123'); ``` -------------------------------- ### Get OneSignal ID Source: https://github.com/onesignal/react-native-onesignal/blob/main/MIGRATION_GUIDE.md Asynchronously retrieves the OneSignal ID for the current user. ```APIDOC ## `OneSignal.User.getOnesignalId` ### Description Returns the OneSignal ID for the current user, which can be null if it is not yet available. ### Method Signature `await OneSignal.User.getOnesignalId(): string | null` ### Returns A promise that resolves to the OneSignal ID string, or null if not available. ``` -------------------------------- ### Swift Code for Widget Bundle Entry Point Source: https://github.com/onesignal/react-native-onesignal/blob/main/examples/build-ios.md The main entry point for the widget bundle, registering the Live Activity widget. This struct should be marked with `@main`. ```swift import WidgetKit import SwiftUI @main struct OneSignalWidgetBundle: WidgetBundle { var body: some Widget { OneSignalWidgetLiveActivity() } } ``` -------------------------------- ### Get Push Subscription Token (Deprecated) Source: https://github.com/onesignal/react-native-onesignal/blob/main/MIGRATION_GUIDE.md This method is deprecated. Use `getTokenAsync` instead. ```javascript OneSignal.User.pushSubscription.getPushSubscriptionToken() ``` -------------------------------- ### Initialize OneSignal SDK Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/OneSignal.md Initializes the OneSignal SDK. Must be called during application startup before using any other OneSignal functionality. Automatically sets up permission and push subscription observers. ```typescript export namespace OneSignal { export function initialize(appId: string): void; } ``` ```javascript import { OneSignal } from 'react-native-onesignal'; // In your App component or at startup OneSignal.initialize('your-app-id-here'); ``` -------------------------------- ### Get Push Subscription ID (Deprecated) Source: https://github.com/onesignal/react-native-onesignal/blob/main/MIGRATION_GUIDE.md This method is deprecated. Use `getIdAsync` instead. ```javascript OneSignal.User.pushSubscription.getPushSubscriptionId() ``` -------------------------------- ### Get External ID Source: https://github.com/onesignal/react-native-onesignal/blob/main/MIGRATION_GUIDE.md Asynchronously retrieves the external ID set for the current user. ```APIDOC ## `OneSignal.User.getExternalId` ### Description Returns the External ID for the current user, which can be null if not set. ### Method Signature `await OneSignal.User.getExternalId(): string | null` ### Returns A promise that resolves to the external ID string, or null if not set. ``` -------------------------------- ### Get Opted-In Status Async Source: https://github.com/onesignal/react-native-onesignal/blob/main/MIGRATION_GUIDE.md Gets a boolean value indicating whether the current user is opted in to push notifications. This returns `true` when the app has notifications permission and `optOut()` is not called. Note: This boolean may return `true` but push notifications may still not be received by the user if the subscription ID and push token do not exist. ```javascript await OneSignal.User.pushSubscription.getOptedInAsync() ``` -------------------------------- ### optIn() Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/PushSubscription.md Enables the push notification subscription. Subscribes the user to push notifications. Requires that the user has already granted permission at the OS level. ```APIDOC ## optIn() ### Description Enables the push notification subscription. ### Method `void` ### Returns void ### Description Subscribes the user to push notifications. Requires that the user has already granted permission at the OS level. ### Example ```javascript OneSignal.User.pushSubscription.optIn(); console.log('User opted in to push notifications'); ``` ``` -------------------------------- ### Get Push Subscription Token Async Source: https://github.com/onesignal/react-native-onesignal/blob/main/MIGRATION_GUIDE.md Retrieves the readonly push token for the current user. This is an asynchronous operation. ```javascript await OneSignal.User.pushSubscription.getTokenAsync() ``` -------------------------------- ### Initialize OneSignal SDK Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/configuration.md Call `initialize()` during app startup, before using any other OneSignal methods. Replace 'your-app-id' with your actual OneSignal App ID. ```typescript import { OneSignal } from 'react-native-onesignal'; // Call during app startup OneSignal.initialize('your-app-id'); ``` -------------------------------- ### Package.json Main Entry Point Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/configuration.md Specifies the main JavaScript file and type definitions for the OneSignal React Native SDK package. ```json { "main": "dist/index.js", "types": "dist/index.d.ts" } ``` -------------------------------- ### InAppMessages - Get Paused Status Source: https://github.com/onesignal/react-native-onesignal/blob/main/MIGRATION_GUIDE.md Retrieves the current paused status of in-app messaging. If true, no in-app messages will be displayed. ```APIDOC ## getPaused ### Description Checks if in-app messaging is currently paused for the user. ### Method `OneSignal.InAppMessages.getPaused()` ### Returns - `Promise`: A promise that resolves to `true` if in-app messages are paused, `false` otherwise. ``` -------------------------------- ### Get Push Subscription ID Async Source: https://github.com/onesignal/react-native-onesignal/blob/main/MIGRATION_GUIDE.md Retrieves the readonly push subscription ID for the current user. This is an asynchronous operation. ```javascript await OneSignal.User.pushSubscription.getIdAsync() ``` -------------------------------- ### Info.plist Configuration Source: https://github.com/onesignal/react-native-onesignal/blob/main/examples/build-ios.md Configure the Info.plist file for the Notification Service Extension. Ensure all standard CFBundle keys are present for simulator compatibility. ```xml CFBundleDisplayName OneSignalNotificationServiceExtension CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType $(PRODUCT_BUNDLE_PACKAGE_TYPE) CFBundleShortVersionString $(MARKETING_VERSION) CFBundleVersion $(CURRENT_PROJECT_VERSION) NSExtension NSExtensionPointIdentifier com.apple.usernotifications.service NSExtensionPrincipalClass $(PRODUCT_MODULE_NAME).NotificationService ``` -------------------------------- ### permissionNative() Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/Notifications.md Gets the native OS-level notification permission enum. This method is iOS only and returns the current permission status of the device. ```APIDOC ## permissionNative() ### Description Gets the native OS-level notification permission enum. iOS only. Returns the enum for the native permission of the device. ### Method Signature `Notifications.permissionNative(): Promise` ### Returns `Promise` - One of: - `OSNotificationPermission.NotDetermined` (0) - `OSNotificationPermission.Denied` (1) - `OSNotificationPermission.Authorized` (2) - `OSNotificationPermission.Provisional` (3) — iOS 12+ only - `OSNotificationPermission.Ephemeral` (4) — iOS 14+ only ### Example ```javascript import { OneSignal, OSNotificationPermission } from 'react-native-onesignal'; try { const permission = await OneSignal.Notifications.permissionNative(); switch (permission) { case OSNotificationPermission.NotDetermined: console.log('Not yet determined'); break; case OSNotificationPermission.Denied: console.log('Denied'); break; case OSNotificationPermission.Authorized: console.log('Authorized'); break; case OSNotificationPermission.Provisional: console.log('Provisional (iOS 12+)'); break; case OSNotificationPermission.Ephemeral: console.log('Ephemeral (iOS 14+)'); break; } } catch (error) { console.error('Error:', error.message); } ``` ``` -------------------------------- ### Initialize OneSignal and Add Listeners Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/README.md Initializes the OneSignal SDK, enables debug logging, and sets up event listeners for notifications and user changes. Remember to clean up listeners when the component unmounts. ```typescript import { OneSignal, LogLevel } from 'react-native-onesignal'; import { useEffect } from 'react'; export function App() { useEffect(() => { // Initialize OneSignal.initialize('your-app-id'); // Enable debug logging OneSignal.Debug.setLogLevel(LogLevel.Debug); // Add notification listeners OneSignal.Notifications.addEventListener('click', handleNotificationClick); OneSignal.Notifications.addEventListener('foregroundWillDisplay', handleForegroundNotification); // Add user listeners OneSignal.User.addEventListener('change', handleUserChange); return () => { // Cleanup listeners OneSignal.Notifications.removeEventListener('click', handleNotificationClick); }; }, []); return ; } ``` -------------------------------- ### Get Push Subscription Token Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/PushSubscription.md Retrieves the platform-specific push notification token. This token is necessary for sending server-side push notifications. ```typescript export namespace pushSubscription { export async function getTokenAsync(): Promise; } ``` ```javascript try { const token = await OneSignal.User.pushSubscription.getTokenAsync(); if (token) { console.log('Push token:', token); // Send to your backend for server-side push notifications } else { console.log('No push token available yet'); } } catch (error) { console.error('Error:', error.message); } ``` -------------------------------- ### Get Native Notification Permission Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/Notifications.md Retrieves the native OS-level notification permission enum. This is iOS-only and returns the current permission status. ```typescript export namespace Notifications { export function permissionNative(): Promise; } ``` -------------------------------- ### Core API Reference - Initialization and Authentication Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/README.md Core initialization and authentication methods for the OneSignal SDK. ```APIDOC ## initialize() ### Description Initializes the OneSignal SDK with your application's ID. ### Method `OneSignal.initialize(appId: string)` ### Parameters #### Path Parameters - **appId** (string) - Required - Your OneSignal application ID. ``` ```APIDOC ## login(userId: string) ### Description Logs in a user with a unique identifier. This is recommended for user-centric applications to enable features like user-specific data and targeting. ### Method `OneSignal.login(userId: string)` ### Parameters #### Path Parameters - **userId** (string) - Required - A unique identifier for the user. ``` ```APIDOC ## logout() ### Description Logs out the current user. This should be called when the user is no longer active or has logged out of your application. ### Method `OneSignal.logout()` ``` ```APIDOC ## setConsentRequired(required: boolean) ### Description Configures whether user consent is required for OneSignal to function, typically for GDPR compliance. ### Method `OneSignal.setConsentRequired(required: boolean)` ### Parameters #### Path Parameters - **required** (boolean) - Required - Set to `true` if consent is required, `false` otherwise. ``` ```APIDOC ## setConsentGiven(given: boolean) ### Description Sets whether the user has given consent for OneSignal to operate. This should be called after `setConsentRequired(true)` and after obtaining user consent. ### Method `OneSignal.setConsentGiven(given: boolean)` ### Parameters #### Path Parameters - **given** (boolean) - Required - Set to `true` if consent has been given, `false` otherwise. ``` -------------------------------- ### Key Files Structure Source: https://github.com/onesignal/react-native-onesignal/blob/main/examples/build.md Overview of the directory structure for the OneSignal React Native demo application. This helps in understanding the organization of source files, services, components, and platform-specific configurations. ```tree examples/demo/ ├── App.tsx ├── index.js ├── app.json ├── babel.config.js ├── metro.config.js ├── package.json ├── tsconfig.json ├── assets/ ├── types/ │ ├── env.d.ts │ └── svg.d.ts ├── src/ │ ├── theme.ts │ ├── models/ │ │ ├── UserData.ts │ │ ├── NotificationType.ts │ │ └── InAppMessageType.ts │ ├── services/ │ │ ├── OneSignalApiService.ts │ │ ├── PreferencesService.ts │ │ └── TooltipHelper.ts │ ├── hooks/ │ │ └── useOneSignal.ts │ ├── screens/ │ │ ├── HomeScreen.tsx │ │ └── SecondaryScreen.tsx │ └── components/ │ ├── AppHeader.tsx │ ├── ToastProvider.tsx │ ├── SectionCard.tsx │ ├── ToggleRow.tsx │ ├── ActionButton.tsx │ ├── ListWidgets.tsx │ ├── modals/ │ │ ├── SingleInputModal.tsx │ │ ├── PairInputModal.tsx │ │ ├── MultiPairInputModal.tsx │ │ ├── MultiSelectRemoveModal.tsx │ │ ├── OutcomeModal.tsx │ │ ├── TrackEventModal.tsx │ │ ├── CustomNotificationModal.tsx │ │ └── TooltipModal.tsx │ └── sections/ │ ├── AppSection.tsx │ ├── UserSection.tsx │ ├── PushSection.tsx │ ├── SendPushSection.tsx │ ├── InAppSection.tsx │ ├── SendIamSection.tsx │ ├── AliasesSection.tsx │ ├── EmailsSection.tsx │ ├── SmsSection.tsx │ ├── TagsSection.tsx │ ├── OutcomesSection.tsx │ ├── TriggersSection.tsx │ ├── CustomEventsSection.tsx │ ├── LocationSection.tsx │ └── LiveActivitySection.tsx ├── android/ └── ios/ ``` -------------------------------- ### Example: Remove a Single Trigger Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/InAppMessages.md Demonstrates how to remove a specific trigger by its key. This is useful when a condition is no longer relevant for in-app message targeting. ```javascript OneSignal.InAppMessages.removeTrigger('temporary_promo'); ``` -------------------------------- ### Documented Features Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt The SDK documentation covers a wide range of features including core functionality, user management, push notifications, in-app messaging, live activities, location services, and analytics. ```APIDOC ## Documented Features ### Core Functionality - SDK Initialization - User Authentication (login/logout) - Privacy Consent (GDPR) - Debug Logging ### User Management - User Identity (OneSignal ID, External ID) - User Attributes (language, tags, aliases) - Contact Methods (email, SMS) - Custom Events - User State Listeners ### Push Notifications - Permission Management - Permission Checking - iOS Provisional Authorization - Native Permission Enum - Push Token Access - Opt-in/Opt-out Control - Notification Listeners (click, foreground, permission) - Notification Control (clear, remove) - Foreground Notification Handling ### In-App Messaging - Message Listeners (click, display, dismiss) - Trigger Management - Message Pausing ### Live Activities - Activity Lifecycle (iOS) - PushToStart/PushToUpdate Tokens (iOS) - Default Live Activity Setup (iOS) ### Location - Permission Requests - Location Collection Control - Location Sharing Status ### Analytics - Outcome Tracking - Custom Event Tracking - Attribution Windows ``` -------------------------------- ### OneSignal.initialize() Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/OneSignal.md Initializes the OneSignal SDK with your application ID. This must be called during application startup before any other OneSignal functions. ```APIDOC ## initialize() ### Description Initializes the OneSignal SDK during application startup. ### Method `initialize` ### Parameters #### Path Parameters - **appId** (string) - Required - Your OneSignal application ID ### Request Example ```javascript import { OneSignal } from 'react-native-onesignal'; // In your App component or at startup OneSignal.initialize('your-app-id-here'); ``` ### Response #### Success Response (void) void ### Description Must be called during application startup before using any other OneSignal functionality. Automatically sets up permission and push subscription observers. ``` -------------------------------- ### SDK Initialization Source: https://github.com/onesignal/react-native-onesignal/blob/main/MIGRATION_GUIDE.md The OneSignal SDK is now initialized using the `initialize` method. Replace the older `setAppId` with `OneSignal.initialize('YOUR_ONESIGNAL_APP_ID')`. ```APIDOC ## Initialization ### Description Initializes the OneSignal SDK with your application ID. ### Method `OneSignal.initialize(appId: string)` ### Parameters * **appId** (string) - Required - Your OneSignal Application ID. ### Request Example ```typescript OneSignal.initialize('YOUR_ONESIGNAL_APP_ID'); ``` ``` -------------------------------- ### Get Push Subscription Token (Deprecated) Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/PushSubscription.md Deprecated method to retrieve the push subscription token. Use `getTokenAsync()` instead. Returns an empty string if not available. ```typescript export namespace pushSubscription { export function getPushSubscriptionToken(): string; } ``` -------------------------------- ### Core API Reference - Live Activities Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/README.md Manages iOS Live Activities, including lifecycle events and token management. ```APIDOC ## Live Activity Lifecycle Events ### Description Add listeners to track the lifecycle of Live Activities on iOS, such as entering or exiting an activity. ### Method `OneSignal.LiveActivities.addEventListener(type: 'enter' | 'exit', handler: (activityId: string) => void)` `OneSignal.LiveActivities.removeEventListener(type: 'enter' | 'exit', handler: (activityId: string) => void)` ### Parameters #### Path Parameters - **type** (string) - Required - The type of lifecycle event ('enter' or 'exit'). - **handler** (function) - Required - The callback function to execute when the specified event occurs. It receives the `activityId`. ``` ```APIDOC ## Live Activity Token Management ### Description Provides methods to obtain tokens required for updating Live Activities. ### Method `OneSignal.LiveActivities.getPushToStartToken(activityId: string): Promise` `OneSignal.LiveActivities.getPushToUpdateToken(activityId: string): Promise` ### Parameters #### Path Parameters - **activityId** (string) - Required - The unique identifier of the Live Activity. ``` ```APIDOC ## Default Live Activity Setup (iOS Only) ### Description Configures the default Live Activity setup for iOS applications. ### Method `OneSignal.LiveActivities.setDefaultConfiguration(options: LiveActivitySetupOptions)` ### Parameters #### Path Parameters - **options** (LiveActivitySetupOptions) - Required - An object containing configuration options for the default Live Activity setup. ``` -------------------------------- ### Get Push Subscription ID (Deprecated) Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/PushSubscription.md Deprecated method to retrieve the push subscription ID. Use `getIdAsync()` instead. Returns an empty string if not available. ```typescript export namespace pushSubscription { export function getPushSubscriptionId(): string; } ``` -------------------------------- ### Get Push Subscription ID Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/PushSubscription.md Retrieves the OneSignal subscription ID for the current push subscription. Use this when you need the unique identifier for a device's subscription. ```typescript export namespace pushSubscription { export async function getIdAsync(): Promise; } ``` ```javascript try { const subscriptionId = await OneSignal.User.pushSubscription.getIdAsync(); if (subscriptionId) { console.log('Subscription ID:', subscriptionId); } else { console.log('No subscription ID available yet'); } } catch (error) { console.error('Error:', error.message); } ``` -------------------------------- ### Info.plist Configuration for Widget Extension Source: https://github.com/onesignal/react-native-onesignal/blob/main/examples/build-ios.md Standard CFBundle keys for the widget extension's Info.plist file. Ensure the CFBundleIdentifier matches your Xcode target name. ```xml CFBundleDisplayName OneSignalWidgetExtension CFBundleExecutable $(EXECUTABLE_NAME) CFBundleIdentifier $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName $(PRODUCT_NAME) CFBundlePackageType $(PRODUCT_BUNDLE_PACKAGE_TYPE) CFBundleShortVersionString $(MARKETING_VERSION) CFBundleVersion $(CURRENT_PROJECT_VERSION) NSExtension NSExtensionPointIdentifier com.apple.widgetkit-extension ``` -------------------------------- ### Restore SDK State Before Initialization Source: https://github.com/onesignal/react-native-onesignal/blob/main/examples/build.md Restore consent flags and privacy consent from AsyncStorage before initializing the OneSignal SDK. This ensures the SDK starts with the correct user consent status. ```typescript OneSignal.setConsentRequired(cachedConsentRequired); OneSignal.setConsentGiven(cachedPrivacyConsent); OneSignal.initialize(appId); ``` -------------------------------- ### Generate App Icons Source: https://github.com/onesignal/react-native-onesignal/blob/main/examples/build.md Execute a script to generate app icons for the React Native project. ```bash bun examples/generate-icons.ts ``` -------------------------------- ### Live Activities (iOS Only) Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/README.md Methods for managing Live Activities on iOS, including entering, exiting, and setting up tokens. ```APIDOC ## LiveActivities: Enter ### Description Enters a Live Activity. ### Method `OneSignal.LiveActivities.enter(activityId, token, handler)` ### Parameters - **activityId** (string) - Required - The ID of the Live Activity. - **token** (string) - Required - The push token for the Live Activity. - **handler** (function) - Required - A callback function to handle the result. ## LiveActivities: Exit ### Description Exits a Live Activity. ### Method `OneSignal.LiveActivities.exit(activityId, handler)` ### Parameters - **activityId** (string) - Required - The ID of the Live Activity. - **handler** (function) - Required - A callback function to handle the result. ## LiveActivities: Set Push To Start Token ### Description Sets the push token for starting a Live Activity. ### Method `OneSignal.LiveActivities.setPushToStartToken(activityType, token)` ### Parameters - **activityType** (string) - Required - The type of the Live Activity. - **token** (string) - Required - The push token. ## LiveActivities: Remove Push To Start Token ### Description Removes the push token for starting a Live Activity. ### Method `OneSignal.LiveActivities.removePushToStartToken(activityType)` ### Parameters - **activityType** (string) - Required - The type of the Live Activity. ## LiveActivities: Setup Default ### Description Sets up default options for Live Activities. ### Method `OneSignal.LiveActivities.setupDefault(options)` ### Parameters - **options** (object) - Required - An object containing default options. ## LiveActivities: Start Default ### Description Starts a default Live Activity. ### Method `OneSignal.LiveActivities.startDefault(activityId, attributes, content)` ### Parameters - **activityId** (string) - Required - The ID of the Live Activity. - **attributes** (object) - Required - An object containing activity attributes. - **content** (object) - Required - An object containing activity content. ``` -------------------------------- ### Get and Set In-App Message Pause State Source: https://github.com/onesignal/react-native-onesignal/blob/main/MIGRATION_GUIDE.md Check if in-app messaging is currently paused. Set the pause state to true to prevent any IAMs from being presented, or false to allow them. ```javascript await OneSignal.InAppMessages.getPaused() OneSignal.InAppMessages.setPaused(true) ``` -------------------------------- ### Add OneSignal Pods to Podfile Source: https://github.com/onesignal/react-native-onesignal/blob/main/examples/build-ios.md Add these extension targets to your Podfile to integrate OneSignal's push notification and live activity services. ```ruby target 'OneSignalNotificationServiceExtension' do pod 'OneSignalXCFramework', '>= 5.0.0', '< 6.0' end target 'OneSignalWidgetExtension' do pod 'OneSignalXCFramework', '>= 5.0.0', '< 6.0' end ``` -------------------------------- ### getPermissionAsync Source: https://github.com/onesignal/react-native-onesignal/blob/main/_autodocs/api-reference/Notifications.md Gets whether the application has push notification permission. Returns true if the user has accepted permissions, or if the app has ephemeral (iOS 14+) or provisional (iOS 12+) permission. ```APIDOC ## getPermissionAsync() ### Description Gets whether the application has push notification permission. Returns true if the user has accepted permissions, or if the app has ephemeral (iOS 14+) or provisional (iOS 12+) permission. ### Method `async` ### Returns `Promise` — True if user has accepted permissions or has ephemeral/provisional permission, false otherwise ### Example ```javascript try { const hasPermission = await OneSignal.Notifications.getPermissionAsync(); if (hasPermission) { console.log('App has notification permission'); } else { console.log('App does not have notification permission'); } } catch (error) { console.error('Error:', error.message); } ``` ``` -------------------------------- ### Configure Info.plist for Background and Live Activities Source: https://github.com/onesignal/react-native-onesignal/blob/main/examples/build-ios.md Add 'UIBackgroundModes' with 'remote-notification' and 'NSSupportsLiveActivities' set to true in your Info.plist to support background notifications and live activities. ```xml UIBackgroundModes remote-notification NSSupportsLiveActivities ``` -------------------------------- ### OneSignal.logout() Source: https://github.com/onesignal/react-native-onesignal/blob/main/MIGRATION_GUIDE.md Logs out the currently logged-in user. After logout, the user property refers to a new device-scoped user, which lacks persistent identity beyond the current app installation and data state. ```APIDOC ## OneSignal.logout() ### Description Logs out the user previously logged in via `login`. The `user` property now references a new device-scoped user. A device-scoped user has no user identity that can later be retrieved, except through this device as long as the app remains installed and the app data is not cleared. ### Method ```javascript OneSignal.logout() ``` ```