From d363cbfc96f6844a19d9b7471e96c6e028ae30e3 Mon Sep 17 00:00:00 2001 From: Ombuweb Date: Fri, 21 Apr 2023 11:57:01 +0200 Subject: [PATCH 1/4] docs(firebase-messaging): update --- packages/firebase-messaging/README.md | 522 ++++++++++++++++++-------- 1 file changed, 364 insertions(+), 158 deletions(-) diff --git a/packages/firebase-messaging/README.md b/packages/firebase-messaging/README.md index 92f45813..ecf2feb1 100644 --- a/packages/firebase-messaging/README.md +++ b/packages/firebase-messaging/README.md @@ -1,29 +1,50 @@ # @nativescript/firebase-messaging -```cli -npm install @nativescript/firebase-messaging -``` +## Intro -## What does it do? +This plugin allows you to use [Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging) in your NativeScript app. -Firebase Cloud Messaging (FCM) is a cross-platform messaging solution that lets you reliably send messages at no cost. +[![image](https://img.youtube.com/vi/sioEY4tWmLI/hqdefault.jpg)](https://www.youtube.com/watch?v=sioEY4tWmLI) -Using FCM, you can notify a client app that new email or other data is available to sync. You can send notification messages to drive user re-engagement and retention. For use cases such as instant messaging, a message can transfer a payload of up to 4 KB to a client app. +Using FCM, you can notify a client app that new email or other data is available to sync. You can send notification messages to drive user re-engagement and retention. For use cases such as instant messaging, a message can transfer a payload of up to `4 KB` to a client app. -[![image](https://img.youtube.com/vi/sioEY4tWmLI/hqdefault.jpg)](https://www.youtube.com/watch?v=sioEY4tWmLI) +FCM messages can be sent to real Android/iOS devices and Android emulators. (iOS simulators however do not handle cloud messages) via several methods (see below). + +Common use cases for handling messages could be: + +- Displaying a notification (see [Notifications](#notifications)). +- Syncing message data silently on the device (e.g. via ApplicationSettings). +- Updating the application's UI. + + +## Set up your app for Firebase + +You need to set up your app for Firebase before you can enable Firebase Messaging. To set up and initialize Firebase for your NativeScript app, follow the instructions on the documentation of the [@nativescript/firebase-core](../firebase-core/) plugin. -## Usage +## Add the Firebase Cloud Messaging SDK to your app -### iOS - Requesting permissions +To add the Firebase Cloud Messaging SDK to your app follow these steps: + +1. Install the `@nativescript/firebase-messaging` plugin by running the following command in the root directory of your project. + +```cli +npm install @nativescript/firebase-messaging +``` + +2. Add the SDK by importing the `@nativescript/firebase-messaging` module once in your app, ideally in the main file (e.g. `app.ts` or `main.ts`). + +```ts +import '@nativescript/firebase-messaging'; +``` + +## iOS: Requesting permissions iOS prevents messages containing notification (or 'alert') payloads from being displayed unless you have received explicit permission from the user. -This module provides a requestPermission method which triggers a native permission dialog requesting the user's permission: +To request permission, call the `requestPermission` method on the . This method triggers a native permission dialog requesting the user's permission. The user can choose to allow or deny the request. ```ts -import { firebase } from '@nativescript/firebase-core'; -import { AuthorizationStatus } from "@nativescript/firebase-messaging"; -import '@nativescript/firebase-messaging'; // only needs to be imported 1x +import { firebase, AuthorizationStatus } from '@nativescript/firebase-core'; async function requestUserPermission() { const authStatus = await firebase() @@ -46,80 +67,86 @@ async function requestUserPermission() { The permissions API for iOS provides much more fine-grain control over permissions and how they're handled within your application. To learn more, view the advanced iOS Permissions documentation. -On Android, you do not need to request user permission. This method can still be called on Android devices; however, and will always resolve successfully. - -### Receiving messages - -FCM messages can be sent to real Android/iOS devices and Android emulators (iOS simulators however do not handle cloud messages) via a number of methods (see below). A message is simply a payload of data which can be used however you see fit within your application. - -Common use-cases for handling messages could be: - -- Displaying a notification (see Notifications). -- Syncing message data silently on the device (e.g. via ApplicationSettings). -- Updating the application's UI. - -Depending on the devices state, incoming messages are handled differently by the device and module. To understand these scenarios, it is first important to establish the various states a device can be in: +## Android: Requesting permissions -| State | Description | -| :--------: | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | -| Foreground | When the application is open and in view. | -| Background | When the application is open, however in the background (minimised). This typically occurs when the user has pressed the "home" button on the device or has switched to another app via the app switcher. | -| Quit | When the device is locked or application is not active or running. The user can quit an app by "swiping it away" via the app switcher UI on the device. | +On Android, you do not need to request user permission. This method can still be called on Android devices; however, and will always resolve successfully. -The user must have opened the app before messages can be received. If the user force quits the app from the device settings, it must be re-opened again before receiving messages. +## Firebase Cloud Messages types and how the user app affects delivery -Depending on the contents of the message, it's important to understand both how the device will handle the message (e.g. display a notification, or even ignore it) and also how the library sends events to your own listeners. +FCM allows you to send the following two types of messages: -### Message handlers +- [Notifications messages](#notifications-messages-delivery-and-app-state) +- [Data-only messages](#data-only-messages-delivery-and-app-state) -The device state and message contents determines which handler will be called: +### Notifications messages delivery and app state -| Foreground | Background | -| :-----------------: | :--------: | -| Notification | onMessage | -| Notification + Data | onMessage | -| Data | onMessage | +The following table shows how the notification messages are delivered to the user app depending on the app state. -- In cases where the message is data-only and the device is in the background or quit, both Android & iOS treat the message as low priority and will ignore it (i.e. no event will be sent). You can however increase the priority by setting the priority to high (Android) and content-available to true (iOS) properties on the payload. + + + + + + + + + + + + + -To learn more about how to send these options in your message payload, view the Firebase documentation for your [FCM API implementation](https://firebase.google.com/docs/cloud-messaging/concept-options). + + + + + -### Notifications + + + + + +
Notification messages typesApp state
ForegroundBackground
Notification onlyDisplayed to the user by the FCM SDK Passed to the onMessage handler for the app code to handle
Notification + optional data App receives a message object with both payloads available.App receives the notification payload in the notification tray, and when the user taps on the notification, the data payload is passed to the onMessage handler +
-The device state and message contents can also determine whether a Notification will be displayed: +#### Always show notifications in the foreground -| | Foreground | Background | Quit | -| :-----------------: | :--------------: | :--------------: | ---------------- | -| Notification | Notification: ❌ | Notification: ✅ | Notification: ✅ | -| Notification + Data | Notification: ❌ | Notification: ✅ | Notification: ✅ | -| Data | Notification: ❌ | Notification: ❌ | Notification: ❌ | +If you always want to display notifications while the application is in the foreground without sending additional parameters/data when sending the push notification, you need to set the [showNotificationsWhenInForeground](#shownotificationswheninforeground) property of the `Messaging` instance to `true`: -### Foreground state messages +```ts +import { firebase } from '@nativescript/firebase-core'; +firebase().messaging().showNotificationsWhenInForeground = true; +``` +#### Listen to notification messages in the foreground -To listen to messages in the foreground, call the onMessage method inside of your application code. Code executed via this handler is able to interact with your application (e.g. updating the state or UI). +Since notification messages are displayed automatically when the app is in the foreground, sometimes you may want to handle the message display manually. To listen to messages in the foreground and handle their display manually, call the [onMessage](#onmessage) method on the instance of [Messaging class](#messaging-class). Code executed via this handler can interact with your application (e.g. updating the state or UI). -For example, the Alert API could be used to display a new Alert each time a message is delivered' +For example, you could display a new Alert each time a message is delivered: ```ts import { alert } from '@nativescript/core'; import { firebase } from '@nativescript/firebase-core'; -import { MessagingCore } from '@nativescript/firebase-messaging-core'; firebase() .messaging() .onMessage(async (remoteMessage) => { - if(MessagingCore.inForeground){ - alert('A new FCM message arrived with application inForeground!', JSON.stringify(remoteMessage)); - }else{ - alert('A new FCM message arrived! with application in background!', JSON.stringify(remoteMessage)); - } + alert('A new FCM message arrived!', JSON.stringify(remoteMessage)); }); ``` -### Data-only messages +### Data-only messages delivery and app state + +The following table shows how the data messages are delivered to the user app depending on the app state. -When an incoming message is "data-only" (contains no notification option), both Android & iOS regard it as low priority and will prevent the application from waking (ignoring the message). To allow data-only messages to trigger , you must set the "priority" to "high" on Android, and enable the content-available flag on iOS. For example, if using the Node.js [firebase-admin](https://www.npmjs.com/package/firebase-admin) package to send a message: +| Foreground | Background +| :--------: | :--------: | +| App receives the data payload in a callback function passed to the onMessage method. | App receives the data payload in a callback function passed to the onMessage method. | + +- When the client app is not in the foreground, both Android & iOS treat the message as low priority and will ignore it (i.e. no event will be sent). To allow data-only messages to trigger, set the payload `priority` property to `high` for Android and the `contentAvailable` property to `true` for iOS. + +For example, if using the Node.js [firebase-admin](https://www.npmjs.com/package/firebase-admin) package to send a message: ```ts admin.messaging().sendToDevice( @@ -139,8 +166,7 @@ admin.messaging().sendToDevice( } ); ``` - -For iOS specific "data-only" messages, the message must include the appropriate APNs headers as well as the content-available flag in order to trigger the handler. For example, if using the Node.js [firebase-admin](https://www.npmjs.com/package/firebase-admin) package to send a "data-only" message to an iOS device: +- For iOS, in addition to setting the `contentAvailable` property to `true`, the payload must contain appropriate APNs. For more information about the APN headers, see [Sending Notification Requests to APNs](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/sending_notification_requests_to_apns/). For example, if using the Node.js [firebase-admin](https://www.npmjs.com/package/firebase-admin) package to send a message, the payload would look like this: ```ts admin.messaging().send({ @@ -166,75 +192,21 @@ admin.messaging().send({ }); ``` -View the [Sending Notification Requests to APNs](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/sending_notification_requests_to_apns/) documentation to learn more about APNs headers. - -These options can be applied to all FCM messages. View the [Server Integration](#server-integration) documentation to learn more about other available SDKs. - -# Always show notifications when the application is in foreground - -If you always want to display notifications while the application is in the foreground without sending additional parameters/data when sending the push notification, you need to set the showNotificationsWhenInForeground option to true: - -```ts -import { firebase } from '@nativescript/firebase-core'; -firebase().messaging().showNotificationsWhenInForeground = true; -``` - -### Topics - -Topics are a mechanism which allow a device to subscribe and unsubscribe from named PubSub channels, all managed via FCM. Rather than sending a message to a specific device by FCM token, you can instead send a message to a topic and any devices subscribed to that topic will receive the message. - -Topics allow you to simplify FCM server integration as you do not need to keep a store of device tokens. There are however some things to keep in mind about topics: - -Messages sent to topics should not contain sensitive or private information. Do not create a topic for a specific user to subscribe to. -Topic messaging supports unlimited subscriptions for each topic. -One app instance can be subscribed to no more than 2000 topics. -The frequency of new subscriptions is rate-limited per project. If you send too many subscription requests in a short period of time, FCM servers will respond with a 429 RESOURCE_EXHAUSTED ("quota exceeded") response. Retry with exponential backoff. -A server integration can send a single message to multiple topics at once. This however is limited to 5 topics. -To learn more about how to send messages to devices subscribed to topics, view the Send messages to topics documentation. - -#### Subscribing to topics - -To subscribe a device, call the subscribeToTopic method with the topic name (must not include "/"): - -```ts -import { firebase } from '@nativescript/firebase-core'; - -firebase() - .messaging() - .subscribeToTopic('weather') - .then(() => console.log('Subscribed to topic!')); -``` - -#### Unsubscribing to topics - -To unsubscribe from a topic, call the unsubscribeFromTopic method with the topic name: - -```ts -import { firebase } from '@nativescript/firebase-core'; - -firebase() - .messaging() - .unsubscribeFromTopic('weather') - .then(() => console.log('Unsubscribed fom the topic!')); -``` - -## Server Integration - -The Cloud Messaging module provides the tools required to enable you to send custom messages directly from your own servers. For example, you could send an FCM message to a specific device when a new chat message is saved to your database and display a notification, or update local device storage, so the message is instantly available. +## Send messages from your servers -Firebase provides a number of SDKs in different languages such as [Node.JS](https://www.npmjs.com/package/firebase-admin), [Java](https://firebase.google.com/docs/reference/admin/java/reference/com/google/firebase/messaging/package-summary), [Python](https://firebase.google.com/docs/reference/admin/python/firebase_admin.messaging), [C#](https://firebase.google.com/docs/reference/admin/dotnet/namespace/firebase-admin/messaging) and [Go](https://godoc.org/firebase.google.com/go/messaging). It also supports sending messages over [HTTP](https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages). These methods allow you to send messages directly to your user's devices via the FCM servers. +The Cloud Messaging module provides the tools required to enable you to send custom messages directly from your servers. For example, you could send an FCM message to a specific device when a new chat message is saved to your database and display a notification, or update local device storage, so the message is instantly available. -### Device tokens +Firebase provides several SDKs in different languages such as [Node.JS](https://www.npmjs.com/package/firebase-admin), [Java](https://firebase.google.com/docs/reference/admin/java/reference/com/google/firebase/messaging/package-summary), [Python](https://firebase.google.com/docs/reference/admin/python/firebase_admin.messaging), [C#](https://firebase.google.com/docs/reference/admin/dotnet/namespace/firebase-admin/messaging) and [Go](https://godoc.org/firebase.google.com/go/messaging). It also supports sending messages over [HTTP](https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages). These methods allow you to send messages directly to your user's devices via the FCM servers. -To send a message to a device, you must access its unique token. A token is automatically generated by the device and can be accessed using the Cloud Messaging module. The token should be saved inside your systems data-store and should be easily accessible when required. +### Send messages using user device tokens -The examples below use a Cloud Firestore database to store and manage the tokens, and Firebase Authentication to manage the users identity. You can however use any datastore or authentication method of your choice. +To send a message to a device, you must access its unique token. A token is automatically generated by the device and can be accessed using the Cloud Messaging module. The token should be saved on your servers and should be easily accessible when required. -> **Note:** If using iOS, ensure you have completed the [setup](#apple-integration) & [requested user permission](#iOS---Requesting-permissions) before trying to receive messages! +The examples below use a Cloud Firestore database to store and manage the tokens, and Firebase Authentication to manage the user's identity. You can however use any data store or authentication method of your choice. -### Saving tokens +#### Saving tokens -Once your application has started, you can call the getToken method on the Cloud Messaging module to get the unique device token (if using a different push notification provider, such as Amazon SNS, you will need to call getAPNSToken on iOS): +Once your application has started, you can call the [getToken](#gettoken) method on the [Messaging](#messaging-class) instance to get the unique device token (if using a different push notification provider, such as Amazon SNS, you will need to call `getAPNSToken` on iOS): ```ts import { firebase } from '@nativescript/firebase-core'; @@ -242,7 +214,6 @@ import '@nativescript/firebase-messaging'; import { FieldValue } from '@nativescript/firebase-auth'; import '@nativescript/firebase-firestore'; - async function saveTokenToDatabase(token) { // Assume user is already signed in const userId = firebase().auth().currentUser.uid; @@ -277,21 +248,21 @@ async function saveTokenToDatabase(token) { } ``` -The above code snippet has a single purpose; storing the device FCM token on a remote database. +The above code snippet stores the device FCM token on a remote database. -Inside of the saveTokenToDatabase method, we store the token on a record specifically relating to the current user. You may also notice that the token is being added via the FieldValue.arrayUnion method. A user can have more than one token (for example using 2 devices) so it's important to ensure that we store all tokens in the database. +Inside the `saveTokenToDatabase` method, we store the token in the current user's document. You may also notice that the token is being added via the [FieldValue.arrayUnion](https://github.com/NativeScript/firebase/blob/main/packages/firebase-firestore/index.d.ts#L426) method. A user can have more than one token (for example using 2 devices) so it's important to ensure that we store all tokens in the database. -### Using tokens +#### Using the stored tokens -With the tokens stored in a secure datastore, we now have the ability to send messages via FCM to those devices. +With the tokens stored in a secure data store, we can now send messages via FCM to those devices. > **Note:** The following example uses the Node.JS firebase-admin package to send messages to our devices, however any SDK (listed above) can be used. -Go ahead and setup the `firebase-tools` library on your server environment. Once setup, our script needs to perform two actions: +Go ahead and set up the `firebase-tools` library on your server environment. Once setup, our script needs to perform two actions: -Fetch the tokens required to send the message. -Send a data payload to the devices that the tokens are registered to. -Imagine our application being similar to Instagram. Users are able to upload pictures, and other users can "like" those pictures. Each time a post is liked, we want to send a message to the user that uploaded the picture. The code below simulates a function which is called with all of the information required when a picture is liked: +1. Fetch the tokens required to send the message. +2. Send a data payload to the devices that the tokens are registered to. +Imagine our application being similar to Instagram. Users can upload pictures, and other users can "like" those pictures. Each time a post is liked, we want to send a message to the user that uploaded the picture. The code below simulates a function that is called with all of the information required when a picture is liked: ```ts // Node.js @@ -327,17 +298,58 @@ async function onUserPictureLiked(ownerId, userId, picture) { } ``` -### Signing out users +### Handle tokens when authenticating users Firebase Cloud Messaging tokens are associated with the instance of the installed app. By default, only token expiration or uninstalling/reinstalling the app will generate a fresh token. -This means that by default, if your app has users and you allow them to log out and log in on the same app on the same device, the same FCM token will be used for both users. Usually this is not what you want, so you must take care to cycle the FCM token at the same time you handle user logout/login. +This means that by default, if two users login into your app from the same device, the same FCM token will be used for both users. Usually, this is not what you want, so you must take care to cycle the FCM token at the same time you handle user logout/login. + +How and when you invalidate a token and generate a new one will be specific to your project, but a common pattern is to delete the FCM token during logout and update your back end to remove it. Then, you fetch the FCM token during login and update your backend systems to associate the new token with the logged-in user. + +Note that when a token is deleted by calling the [deleteToken](#deletetoken) method, it is immediately and permanently invalid. + +## Send messages via topics + +Topics are mechanisms that allow a device to subscribe and unsubscribe from named [PubSub channels](https://redis.io/commands/pubsub-channels/), all managed via FCM. Rather than sending a message to a specific device by FCM token, you can instead send a message to a topic and any devices subscribed to that topic will receive the message. + +Topics allow you to simplify FCM server integration as you do not need to keep a store of device tokens. There are, however, some things to keep in mind about topics: + +- Messages sent to topics should not contain sensitive or private information. +- Do not create a topic for a specific user to subscribe to. +- Topic messaging supports unlimited subscriptions for each topic. +- One app instance can be subscribed to no more than 2000 topics. +- The frequency of new subscriptions is rate-limited per project. If you send too many subscription requests in a short period, FCM servers will respond with a `429 RESOURCE_EXHAUSTED` ("quota exceeded") response. Retry with exponential backoff. +- A server integration can send a single message to multiple topics at once. However, this is limited to `5` topics. + +To learn more about how to send messages to devices subscribed to topics, see [Topic messaging on Android](https://firebase.google.com/docs/cloud-messaging/android/topic-messaging) or [Send messages to topics on Apple platforms](https://firebase.google.com/docs/cloud-messaging/ios/topic-messaging). + +### Subscribing to topics + +To subscribe a device to a topic, call the [subscribeToTopic](#subscribetotopic) method on the [Messsaging](#messaging-class) instance with the topic name (must not include ´/´): + +```ts +import { firebase } from '@nativescript/firebase-core'; + +firebase() + .messaging() + .subscribeToTopic('weather') + .then(() => console.log('Subscribed to topic!')); +``` + +### Unsubscribing to topics + +To unsubscribe from a topic, call the [unsubscribeFromTopic](#unsubscribefromtopic) method with the topic name: -How and when you invalidate a token and generate a new one will be specific to your project, but a common pattern is to delete the FCM token during logout and update your back end to remove it, then to fetch the FCM token during login and update your back end systems to associate the new token with the logged in user. +```ts +import { firebase } from '@nativescript/firebase-core'; -Note that when a token is deleted by calling the deleteToken method, it is immediately and permanently invalid. +firebase() + .messaging() + .unsubscribeFromTopic('weather') + .then(() => console.log('Unsubscribed fom the topic!')); +``` -### Send messages to topics +### Send messages to a user device via topics When devices [subscribe to topics](#Subscribing-to-topics), you can send messages without specifying/storing any device tokens. @@ -351,7 +363,7 @@ const message = { type: 'warning', content: 'A new weather warning has been created!', }, - topic: 'weather', + topic: 'weather',// topic name }; admin @@ -365,9 +377,9 @@ admin }); ``` -### Conditional topics +### Send messages to a conditional topics -To send a message to a combination of topics, specify a condition, which is a boolean expression that specifies the target topics. For example, the following condition will send messages to devices that are subscribed to weather and either news or traffic: +To send a message to a combination of topics, specify a condition, which is a boolean expression that specifies the target topics. For example, the following condition will send messages to devices that are subscribed to `weather` and either `news` or `traffic`: ```ts condition: "'weather' in topics && ('news' in topics || 'traffic' in topics)"; @@ -396,13 +408,13 @@ admin }); ``` -### Send messages with image +## Send an image in the notification payload Both the Notifications composer and the FCM API support image links in the message payload. -#### iOS +### iOS -To successfully send an image using the Admin SDK it's important that the `ApnsConfig` options are set: +To successfully send an image using the Admin SDK `ApnsConfig` options must be met: ```ts const payload = { @@ -425,7 +437,7 @@ const payload = { > **Note:** Check out the [official Firebase documentation](https://firebase.google.com/docs/cloud-messaging/ios/send-image) to see the list of available configuration for iOS. -#### Android +### Android Similarly to iOS, some configurations specific to Android are needed: @@ -443,9 +455,9 @@ const payload = { }; ``` -> **Note:** If you want to know more about sending an image on Android have a look at [the documentation](https://firebase.google.com/docs/cloud-messaging/android/send-image). +> **Note:** If you want to know more about sending an image on Android have a look at [Send an image in the notification payload](https://firebase.google.com/docs/cloud-messaging/android/send-image). -### Pulling it all together +### send one image notification for both iOS and Android It's possible to send one notification that will be delivered to both platforms using the Admin SDK: @@ -490,11 +502,9 @@ admin }); ``` -### Android Integration - -Push notification icon and color +### Configure Push notification icon and color for Android -If you want to use a specific icon for the push notification, it has to be configured in the tag in the AndroidManifest.xml +If you want to use a specific icon and color for the push notification, it has to be configured in the tag in the AndroidManifest.xml ```xml ``` -### Apple Integration +### iOS: Enable push support in Xcode -#### Enable push support in Xcode Open /platforms/ios/yourproject.**xcworkspace** (!) and go to your project's target and head over to "Capabilities" to switch this on (if it isn't already): ![push-xcode-config](https://raw.githubusercontent.com/NativeScript/firebase/main/packages/firebase-messaging/assets/images/push-xcode-config.png) @@ -514,9 +523,8 @@ Open /platforms/ios/yourproject.**xcworkspace** (!) and go to your project's tar #### Copy the entitlements file -The previous step created a the file `platforms/ios/YourAppName/(Resources/)YourAppName.entitlements`. -Move and rename that file to `app/App_Resources/iOS/app.entitlements` (if it doesn't exist yet, otherwise merge its contents), -so it's not removed when you remove and re-add the iOS platform. The relevant content for background push in that file is: +The previous step created the file `platforms/ios/YourAppName/(Resources/)YourAppName.entitlements`. +Move and rename that file to `app/App_Resources/iOS/app.entitlements` (if it doesn't exist yet, otherwise merge its contents), so that it doesn't get deleted when you run `ns clean`. The relevant content for background push in that file is: ```xml aps-environment @@ -534,9 +542,207 @@ Open `app/App_Resources/iOS/Info.plist` and add this to the bottom: ``` -#### Provisioning + + +## API +### Messaging class +#### android +```ts +import { firebase } from '@nativescript/firebase-core'; + +messagingAndroid: com.google.firebase.messaging.FirebaseMessaging = firebase().messaging().android; +``` +A `read-only` property that returns the instance of the Messaging class for Android. + +--- +#### ios +```ts +import { firebase } from '@nativescript/firebase-core'; + +messagingIos: MessagingCore = firebase().messaging().ios; +``` +A `read-only` property that returns the instance of the Messaging class for iOS. + +--- +#### app +```ts +import { firebase } from '@nativescript/firebase-core'; +messageApp: FirebaseApp = firebase().messaging().app; +``` +A `read-only` property that returns the instance of the FirebaseApp class associated with this Cloud Messaging instance. + +--- +#### isAutoInitEnabled +```ts +import { firebase } from '@nativescript/firebase-core'; +isAutoInitEnabled: boolean = firebase().messaging().isAutoInitEnabled; +// or +firebase().messaging().isAutoInitEnabled = true; +``` + +Determines whether to enable or disable auto-initialization of Firebase Cloud Messaging. For more information about this property for iOS, see [autoInitEnabled](https://firebase.google.com/docs/reference/ios/firebasemessaging/api/reference/Classes/FIRMessaging#autoinitenabled). + +--- +#### showNotificationsWhenInForeground +```ts +import { firebase } from '@nativescript/firebase-core'; +showNotificationsWhenInForeground: boolean = firebase().messaging().showNotificationsWhenInForeground; +// or +firebase().messaging().showNotificationsWhenInForeground = true; +``` + +--- +#### isDeviceRegisteredForRemoteMessages +```ts +import { firebase } from '@nativescript/firebase-core'; +isDeviceRegisteredForRemoteMessages: boolean = firebase().messaging().isDeviceRegisteredForRemoteMessages; +``` +A property that returns a boolean value indicating whether the app is registered to receive remote notifications. + +--- +#### getToken() +```ts +import { firebase } from '@nativescript/firebase-core'; +firebase().messaging().getToken() + .then((token: string) => { + console.log('Token: ', token); + }).catch((error: Error) => { + console.log('Error: ', error); + }); +``` + +--- +#### getAPNSToken() +```ts +import { firebase } from '@nativescript/firebase-core'; +aPNSToken: string | null = firebase().messaging().getAPNSToken() +``` + +--- +#### hasPermission() +```ts +import { firebase } from '@nativescript/firebase-core'; +firebase().messaging().hasPermission() + .then((status: AuthorizationStatus) => { + console.log('Authorization status: ', status); + }).catch((error: Error) => { + console.log('Error: ', error); + }); +``` + +--- +#### onMessage() +```ts +import { firebase } from '@nativescript/firebase-core'; +firebase().messaging().onMessage(listener); +``` + +| Parameter | Type | Description | +| --- | --- | --- | +| `listener` | `(message: RemoteMessage) => any` | A callback function that is invoked when a new message is received | + +--- +#### onNotificationTap() +```ts +import { firebase } from '@nativescript/firebase-core'; +firebase().messaging().onNotificationTap(listener); +``` +| Parameter | Type | Description | +| --- | --- | --- | +| `listener` | `(message: RemoteMessage) => any` | A callback function that is invoked when a new message is received | +#### onToken() +```ts +import { firebase } from '@nativescript/firebase-core'; +firebase().messaging().onToken(listener); +``` +| Parameter | Type | Description | +| --- | --- | --- | +| `listener` | `(token: string) => any` | A callback function that is invoked when | + +--- +#### registerDeviceForRemoteMessages() +```ts +import { firebase } from '@nativescript/firebase-core'; +firebase().messaging().registerDeviceForRemoteMessages() + .then(() => { + console.log('Device registered for remote messages'); + }).catch((error: Error) => { + console.log('Error: ', error); + }); +``` + +--- +#### requestPermission() +```ts +import { firebase } from '@nativescript/firebase-core'; +firebase().messaging().requestPermission(permissions) + .then((status: AuthorizationStatus) => { + console.log('Authorization status: ', status); + }).catch((error: Error) => { + console.log('Error: ', error); + }); +``` +| Parameter | Type | Description | +| --- | --- | --- | +| `permissions` | [Permissions](https://github.com/NativeScript/firebase/blob/main/packages/firebase-messaging-core/index.d.ts#L16-L19) | An object containing the permissions to request. | + +--- +#### subscribeToTopic() +```ts +import { firebase } from '@nativescript/firebase-core'; +firebase().messaging().subscribeToTopic(topic) + .then(() => { + console.log('Subscribed to topic'); + }).catch((error: Error) => { + console.log('Error: ', error); + }); +``` +| Parameter | Type | Description | +| --- | --- | --- | +| `topic` | `string` | The name of the topic to subscribe to. | + +--- +#### unsubscribeFromTopic() +```ts +import { firebase } from '@nativescript/firebase-core'; +firebase().messaging().unsubscribeFromTopic(topic) + .then(() => { + console.log('Unsubscribed from topic'); + }).catch((error: Error) => { + console.log('Error: ', error); + }); +``` +| Parameter | Type | Description | +| --- | --- | --- | +| `topic` | `string` | The name of the topic to unsubscribe from. | + +--- +#### unregisterDeviceForRemoteMessages() +```ts +import { firebase } from '@nativescript/firebase-core'; +firebase().messaging().unregisterDeviceForRemoteMessages() + .then(() => { + console.log('Device unregistered for remote messages'); + }).catch((error: Error) => { + console.log('Error: ', error); + }); +``` + +--- +#### deleteToken() +```ts +import { firebase } from '@nativescript/firebase-core'; +firebase().messaging().deleteToken() + .then(() => { + console.log('Token deleted'); + }).catch((error: Error) => { + console.log('Error: ', error); + }); +``` -Follow [this guide](https://firebase.google.com/docs/cloud-messaging/ios/certs) to the letter. Once you've done it run tns run ios and upon starting the app it should prompt you for notification support. That also works on the simulator, but actually receiving (background) notifications is only possible on a real device. +--- ## License From 7e4d5a28ff36b5cb25eac06f9e3aa8501b675f60 Mon Sep 17 00:00:00 2001 From: Ombuweb Date: Mon, 24 Apr 2023 09:20:11 +0200 Subject: [PATCH 2/4] chore: update --- packages/firebase-messaging/README.md | 142 ++++++++++++++++++-------- 1 file changed, 99 insertions(+), 43 deletions(-) diff --git a/packages/firebase-messaging/README.md b/packages/firebase-messaging/README.md index ecf2feb1..4b37b1c6 100644 --- a/packages/firebase-messaging/README.md +++ b/packages/firebase-messaging/README.md @@ -1,5 +1,58 @@ # @nativescript/firebase-messaging +## Contents +* [Intro](#intro) +* [Set up your app for Firebase](#set-up-your-app-for-firebase) +* [Add the Firebase Cloud Messaging SDK to your app](#add-the-firebase-cloud-messaging-sdk-to-your-app) +* [iOS: Requesting permissions](#ios-requesting-permissions) +* [Android: Requesting permissions](#android-requesting-permissions) +* [How the app state affects messages delivery](#how-the-app-state-affects-messages-delivery) + * [Notifications messages delivery and app state](#notifications-messages-delivery-and-app-state) + * [Always show notifications in the foreground](#always-show-notifications-in-the-foreground) + * [Listen to notification messages in the foreground](#listen-to-notification-messages-in-the-foreground) + * [Data-only messages delivery and app state](#data-only-messages-delivery-and-app-state) +* [Send messages from your servers](#send-messages-from-your-servers) + * [Send messages using user device tokens](#send-messages-using-user-device-tokens) + * [Saving tokens](#saving-tokens) + * [Using the stored tokens](#using-the-stored-tokens) + * [Handle tokens when authenticating users](#handle-tokens-when-authenticating-users) +* [Send messages via topics](#send-messages-via-topics) + * [Subscribing to topics](#subscribing-to-topics) + * [Unsubscribing from topics](#unsubscribing-from-topics) + * [Send messages to a user device via topics](#send-messages-to-a-user-device-via-topics) + * [Send messages to conditional topics](#send-messages-to-conditional-topics) +* [Send an image in the notification payload](#send-an-image-in-the-notification-payload) + * [iOS-specific options](#ios-specific-options) + * [Android-specific options](#android-specific-options) + * [send one image notification for both iOS and Android](#send-one-image-notification-for-both-ios-and-android) +* [Android: Configure Push notification icon and color](#android-configure-push-notification-icon-and-color) +* [iOS: Enable the support for the delivery of push notification in the background in Xcode](#ios-enable-the-support-for-the-delivery-of-push-notification-in-the-background-in-xcode) + * [Copy the entitlements file](#copy-the-entitlements-file) + * [Allow processing when a background push notification is received](#allow-processing-when-a-background-push-notification-is-received) +* [API](#api) + * [Messaging class](#messaging-class) + * [android](#android) + * [ios](#ios) + * [app](#app) + * [isAutoInitEnabled](#isautoinitenabled) + * [showNotificationsWhenInForeground](#shownotificationswheninforeground) + * [isDeviceRegisteredForRemoteMessages](#isdeviceregisteredforremotemessages) + * [deleteToken()](#deletetoken) + * [getToken()](#gettoken) + * [getAPNSToken()](#getapnstoken) + * [deleteToken()](#deletetoken) + * [hasPermission()](#haspermission) + * [onMessage()](#onmessage) + * [onNotificationTap()](#onnotificationtap) + * [onToken()](#ontoken) + * [registerDeviceForRemoteMessages()](#registerdeviceforremotemessages) + * [requestPermission()](#requestpermission) + * [subscribeToTopic()](#subscribetotopic) + * [unregisterDeviceForRemoteMessages()](#unregisterdeviceforremotemessages) + * [unsubscribeFromTopic()](#unsubscribefromtopic) + +* [License](#license) + ## Intro This plugin allows you to use [Firebase Cloud Messaging](https://firebase.google.com/docs/cloud-messaging) in your NativeScript app. @@ -8,12 +61,12 @@ This plugin allows you to use [Firebase Cloud Messaging](https://firebase.google Using FCM, you can notify a client app that new email or other data is available to sync. You can send notification messages to drive user re-engagement and retention. For use cases such as instant messaging, a message can transfer a payload of up to `4 KB` to a client app. -FCM messages can be sent to real Android/iOS devices and Android emulators. (iOS simulators however do not handle cloud messages) via several methods (see below). +FCM messages can be sent to real Android/iOS devices and Android emulators. iOS simulators however do not handle cloud messages. Common use cases for handling messages could be: -- Displaying a notification (see [Notifications](#notifications)). -- Syncing message data silently on the device (e.g. via ApplicationSettings). +- Displaying a notification (see [Listen to notification messages in the foreground](#listen-to-notification-messages-in-the-foreground)). +- Syncing message data silently on the device (e.g. via the ApplicationSettings class). - Updating the application's UI. @@ -31,7 +84,7 @@ To add the Firebase Cloud Messaging SDK to your app follow these steps: npm install @nativescript/firebase-messaging ``` -2. Add the SDK by importing the `@nativescript/firebase-messaging` module once in your app, ideally in the main file (e.g. `app.ts` or `main.ts`). +2. Add the SDK by importing the `@nativescript/firebase-messaging` module. You should import this module once in your app, ideally in the main file (e.g. `app.ts` or `main.ts`). ```ts import '@nativescript/firebase-messaging'; @@ -41,7 +94,7 @@ import '@nativescript/firebase-messaging'; iOS prevents messages containing notification (or 'alert') payloads from being displayed unless you have received explicit permission from the user. -To request permission, call the `requestPermission` method on the . This method triggers a native permission dialog requesting the user's permission. The user can choose to allow or deny the request. +To request permission, call the [requestPermission](#requestpermission) method on the [Messaging class](#messaging-class) instance returned by `firebase().messaging()`. This method triggers a native permission dialog requesting the user's permission. The user can choose to allow or deny the request. ```ts import { firebase, AuthorizationStatus } from '@nativescript/firebase-core'; @@ -65,19 +118,19 @@ async function requestUserPermission() { } ``` -The permissions API for iOS provides much more fine-grain control over permissions and how they're handled within your application. To learn more, view the advanced iOS Permissions documentation. - ## Android: Requesting permissions -On Android, you do not need to request user permission. This method can still be called on Android devices; however, and will always resolve successfully. +On Android, you do not need to request user permission. This method can still be called on Android devices. However, it will always resolve successfully. -## Firebase Cloud Messages types and how the user app affects delivery +## How the app state affects messages delivery FCM allows you to send the following two types of messages: - [Notifications messages](#notifications-messages-delivery-and-app-state) - [Data-only messages](#data-only-messages-delivery-and-app-state) +How these messages are delivered depends on whether the app is in the foreground or background. + ### Notifications messages delivery and app state The following table shows how the notification messages are delivered to the user app depending on the app state. @@ -113,7 +166,7 @@ The following table shows how the notification messages are delivered to the use #### Always show notifications in the foreground -If you always want to display notifications while the application is in the foreground without sending additional parameters/data when sending the push notification, you need to set the [showNotificationsWhenInForeground](#shownotificationswheninforeground) property of the `Messaging` instance to `true`: +If you want to always display notifications while the application is in the foreground without sending additional parameters/data when sending the push notification, set the [showNotificationsWhenInForeground](#shownotificationswheninforeground) property of the `Messaging` instance to `true`: ```ts import { firebase } from '@nativescript/firebase-core'; @@ -121,7 +174,7 @@ firebase().messaging().showNotificationsWhenInForeground = true; ``` #### Listen to notification messages in the foreground -Since notification messages are displayed automatically when the app is in the foreground, sometimes you may want to handle the message display manually. To listen to messages in the foreground and handle their display manually, call the [onMessage](#onmessage) method on the instance of [Messaging class](#messaging-class). Code executed via this handler can interact with your application (e.g. updating the state or UI). +Since notification messages are displayed automatically(see [Notifications messages delivery and app state](#notifications-messages-delivery-and-app-state)) when the app is in the foreground, sometimes you may want to handle the display of the message manually. To listen to a message in the foreground and handle their display manually, call the [onMessage](#onmessage) method on the instance of [Messaging class](#messaging-class). Code executed via this handler can interact with your application (e.g. updating the state or UI). For example, you could display a new Alert each time a message is delivered: @@ -146,7 +199,7 @@ The following table shows how the data messages are delivered to the user app de - When the client app is not in the foreground, both Android & iOS treat the message as low priority and will ignore it (i.e. no event will be sent). To allow data-only messages to trigger, set the payload `priority` property to `high` for Android and the `contentAvailable` property to `true` for iOS. -For example, if using the Node.js [firebase-admin](https://www.npmjs.com/package/firebase-admin) package to send a message: +For example, if using the Node.js [firebase-admin](https://www.npmjs.com/package/firebase-admin) package to send a message, you would set the payload as follows: ```ts admin.messaging().sendToDevice( @@ -166,7 +219,7 @@ admin.messaging().sendToDevice( } ); ``` -- For iOS, in addition to setting the `contentAvailable` property to `true`, the payload must contain appropriate APNs. For more information about the APN headers, see [Sending Notification Requests to APNs](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/sending_notification_requests_to_apns/). For example, if using the Node.js [firebase-admin](https://www.npmjs.com/package/firebase-admin) package to send a message, the payload would look like this: +- For iOS, in addition to setting the `contentAvailable` property to `true`, the payload must contain appropriate APNs headers. For more information about the APN headers, see [Sending Notification Requests to APNs](https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/sending_notification_requests_to_apns/). For example, if using the Node.js [firebase-admin](https://www.npmjs.com/package/firebase-admin) package to send a message, the payload would look like this: ```ts admin.messaging().send({ @@ -196,7 +249,7 @@ admin.messaging().send({ The Cloud Messaging module provides the tools required to enable you to send custom messages directly from your servers. For example, you could send an FCM message to a specific device when a new chat message is saved to your database and display a notification, or update local device storage, so the message is instantly available. -Firebase provides several SDKs in different languages such as [Node.JS](https://www.npmjs.com/package/firebase-admin), [Java](https://firebase.google.com/docs/reference/admin/java/reference/com/google/firebase/messaging/package-summary), [Python](https://firebase.google.com/docs/reference/admin/python/firebase_admin.messaging), [C#](https://firebase.google.com/docs/reference/admin/dotnet/namespace/firebase-admin/messaging) and [Go](https://godoc.org/firebase.google.com/go/messaging). It also supports sending messages over [HTTP](https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages). These methods allow you to send messages directly to your user's devices via the FCM servers. +Firebase provides several SDKs for that purpose in different languages such as [Node.JS](https://www.npmjs.com/package/firebase-admin), [Java](https://firebase.google.com/docs/reference/admin/java/reference/com/google/firebase/messaging/package-summary), [Python](https://firebase.google.com/docs/reference/admin/python/firebase_admin.messaging), [C#](https://firebase.google.com/docs/reference/admin/dotnet/namespace/firebase-admin/messaging) and [Go](https://godoc.org/firebase.google.com/go/messaging). It also supports sending messages over [HTTP](https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages). These methods allow you to send messages directly to your user's devices via the FCM servers. ### Send messages using user device tokens @@ -206,7 +259,7 @@ The examples below use a Cloud Firestore database to store and manage the tokens #### Saving tokens -Once your application has started, you can call the [getToken](#gettoken) method on the [Messaging](#messaging-class) instance to get the unique device token (if using a different push notification provider, such as Amazon SNS, you will need to call `getAPNSToken` on iOS): +Once your application has started, you can call the [getToken](#gettoken) method on the [Messaging](#messaging-class) instance to get the unique device token. If you are using a different push notification provider, such as Amazon SNS, you will need to call [getAPNSToken](#getapnstoken) on iOS: ```ts import { firebase } from '@nativescript/firebase-core'; @@ -250,18 +303,18 @@ async function saveTokenToDatabase(token) { The above code snippet stores the device FCM token on a remote database. -Inside the `saveTokenToDatabase` method, we store the token in the current user's document. You may also notice that the token is being added via the [FieldValue.arrayUnion](https://github.com/NativeScript/firebase/blob/main/packages/firebase-firestore/index.d.ts#L426) method. A user can have more than one token (for example using 2 devices) so it's important to ensure that we store all tokens in the database. +Inside the `saveTokenToDatabase` method, we store the token in the current user's document. Notice that the token is being added via the [FieldValue.arrayUnion](https://github.com/NativeScript/firebase/blob/main/packages/firebase-firestore/index.d.ts#L426) method. A user can have more than one token (for example using 2 devices) so it's important to ensure that we store all tokens in the database and the `FieldValue.arrayUnion` allows us to do that. #### Using the stored tokens With the tokens stored in a secure data store, we can now send messages via FCM to those devices. -> **Note:** The following example uses the Node.JS firebase-admin package to send messages to our devices, however any SDK (listed above) can be used. +> **Note:** The following example uses the Node.JS firebase-admin package to send messages to our devices. However, you can use any of the SDKs listed above can be used. Go ahead and set up the `firebase-tools` library on your server environment. Once setup, our script needs to perform two actions: 1. Fetch the tokens required to send the message. -2. Send a data payload to the devices that the tokens are registered to. +2. Send a data payload to the devices that the tokens are registered for. Imagine our application being similar to Instagram. Users can upload pictures, and other users can "like" those pictures. Each time a post is liked, we want to send a message to the user that uploaded the picture. The code below simulates a function that is called with all of the information required when a picture is liked: ```ts @@ -318,14 +371,14 @@ Topics allow you to simplify FCM server integration as you do not need to keep a - Do not create a topic for a specific user to subscribe to. - Topic messaging supports unlimited subscriptions for each topic. - One app instance can be subscribed to no more than 2000 topics. -- The frequency of new subscriptions is rate-limited per project. If you send too many subscription requests in a short period, FCM servers will respond with a `429 RESOURCE_EXHAUSTED` ("quota exceeded") response. Retry with exponential backoff. +- The frequency of new subscriptions is rate-limited per project. If you send too many subscription requests in a short period, FCM servers will respond with a `429 RESOURCE_EXHAUSTED` ("quota exceeded") response. - A server integration can send a single message to multiple topics at once. However, this is limited to `5` topics. To learn more about how to send messages to devices subscribed to topics, see [Topic messaging on Android](https://firebase.google.com/docs/cloud-messaging/android/topic-messaging) or [Send messages to topics on Apple platforms](https://firebase.google.com/docs/cloud-messaging/ios/topic-messaging). ### Subscribing to topics -To subscribe a device to a topic, call the [subscribeToTopic](#subscribetotopic) method on the [Messsaging](#messaging-class) instance with the topic name (must not include ´/´): +To subscribe a device to a topic, call the [subscribeToTopic](#subscribetotopic) method on the [Messaging](#messaging-class) instance with the topic name (must not include `/`): ```ts import { firebase } from '@nativescript/firebase-core'; @@ -336,7 +389,7 @@ firebase() .then(() => console.log('Subscribed to topic!')); ``` -### Unsubscribing to topics +### Unsubscribing from topics To unsubscribe from a topic, call the [unsubscribeFromTopic](#unsubscribefromtopic) method with the topic name: @@ -351,9 +404,7 @@ firebase() ### Send messages to a user device via topics -When devices [subscribe to topics](#Subscribing-to-topics), you can send messages without specifying/storing any device tokens. - -Using the firebase-admin Admin SDK as an example, we can send a message to devices subscribed to a topic: +Using the firebase-admin Admin SDK as an example, we can send a message to devices subscribed to a topic(`weather`): ```ts const admin = require('firebase-admin'); @@ -377,15 +428,15 @@ admin }); ``` -### Send messages to a conditional topics +### Use conditions to send a messages to more than one topic at once -To send a message to a combination of topics, specify a condition, which is a boolean expression that specifies the target topics. For example, the following condition will send messages to devices that are subscribed to `weather` and either `news` or `traffic`: +To send a message to a combination of topics, specify a condition, which is a boolean expression that specifies the target topics. For example, the following condition will send messages to devices that are subscribed to `weather` and either `news` or `traffic` tpoics: ```ts condition: "'weather' in topics && ('news' in topics || 'traffic' in topics)"; ``` -To send a message to this condition, replace the topic key with condition: +To send a message to this condition, replace the topic key with the condition: ```ts const admin = require('firebase-admin'); @@ -412,9 +463,9 @@ admin Both the Notifications composer and the FCM API support image links in the message payload. -### iOS +### iOS-specific options -To successfully send an image using the Admin SDK `ApnsConfig` options must be met: +To successfully send an image using the Admin SDK, set the `ApnsConfig` options with the `apns` property for iOS: ```ts const payload = { @@ -435,9 +486,9 @@ const payload = { }; ``` -> **Note:** Check out the [official Firebase documentation](https://firebase.google.com/docs/cloud-messaging/ios/send-image) to see the list of available configuration for iOS. +> **Note:** To see the list of available configuration for iOS, check out the [official Firebase documentation](https://firebase.google.com/docs/cloud-messaging/ios/send-image). -### Android +### Android-specific options Similarly to iOS, some configurations specific to Android are needed: @@ -455,9 +506,9 @@ const payload = { }; ``` -> **Note:** If you want to know more about sending an image on Android have a look at [Send an image in the notification payload](https://firebase.google.com/docs/cloud-messaging/android/send-image). +> **Note:** For more information about sending an image on Android, see [Send an image in the notification payload](https://firebase.google.com/docs/cloud-messaging/android/send-image). -### send one image notification for both iOS and Android +### Send one image notification for both iOS and Android It's possible to send one notification that will be delivered to both platforms using the Admin SDK: @@ -502,9 +553,9 @@ admin }); ``` -### Configure Push notification icon and color for Android +### Android: Configure Push notification icon and color -If you want to use a specific icon and color for the push notification, it has to be configured in the tag in the AndroidManifest.xml +If you want to use a specific icon and color for the push notification, configure them in in the `App_Resources/Android/src/main/AndroidManifest.xml` file: ```xml ``` -### iOS: Enable push support in Xcode - +### iOS: Enable the support for the delivery of push notifications in the background in Xcode Open /platforms/ios/yourproject.**xcworkspace** (!) and go to your project's target and head over to "Capabilities" to switch this on (if it isn't already): ![push-xcode-config](https://raw.githubusercontent.com/NativeScript/firebase/main/packages/firebase-messaging/assets/images/push-xcode-config.png) -> **Note:** Without this enabled you will receive push messages in the foreground, but **NOT in the background** / when the app is killed. +> **Note:** Without this enabled you will receive push messages in the foreground, but **NOT in the background**. #### Copy the entitlements file -The previous step created the file `platforms/ios/YourAppName/(Resources/)YourAppName.entitlements`. -Move and rename that file to `app/App_Resources/iOS/app.entitlements` (if it doesn't exist yet, otherwise merge its contents), so that it doesn't get deleted when you run `ns clean`. The relevant content for background push in that file is: +The previous step created the file `platforms/ios/YourAppName/Resources/YourAppName.entitlements`. +To prevent the file from being deleted when you run `ns clean`, move and rename it to `app/App_Resources/iOS/app.entitlements` (if it doesn't exist yet, otherwise merge its contents). The relevant content for background push in that file is: ```xml aps-environment development ``` -#### Allow processing when a background push is received +#### Allow processing received a background push notification -Open `app/App_Resources/iOS/Info.plist` and add this to the bottom: +Open `app/App_Resources/iOS/Info.plist` and add the following code at the bottom: ```xml UIBackgroundModes @@ -592,6 +642,7 @@ showNotificationsWhenInForeground: boolean = firebase().messaging().showNotifica // or firebase().messaging().showNotificationsWhenInForeground = true; ``` +Allows you to always display notifications while the application is in the foreground without sending additional parameters/data when sending the push notification --- #### isDeviceRegisteredForRemoteMessages @@ -599,7 +650,7 @@ firebase().messaging().showNotificationsWhenInForeground = true; import { firebase } from '@nativescript/firebase-core'; isDeviceRegisteredForRemoteMessages: boolean = firebase().messaging().isDeviceRegisteredForRemoteMessages; ``` -A property that returns a boolean value indicating whether the app is registered to receive remote notifications. +A property that returns a boolean value indicating whether the app is registered to receive remote notifications or not. --- #### getToken() @@ -612,6 +663,7 @@ firebase().messaging().getToken() console.log('Error: ', error); }); ``` +Gets the user's device token. For more information, see [getToken()](https://firebase.google.com/docs/reference/kotlin/com/google/firebase/messaging/FirebaseMessaging#getToken()) --- #### getAPNSToken() @@ -619,6 +671,7 @@ firebase().messaging().getToken() import { firebase } from '@nativescript/firebase-core'; aPNSToken: string | null = firebase().messaging().getAPNSToken() ``` +Returns a Apple Push Notification service (APNs) token for the app’s current device. For more information, see [apnsToken](https://firebase.google.com/docs/reference/ios/firebasemessaging/api/reference/Classes/FIRMessaging#apnstoken). --- #### hasPermission() @@ -631,6 +684,7 @@ firebase().messaging().hasPermission() console.log('Error: ', error); }); ``` +Checks if the app, on iOS, has permission to send notifications to the user. --- #### onMessage() @@ -652,6 +706,8 @@ firebase().messaging().onNotificationTap(listener); | Parameter | Type | Description | | --- | --- | --- | | `listener` | `(message: RemoteMessage) => any` | A callback function that is invoked when a new message is received | + +--- #### onToken() ```ts import { firebase } from '@nativescript/firebase-core'; From 05d44021d99c3815b39828c083606f950d55c511 Mon Sep 17 00:00:00 2001 From: Ombuweb Date: Tue, 25 Apr 2023 00:07:38 +0200 Subject: [PATCH 3/4] chore: update --- packages/firebase-messaging/README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/packages/firebase-messaging/README.md b/packages/firebase-messaging/README.md index f37ba1a1..0c34a3be 100644 --- a/packages/firebase-messaging/README.md +++ b/packages/firebase-messaging/README.md @@ -733,6 +733,7 @@ Checks if the app, on iOS, has permission to send notifications to the user. import { firebase } from '@nativescript/firebase-core'; firebase().messaging().onMessage(listener); ``` +Registers a callback function that is invoked when a new message is received. | Parameter | Type | Description | | --- | --- | --- | @@ -744,6 +745,8 @@ firebase().messaging().onMessage(listener); import { firebase } from '@nativescript/firebase-core'; firebase().messaging().onNotificationTap(listener); ``` +Registers a callback function that is invoked when a user taps on a notification. + | Parameter | Type | Description | | --- | --- | --- | | `listener` | `(message: RemoteMessage) => any` | A callback function that is invoked when a new message is received | @@ -754,6 +757,8 @@ firebase().messaging().onNotificationTap(listener); import { firebase } from '@nativescript/firebase-core'; firebase().messaging().onToken(listener); ``` +Registers a callback function that is invoked when a user's device changes its registration token. + | Parameter | Type | Description | | --- | --- | --- | | `listener` | `(token: string) => any` | A callback function that is invoked when | @@ -787,6 +792,7 @@ firebase().messaging().requestPermission(permissions) --- #### subscribeToTopic() + ```ts import { firebase } from '@nativescript/firebase-core'; firebase().messaging().subscribeToTopic(topic) @@ -796,6 +802,8 @@ firebase().messaging().subscribeToTopic(topic) console.log('Error: ', error); }); ``` +For the description of this method, visit [subscribeToTopic()](https://firebase.google.com/docs/reference/android/com/google/firebase/messaging/FirebaseMessaging#subscribeToTopic(java.lang.String)) on the Firebase website. + | Parameter | Type | Description | | --- | --- | --- | | `topic` | `string` | The name of the topic to subscribe to. | @@ -811,6 +819,8 @@ firebase().messaging().unsubscribeFromTopic(topic) console.log('Error: ', error); }); ``` +For the description of this method, visit [unsubscribeToTopic()](https://firebase.google.com/docs/reference/android/com/google/firebase/messaging/FirebaseMessaging#unsubscribeFromTopic(java.lang.String)) on the Firebase website. + | Parameter | Type | Description | | --- | --- | --- | | `topic` | `string` | The name of the topic to unsubscribe from. | @@ -838,6 +848,7 @@ firebase().messaging().deleteToken() console.log('Error: ', error); }); ``` +For the description of the deleteToken method, visit [deleteToken()](https://firebase.google.com/docs/reference/android/com/google/firebase/messaging/FirebaseMessaging#deleteToken()) on the Firebase website. --- From 01459ecb444359d093f248534fd3cd4b81c55e5e Mon Sep 17 00:00:00 2001 From: Ombuweb Date: Fri, 7 Jul 2023 21:44:54 +0200 Subject: [PATCH 4/4] fix: error in content --- packages/firebase-messaging/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/firebase-messaging/README.md b/packages/firebase-messaging/README.md index 9dc6e4e0..ee33b4fa 100644 --- a/packages/firebase-messaging/README.md +++ b/packages/firebase-messaging/README.md @@ -175,7 +175,7 @@ firebase().messaging().showNotificationsWhenInForeground = true; ``` #### Listen to notification messages in the foreground -Since notification messages are displayed automatically(see [Notifications messages delivery and app state](#notifications-messages-delivery-and-app-state)) when the app is in the foreground, sometimes you may want to handle the display of the message manually. To listen to a message in the foreground and handle their display manually, call the [onMessage](#onmessage) method on the instance of [Messaging class](#messaging-class). Code executed via this handler can interact with your application (e.g. updating the state or UI). +Since notification messages are displayed automatically(see [Notifications messages delivery and app state](#notifications-messages-delivery-and-app-state)) when the app is in the background, sometimes you may want to handle the display of the message manually. To listen to a message being received when the app is in the foreground or manually handle the display of the message when the app is in the background, pass a callback function to the [onMessage](#onmessage) method of the instance of [Messaging class](#messaging-class). The callback will. Code executed via this handler can interact with your application (e.g. updating the state or UI). For example, you could display a new Alert each time a message is delivered: