### Example: Full Startup Wiring Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode This example demonstrates the complete setup for handling FCM messages, including background message handling and foreground configuration. ```typescript // Example: full startup wiring // 1. Handle background messages import messaging from '@react-native-firebase/messaging'; async function onMessageReceived(remoteMessage) { await handleFcmMessage(remoteMessage); } messaging().setBackgroundMessageHandler(onMessageReceived); // 2. Handle foreground messages import notifee from '@notifee/react-native'; async function onForegroundMessageReceived(remoteMessage) { await notifee.displayNotification(remoteMessage.notification); } messaging().onMessage(onForegroundMessageReceived); // 3. Set FCM config (optional) await notifee.setFcmConfig({ // ... config options }); ``` -------------------------------- ### Install Pods Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/ios/remote-notification-support After updating the Podfile, run this command to install the necessary dependencies. ```bash cd ios && pod install --repo-update ``` -------------------------------- ### Full notifee_options Schema Example Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode A comprehensive example of the `notifee_options` payload structure, demonstrating various configuration options for both Android and iOS notifications. ```json { "_v": 1, "title": "Order received", "body": "We're preparing your food.", "android": { "channelId": "orders", "smallIcon": "ic_notification", "largeIcon": "https://cdn.example.com/avatar.png", "color": "#4CAF50", "pressAction": { "id": "open-order", "launchActivity": "default" }, "actions": [ { "title": "Accept", "pressAction": { "id": "accept" } }, { "title": "Decline", "pressAction": { "id": "decline" }, "input": true }, ], "style": { "type": "BIG_TEXT", "text": "Long body text ..." }, }, "ios": { "sound": "default", "categoryId": "ORDER_UPDATE", "threadId": "orders-thread", "interruptionLevel": "timeSensitive", "attachments": [ { "url": "https://cdn.example.com/orders/42.png", "identifier": "attachment-0" }, ], }, } ``` -------------------------------- ### Install Dependencies Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Install the main package along with Firebase app and messaging modules. These are required for both the CLI and server SDK. ```bash yarn add react-native-notify-kit @react-native-firebase/app @react-native-firebase/messaging ``` -------------------------------- ### iOS NSE Setup: Bare React Native CLI Setup Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Steps to set up the Native Notification Service Extension (NSE) for a bare React Native CLI project. This involves manual configuration within Xcode. ```bash # 1. Create a new 'Notification Service Extension' target in Xcode. # 2. Copy the contents of the NotifyKit NSE template into your new target. # 3. Update the build settings and Info.plist as required by NotifyKit. ``` -------------------------------- ### Troubleshooting: pod install fails after NSE generation Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Steps to resolve `pod install` failures that occur after generating the Native Notification Service Extension (NSE). ```bash # Clean and reinstall pods: cd ios pod deintegrate pod clean pod install ``` -------------------------------- ### iOS NSE Setup: Expo CNG Setup Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Instructions for setting up the Native Notification Service Extension (NSE) when using Expo's Custom Native Code (CNG) or development builds. ```bash # Follow the Expo documentation for setting up custom native code. # Ensure the NotifyKit NSE is correctly configured within your project structure. ``` -------------------------------- ### Handle Quick Action Press in Background Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/ios/interaction Listen for background events to handle user interaction with Quick Actions. This example specifically logs when the 'mark-as-read' action is pressed. ```javascript import notifee, { EventType } from 'react-native-notify-kit'; notifee.onBackgroundEvent(async ({ type, detail }) => { if (type === EventType.ACTION_PRESS && detail.pressAction.id === 'mark-as-read') { console.log('User pressed the "Mark as read" action.'); } }); ``` -------------------------------- ### Install React Native Notify Kit with npm or Yarn Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/installation Install the package at the root of your React Native project using either npm or Yarn. ```bash # Using npm npm install --save react-native-notify-kit # Using Yarn yarn add react-native-notify-kit ``` -------------------------------- ### Install Expo Build Properties Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/installation Install the expo-build-properties package to manage Android SDK versions in your Expo project. ```bash npx expo install expo-build-properties ``` -------------------------------- ### iOS Notification Service Extension (NSE) Setup Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Instructions for setting up the Notification Service Extension (NSE) on iOS, which is required to rewrite incoming APNs notifications before they are displayed. Two setup paths are provided: Expo CNG/prebuild and Bare React Native CLI. ```APIDOC ## iOS Notification Service Extension (NSE) Setup iOS requires a Notification Service Extension (NSE) to rewrite incoming APNs notifications before display. FCM Mode has two automated setup paths: * **Expo CNG / prebuild**: Use the config plugin. * **Bare React Native**: Use the `init-nse` CLI. ### Expo CNG Setup Use the Expo CNG / development builds setup. The plugin runs during prebuild and generates the necessary Swift service, `Info.plist`, entitlements, Xcode target, host dependency, `.appex` embed phase, EAS `appExtensions` entry, and Podfile target. Do not use `npx react-native-notify-kit init-nse` as the primary Expo setup path. Generated Expo native folders are disposable, so the plugin is the durable source of truth. ### Bare React Native CLI Setup ```bash npx react-native-notify-kit init-nse cd ios && pod install ``` **What the bare CLI does:** 1. **Auto-detects** your iOS project (`ios/*.xcodeproj` or `.xcworkspace`) and your main app target's bundle ID. 2. **Creates** three files under `ios/NotifyKitNSE/`: * `NotificationService.swift` — calls `NotifeeExtensionHelper.populateNotificationContent(...)` to apply `notifee_options`. * `Info.plist` — sets `NSExtensionPointIdentifier = com.apple.usernotifications.service` and the principal class. * `NotifyKitNSE.entitlements` — an empty file (extend if you need App Groups for cross-target data sharing). 3. **Patches** `ios/Podfile` — adds a `target 'NotifyKitNSE'` block nested inside your app target with `inherit! :search_paths`. The `RNNotifeeCore` pod is added as a dependency of the NSE target only (not the main app) to avoid the duplicate-symbols linker error. 4. **Patches** `ios/YourApp.xcodeproj/project.pbxproj` — adds the NSE native target with build phases, inherits signing from the parent target, and sets `PRODUCT_BUNDLE_IDENTIFIER = .NotifyKitNSE`. 5. **Backs up** the Podfile and `.pbxproj` before every edit (PID-stamped backups, atomic writes, rollback on failure). Open Xcode after `pod install`, verify the `NotifyKitNSE` target's signing (it should inherit from your app target), build, and you're done. ``` -------------------------------- ### Get System Notification Sounds and Create Channel Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/android/behaviour Retrieve a list of system notification sounds using `react-native-notification-sounds` and set one as the sound for a notification channel. This example demonstrates using the URL of the first sound in the retrieved list. ```javascript import NotificationSounds from 'react-native-notification-sounds'; import notifee from 'react-native-notify-kit'; // Retrieve a list of system notification sounds const soundsList = await NotificationSounds.getNotifications('notification'); await notifee.createChannel({ id: 'custom-sound', name: 'System Sound', // Set sound to Aldebaran // (url: "content://media/internal/audio/media/30") sound: soundsList[0].url, }); ``` -------------------------------- ### iOS: Initialize Notification Service Extension (Bare React Native) Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode For bare React Native projects, initialize the Notification Service Extension using the `npx react-native-notify-kit init-nse` command, followed by installing pods in the `ios` directory. ```bash npx react-native-notify-kit init-nse cd ios && pod install ``` -------------------------------- ### Server SDK: Build FCM Payload Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode This example shows how to use the server SDK to construct a unified FCM payload that works for both Android and iOS when using FCM Mode. ```javascript import { buildNotifyKitPayload } from '@notifee/server'; const input = { notification: { title: 'New Message', body: 'Hello from FCM Mode!', }, data: { // Custom data payload userId: '12345', }, // Platform-specific options can be added here if needed // android: { ... }, // apns: { ... }, }; const payload = buildNotifyKitPayload(input); // Send the payload to FCM... ``` -------------------------------- ### iOS Expo Setup with Google Services Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Configure the Notification Service Extension for iOS in Expo, including the path to your Google Services file. This setup enables the default NSE target during Expo prebuild. ```javascript export default { expo: { name: 'MyApp', slug: 'my-app', ios: { bundleIdentifier: 'com.example.myapp', googleServicesFile: './GoogleService-Info.plist', }, plugins: [ [ 'react-native-notify-kit', { ios: { notificationServiceExtension: true, }, }, ], ], }, }; ``` -------------------------------- ### Migration Step 1: Server Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode The first step in migrating from a manual setup to FCM Mode involves updating the server-side payload generation. ```typescript // Server-side changes: // Replace manual payload construction with buildNotifyKitPayload // import { buildNotifyKitPayload } from "react-native-notify-kit/server"; // const payload = buildNotifyKitPayload(yourInputData); ``` -------------------------------- ### Minimal Expo Config for Android Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Example of a minimal Expo configuration object for an Android project using NotifyKit and Firebase. ```javascript export default { expo: { name: 'MyApp', slug: 'my-app', android: { package: 'com.example.yourapp', googleServicesFile: './google-services.json', }, plugins: [ '@react-native-firebase/app', '@react-native-firebase/messaging', 'react-native-notify-kit', ], }, }; ``` -------------------------------- ### Client-side Version Mismatch Log Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Example log message indicating that a client is using an older version of the library that does not support newer `notifee_options` schema versions. Clients should be updated to support new fields. ```log [react-native-notify-kit] notifee_options version 2 is newer than supported version 1. Display may be incomplete. ``` -------------------------------- ### iOS Expo Setup with Custom NSE Target Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Customize the Notification Service Extension target name and bundle suffix for iOS in Expo. This explicit configuration allows for more control over the NSE setup. ```javascript export default { expo: { name: 'MyApp', slug: 'my-app', ios: { bundleIdentifier: 'com.example.myapp', }, plugins: [ [ 'react-native-notify-kit', { ios: { notificationServiceExtension: { enabled: true, targetName: 'NotifyKitNSE', bundleSuffix: '.NotifyKitNSE', }, }, }, ], ], }, }; ``` -------------------------------- ### Notification Service Extension Log Output Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode These are example log lines from the Notification Service Extension, viewable in Console.app. They indicate the stages of notification processing and potential timeouts. ```text [NotifyKitNSE] didReceive id=... title=... hasNotifeeOptions=true requestedAttachments=1 urls=https://... [NotifyKitNSE] contentHandler id=... title=... deliveredAttachments=1 identifiers=notifee-attachment-0 [NotifyKitNSE] serviceExtensionTimeWillExpire id=... title=... deliveredAttachments=0 ``` -------------------------------- ### Handle Notification Action Presses Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Implement logic to handle user interactions with notification action buttons. This example shows how to check the `pressAction.id` in a background event listener. ```javascript notifee.onBackgroundEvent(async ({ type, detail }) => { if (type === EventType.ACTION_PRESS && detail.pressAction?.id === 'accept-order') { // ... } }); ``` -------------------------------- ### Rebuild Project for Autolinking Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/installation After installation, rebuild your React Native project to ensure autolinking is applied correctly for both iOS and Android. ```bash # For iOS cd ios/ && pod install --repo-update npx react-native run-ios # For Android npx react-native run-android ``` -------------------------------- ### Build Long Lived Task with Event Subscription Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/android/foreground-service Create a long-lived task for the foreground service that continuously runs until `stopForegroundService` is called. This example shows how to subscribe to task update events and stop the service when a task is complete. ```javascript notifee.registerForegroundService(() => { return new Promise(() => { // Example task subscriber onTaskUpdate(async task => { if (task.complete) { await notifee.stopForegroundService(); } }); }); }); ``` -------------------------------- ### Get Power Manager Info and Open Settings Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/android/background-restrictions Use this snippet to check for power management restrictions and prompt the user to open the device's power manager settings if necessary. It first retrieves information about the device's power manager and then, if an activity is available, presents an alert to the user with an option to open the relevant settings screen. ```javascript // 1. get info on the device and the Power Manager settings const powerManagerInfo = await notifee.getPowerManagerInfo(); if (powerManagerInfo.activity) { // 2. ask your users to adjust their settings Alert.alert( 'Restrictions Detected', 'To ensure notifications are delivered, please adjust your settings to prevent the app from being killed', [ // 3. try to open the vendor settings screen { text: 'OK, open settings', onPress: async () => await notifee.openPowerManagerSettings(), }, { text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel', }, ], { cancelable: false }, ); } ``` -------------------------------- ### Set Notification Categories for Quick Actions Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/ios/interaction Define notification categories with custom actions. Each action requires a unique ID and display text. This setup is necessary for enabling interactive Quick Actions. ```javascript async function setCategories() { await notifee.setNotificationCategories([ { id: 'message', actions: [ { id: 'mark-as-read', title: 'Mark as read', }, ], }, ]); } ``` -------------------------------- ### Example Notification Payload with Notifee Options Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/ios/remote-notification-support This JSON payload demonstrates how to include `notifee_options` within the APNS payload to customize notification display on iOS. `mutableContent: 1` is required for the Notification Service Extension to be invoked. ```json { "notification": { "title": "A notification title!", "body": "A notification body" }, "apns": { "payload": { "aps": { "mutableContent": 1, "contentAvailable": 1 }, "notifee_options": { "ios": { "sound": "media/kick.wav", "categoryId": "post", "attachments": [{ "url": "https://placeimg.com/640/480/any", "thumbnailHidden": true }] } } } } } ``` -------------------------------- ### Update an Existing Notification with Progress Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/android/progress-indicators Update a notification by its ID to reflect the progress of an ongoing task. This example shows how to handle 'start', 'update', and 'complete' events for an upload task. ```javascript onUploadTaskEvent(async (event, upload) => { if (event.status === 'start') { await notifee.displayNotification({ id: upload.id, android: { progress: { max: upload.size, current: 0, }, }, }); } if (event.status === 'update') { await notifee.displayNotification({ id: upload.id, android: { progress: { max: upload.size, current: upload.current, }, }, }); } if (upload.size === upload.current) { await notifee.displayNotification({ id: upload.id, title: 'Finalizing upload...', android: { progress: { indeterminate: true, }, }, }); } if (event.status === 'complete') { await notifee.cancelNotification(upload.id); } }); ``` -------------------------------- ### Initialize Notify Kit Service Extension Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Run the initialization command for bare React Native projects to set up the Notify Kit Service Extension. ```bash npx react-native-notify-kit init-nse && cd ios && pod install ``` -------------------------------- ### Run iOS Prebuild and Development Build Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Commands to prebuild the iOS project and run it on a device for development. ```bash npx expo prebuild --platform ios npx expo run:ios --device ``` -------------------------------- ### Configure Podfile for Notification Service Extension Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/ios/remote-notification-support Add this configuration to your Podfile to correctly link the NotifeeExtension. This avoids duplicate symbol linker errors when using `use_frameworks!`. ```ruby $NotifeeExtension = true target 'NotifeeNotificationService' do pod 'RNNotifeeCore', :path => '../node_modules/react-native-notify-kit/RNNotifeeCore.podspec' end ``` -------------------------------- ### Enable Native Android Logs Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/debugging Enable native logs in release mode for Android by setting a system property. ```bash adb shell setprop log.tag.NOTIFEE DEBUG ``` -------------------------------- ### Clean Prebuild for Expo Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Run a clean prebuild for iOS if native folders were generated before adding the plugin. ```bash npx expo prebuild --clean --platform ios ``` -------------------------------- ### Configure Action with Basic Input Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/ios/interaction Enable user input for an action by setting the 'input' property to true. This will automatically display an input box and send button when the action is pressed. ```javascript async function setCategories() { await notifee.setNotificationCategories([ { id: 'message', actions: [ { id: 'reply', title: 'Reply', input: true, }, ], }, ]); } ``` -------------------------------- ### Get Badge Count Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/ios/badges Retrieves the current badge count displayed on the application icon. ```javascript notifee.getBadgeCount().then(count => console.log('Current badge count: ', count)); ``` -------------------------------- ### Initialize iOS Notification Service Extension Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/installation Use the CLI command to scaffold an iOS Notification Service Extension for rich payload support with FCM. ```bash npx react-native-notify-kit init-nse ``` -------------------------------- ### Retrieve All Trigger Notification IDs Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/triggers Get a list of IDs for all pending trigger notifications. This is useful for managing or verifying scheduled notifications. ```javascript notifee.getTriggerNotificationIds().then(ids => console.log('All trigger notifications: ', ids)); ``` -------------------------------- ### Android Configuration: SDK Versions Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/installation Set the compile, target, and minimum SDK versions for your Android project. Ensure these values meet the library's baseline requirements. ```gradle buildscript { ext { compileSdkVersion = 35 targetSdkVersion = 35 minSdkVersion = 24 ... } ... } ``` -------------------------------- ### Create Notification Channel Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Create notification channels at app startup to ensure they exist before displaying notifications. The `id` must match the `channelId` sent by the server. ```javascript await notifee.createChannel({ id: 'orders', name: 'Orders', importance: AndroidImportance.HIGH, sound: 'default', // If you want a custom sound: // sound: 'my_custom_sound', // file at android/app/src/main/res/raw/my_custom_sound.mp3 }); ``` -------------------------------- ### Troubleshooting: handleFcmMessage returns null Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Explanation for why `notifee.handleFcmMessage` might return `null` and how to handle this scenario. ```markdown ## handleFcmMessage returns null `notifee.handleFcmMessage` returns `null` if the message does not contain notification content that requires display (e.g., it's a data-only message intended for background processing). ``` -------------------------------- ### Get Existing Notification Settings Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/ios/permissions Fetch the current notification permission settings without requesting new permissions. Useful for checking the user's current configuration. ```javascript async function getExistingSettings() { const settings = await notifee.getNotificationSettings(); if (settings) { console.log('Current permission settings: ', settings); } } ``` -------------------------------- ### Migration Step 3: iOS Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode The third step for migration involves setting up the Native Notification Service Extension (NSE) on iOS. ```bash # iOS NSE setup: # Follow the instructions for setting up the NSE for bare React Native CLI or Expo CNG. ``` -------------------------------- ### Parent Bundle ID Warning Example Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode This log message indicates that the parent bundle ID uses a variable, requiring manual setting of the NSE's bundle ID in Xcode. ```text Parent bundle ID uses a variable: $(PRODUCT_BUNDLE_PREFIX).MyApp The NSE bundle ID will need to be set manually in Xcode. ``` -------------------------------- ### Build and Send FCM Payload Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Example of building a notification payload using `buildNotifyKitPayload` and sending it via Firebase Admin SDK. This function handles platform-specific configurations for Android and iOS. ```typescript // server/sendNotification.ts import { buildNotifyKitPayload } from 'react-native-notify-kit/server'; import * as admin from 'firebase-admin'; admin.initializeApp(); export async function sendOrderUpdate(deviceToken: string, orderId: string) { const message = buildNotifyKitPayload({ token: deviceToken, notification: { id: `order-${orderId}`, title: 'Your order is on the way', body: 'Tap to see live tracking.', data: { orderId, screen: 'tracking' }, android: { channelId: 'orders', smallIcon: 'ic_notification', color: '#4CAF50', pressAction: { id: 'open-order', launchActivity: 'default' }, }, ios: { sound: 'default', categoryId: 'ORDER_UPDATE', interruptionLevel: 'timeSensitive', attachments: [{ url: 'https://cdn.example.com/orders/42.png' }], }, }, options: { androidPriority: 'high', iosBadgeCount: 1, ttl: 3600, }, }); await admin.messaging().send(message); } ``` -------------------------------- ### Troubleshooting: Expo prebuild did not generate NotifyKitNSE Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Steps to troubleshoot why the NotifyKit Native Notification Service Extension (NSE) was not generated after running `expo prebuild`. ```markdown ## Expo prebuild did not generate NotifyKitNSE Ensure the NotifyKit Expo config plugin is correctly added to your `app.json` or `app.config.js` and that `expo prebuild` was run successfully. ``` -------------------------------- ### Get Initial Notification on App Open Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/events Call `getInitialNotification()` early in your React lifecycle to retrieve the notification that caused the app to open. This is useful for handling specific user interactions with notifications. ```javascript import React, { useState, useEffect } from 'react'; import notifee from 'react-native-notify-kit'; function App() { const [loading, setLoading] = useState(true); // Bootstrap sequence function async function bootstrap() { const initialNotification = await notifee.getInitialNotification(); if (initialNotification) { console.log('Notification caused application to open', initialNotification.notification); console.log('Press action used to open the app', initialNotification.pressAction); } } useEffect(() => { bootstrap() .then(() => setLoading(false)) .catch(console.error); }, []); if (loading) { return null; } ... } ``` -------------------------------- ### Register Device for Remote Messages and Get Token Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/integrations/fcm Registers the device for remote messages and retrieves the FCM registration token. This token should be sent to your backend API to target specific devices. ```javascript import messaging from '@react-native-firebase/messaging'; async function registerDeviceToken() { await messaging().registerDeviceForRemoteMessages(); const token = await messaging().getToken(); await postToApi('/users/me/tokens', { token }); } ``` -------------------------------- ### Create an Interval Trigger Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/triggers Set up a notification to repeat at a specified interval. This is useful for implementing timers. Ensure the necessary imports are included. ```javascript import notifee, { IntervalTrigger, TriggerType, TimeUnit } from 'react-native-notify-kit'; const trigger: IntervalTrigger = { type: TriggerType.INTERVAL, interval: 30, timeUnit: TimeUnit.MINUTES }; ``` -------------------------------- ### Configure Action with Custom Input UI Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/ios/interaction Customize the placeholder text and send button text for an input action by providing an object to the 'input' property. This allows for a more tailored user experience. ```javascript async function setCategories() { await notifee.setNotificationCategories([ { id: 'message', actions: [ { id: 'reply', title: 'Reply', input: { placeholderText: 'Send a message...', buttonText: 'Send Now', }, }, ], }, ]); } ``` -------------------------------- ### Handle Quick Action Button Press Event Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/android/interaction Subscribe to `ACTION_PRESS` events in the foreground to identify which quick action button was pressed using its unique `id`. ```javascript import notifee, { EventType } from 'react-native-notify-kit'; notifee.onForegroundEvent(({ type, detail }) => { if (type === EventType.ACTION_PRESS && detail.pressAction.id) { console.log('User pressed an action with the id: ', detail.pressAction.id); } }); ``` -------------------------------- ### Handle Background Notifications and Badge Count Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/ios/badges Increment the badge count when a notification is displayed in the background. Decrement the count if the user presses a specific action like 'Mark as read'. Requires Firebase messaging setup. ```javascript import notifee, { EventType } from 'react-native-notify-kit'; import { firebase } from '@react-native-firebase/messaging' // Your app's background handler for incoming remote messages firebase.messaging().setBackgroundMessageHandler(async ( remoteMessage: FirebaseMessagingTypes.RemoteMessage ) => { await notifee.displayNotification(...) // Increment the count by 1 await notifee.incrementBadgeCount(); }) notifee.onBackgroundEvent(async ({ type, detail }) => { const { notification, pressAction } = detail; // Check if the user pressed the "Mark as read" action if (type === EventType.ACTION_PRESS && pressAction.id === 'mark-as-read') { // Decrement the count by 1 await notifee.decrementBadgeCount(); // Remove the notification await notifee.cancelNotification(notification.id); } }); ``` -------------------------------- ### Troubleshooting: Payload too large Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Guidance on handling FCM payload size limits and preventing 'Payload too large' errors. ```markdown ## Payload too large FCM payloads are limited to 4 KB. Ensure your notification data does not exceed this limit. Consider sending only essential information and fetching additional data from your server upon notification interaction. ``` -------------------------------- ### Initialize Notification Service Extension Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Use this command to initialize a new Notification Service Extension for React Native Notify Kit. Options allow customization of paths, names, and overwriting existing targets. ```bash npx react-native-notify-kit init-nse [options] ``` -------------------------------- ### Specify Foreground Service Types per Notification Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/android/foreground-service You can scope foreground service types per-invocation by setting the `foregroundServiceTypes` property on the notification object. This is useful when runtime permissions are granted after the service has started. If not provided, types are taken from the manifest. ```javascript import notifee, { AndroidForegroundServiceType } from 'react-native-notify-kit'; notifee.displayNotification({ title: 'Foreground service', body: 'This notification will exist for the lifetime of the service runner', android: { channelId, asForegroundService: true, foregroundServiceTypes: [ AndroidForegroundServiceType.FOREGROUND_SERVICE_TYPE_CAMERA, AndroidForegroundServiceType.FOREGROUND_SERVICE_TYPE_MICROPHONE, ], }, }); ``` -------------------------------- ### Configure Foreground Action Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/ios/interaction Set the 'foreground' property to true to force the application to open in the foreground when an action is pressed. This will trigger an ACTION_PRESS event. ```javascript async function setCategories() { await notifee.setNotificationCategories([ { id: 'message', actions: [ { id: 'view-post', title: 'View post', // Trigger the app to open in the foreground foreground: true, }, ], }, ]); } ``` -------------------------------- ### Prewarm Foreground Service Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/android/foreground-service Pre-loads foreground service classes and warms the INotificationManager Binder proxy on a background thread. This is useful for latency-sensitive apps that display notifications very early after process start. It is safe to call multiple times and has no effect on iOS. ```javascript import notifee from 'react-native-notify-kit'; // Call early in your app startup — e.g. in index.js or App.tsx notifee.prewarmForegroundService(); ``` -------------------------------- ### Configure Lights for Android Channels Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/android/behaviour Configure notification lights for Android channels. Use `lights: true` and `lightColor` for API level 26+, or an array `[color, onDuration, offDuration]` for older versions. ```javascript import notifee, { AndroidColor } from 'react-native-notify-kit'; // Android >= 8.0 (API level 26) notifee.createChannel({ id: 'custom-lights', name: 'Channel with custom lights', lights: true, lightColor: AndroidColor.RED, }); // Android < 8.0 (API level 26) notifee.displayNotification({ body: 'Custom lights', android: { lights: [AndroidColor.RED, 300, 600], }, }); ``` -------------------------------- ### Launch Application on Notification Action Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/android/interaction Use the `launchActivity` property to open the application when a notification action is pressed. Set to 'default' to use the application's default launch activity. ```javascript notifee.displayNotification({ title: 'New message', body: 'You have a new message from Sarah!', data: { chatId: '123', }, android: { channelId: 'messages', actions: [ { title: 'Open', icon: 'https://my-cdn.com/icons/open-chat.png', pressAction: { id: 'open-chat', launchActivity: 'default', }, }, ], }, }); ``` -------------------------------- ### Build iOS Development Build with EAS Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Command to build an iOS development build using EAS. ```bash eas build --profile development --platform ios ``` -------------------------------- ### Create Channel with Custom Sound (Android >= 8.0) Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/android/behaviour Set a custom sound for a notification channel on Android 8.0 (API level 26) and above. Ensure the sound file is in the `res/raw/` directory and specify it by name without the extension. ```javascript notifee.createChannel({ id: 'custom-sound', name: 'Channel with custom sound', sound: 'hollow', }); ``` -------------------------------- ### Troubleshooting: Notification appears but tap doesn't open app Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Steps to debug why a notification appears correctly, but tapping on it does not launch the application or navigate to the intended screen. ```markdown ## Notification appears but tap doesn't open app Check your deep linking configuration and ensure that the `onNotification` or `onBackgroundNotification` handlers are correctly set up to process the notification payload and navigate the user appropriately. ``` -------------------------------- ### Configure Full-Screen Action with Custom Component or Activity Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/android/behaviour Customize full-screen notifications by specifying a custom component or an Android Activity using `mainComponent` or `launchActivity` properties within `fullScreenAction`. ```javascript notifee.displayNotification({ body: 'Full-screen notification', android: { fullScreenAction: { // For custom component: id: 'default', mainComponent: 'custom-component', // For Android Activity other than the default: id: 'full-screen', launchActivity: 'com.awesome.app.FullScreenActivity', }, }, }); ``` -------------------------------- ### Troubleshooting: Custom sound not playing Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Guidance on how to resolve issues with custom notification sounds not playing on either Android or iOS. ```markdown ## Custom sound not playing Ensure custom sound files are correctly placed in the respective native project directories (`android/app/src/main/res/raw` for Android, and added to the Xcode project for iOS) and referenced correctly in the notification payload. ``` -------------------------------- ### Configure Predefined Choices for Notification Input Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/android/interaction Provide an object to the `input` property with `allowFreeFormInput: false` and an array of `choices` to present users with predefined options. The `placeholder` can also be set. ```javascript notifee.displayNotification({ title: 'New message', body: 'You have a new message from Sarah!', android: { channelId: 'messages', actions: [ { title: 'Reply', icon: 'https://my-cdn.com/icons/reply.png', pressAction: { id: 'reply', }, input: { allowFreeFormInput: false, // set to false choices: ['Yes', 'No', 'Maybe'], placeholder: 'Reply to Sarah...', }, }, ], }, }); ``` -------------------------------- ### Troubleshooting: Expo Go does not work Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Guidance for resolving issues when FCM Mode does not function correctly within the Expo Go app. This often relates to native module limitations in Expo Go. ```markdown ## Expo Go does not work Expo Go does not support custom native modules required for FCM Mode. You must use development builds or a bare React Native project. ``` -------------------------------- ### Displaying Large Icons Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/android/appearance Demonstrates various methods for setting a large icon for notifications on Android, including remote URLs, local images, file paths, and Android resources. ```APIDOC ## Displaying Large Icons To set a large icon, add a `largeIcon` property to the notification body. The image will be automatically scaled to fit inside of the notification. It is recommended you use images a minimum size of 192x192 pixels to handle all device resolutions. ### Methods for `largeIcon`: * **Remote image URL**: `largeIcon: 'https://my-cdn.com/users/123456.png'` * **Local image**: `largeIcon: require('../assets/user.jpg')` * **Absolute file path**: `largeIcon: file:///xxxx/xxxx/xxxx.jpg` * **Android resource (mipmap or drawable)**: `largeIcon: 'large_icon'` * **Base 64 image**: `largeIcon: `data:${image.mime};base64,${image.rawBase64Data} ` ### Example Usage: ```javascript notifee.displayNotification({ title: 'Chat with Joe Bloggs', body: 'A new message has been received from a user.', android: { largeIcon: 'https://my-cdn.com/users/123456.png', // or other methods listed above }, }); ``` ``` -------------------------------- ### Server SDK: Other Exports Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode Details on other available exports from the server SDK, beyond `buildNotifyKitPayload`, which might include utility functions or types. ```typescript import { /* other exports */ } from "react-native-notify-kit/server"; // Use other exports as needed... ``` -------------------------------- ### Hook Notifee Extension Helper into NotificationService.m Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/ios/remote-notification-support Integrate the NotifeeExtensionHelper into your Objective-C NotificationService.m file to process incoming remote notifications. ```objective-c #import "NotificationService.h" #import "NotifeeExtensionHelper.h" @implementation NotificationService - (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler { self.contentHandler = contentHandler; self.bestAttemptContent = [request.content mutableCopy]; [NotifeeExtensionHelper populateNotificationContent:request withContent:self.bestAttemptContent withContentHandler:contentHandler]; } - (void)serviceExtensionTimeWillExpire { // Safety net: hand back whatever we have if we ran out of time. if (self.contentHandler && self.bestAttemptContent) { self.contentHandler(self.bestAttemptContent); } } @end ``` -------------------------------- ### Migration Step 2: Client Source: https://docs.page/marcocrupi/react-native-notify-kit/fcm-mode The second step in migration focuses on updating the client-side code to handle FCM messages using the new API. ```typescript // Client-side changes: // Update your FCM message handler to use notifee.handleFcmMessage // import notifee from '@notifee/react-native'; // async function onMessageReceived(remoteMessage) { // await notifee.handleFcmMessage(remoteMessage); // } ``` -------------------------------- ### Configure Android SDK Versions in app.json/app.config.js Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/installation Set Android compile, target, and minimum SDK versions using the expo-build-properties plugin in your app configuration file. Ensure values meet or exceed the library's baseline requirements. ```json { "name": "my app", "plugins": [ [ "expo-build-properties", { "android": { "compileSdkVersion": 35, "targetSdkVersion": 35, "minSdkVersion": 24 } } ] ] } ``` -------------------------------- ### Create Notification with Stop Action Source: https://docs.page/marcocrupi/react-native-notify-kit/react-native/android/foreground-service Display a notification with a Quick Action that allows the user to stop the foreground service. The action's ID must match the one listened for in the event handler. ```javascript notifee.displayNotification({ title: 'Foreground Service Notification', body: 'Press the Quick Action to stop the service', android: { channelId, actions: [ { title: 'Stop', pressAction: { id: 'stop', }, }, ], }, }); ```