From dc1f290684b8d59df6c6d580bc69a9603ebe16b2 Mon Sep 17 00:00:00 2001 From: Tom Hartz Date: Fri, 22 Nov 2019 11:03:43 -0500 Subject: [PATCH] Rationalise calling of and data passed to onMessageReceived(). Resolves #48. --- README.md | 1091 ++++++++++++++++++- src/android/FirebasePlugin.java | 26 +- src/android/OnNotificationOpenReceiver.java | 4 +- src/ios/AppDelegate+FirebasePlugin.m | 148 ++- 4 files changed, 1242 insertions(+), 27 deletions(-) diff --git a/README.md b/README.md index d8c0437db..54f5ac98a 100644 --- a/README.md +++ b/README.md @@ -158,11 +158,1098 @@ If your build is still failing, you can try installing [cordova-android-firebase Checkout our [guide](docs/GOOGLE_TAG_MANAGER.md) for info on setting up Google Tag Manager. -## Configuring Notifications +### Background notifications +If the notification message arrives while the app is in the background/not running, it will be displayed as a system notification. +No callback can be made by the plugin to the app when the message arrives since the display of the notification is entirely handled by the operating system. +However if the user taps the system notification, this launches/resumes the app and the notification title, body and optional data payload is passed to the [onMessageReceived](#onMessageReceived) callback. -Checkout our [guide](docs/NOTIFICATIONS.md) for info on configuring notification icons and colors. +When the `onMessageReceived` is called in response to a user tapping a system notification while the app is in the background/not running, it will be passed the property `tap: "background"`. + + +### Foreground notifications +If the notification message arrives while the app is in running in the foreground, by default **it will NOT be displayed as a system notification**. +Instead the notification message payload will be passed to the [onMessageReceived](#onMessageReceived) callback for the plugin to handle (`tap` will not be set). + +If you include the `notification_foreground` key in the `data` payload, the plugin will also display a system notification upon receiving the notification messages while the app is running in the foreground. +For example: + + { + "name": "my_notification", + "notification": { + "body": "Notification body", + "title": "Notification title" + }, + "data": { + "notification_foreground": "true", + } + } + +When the `onMessageReceived` is called in response to a user tapping a system notification while the app is in the foreground, it will be passed the property `tap: "foreground"`. + +You can set additional properties of the foreground notification using the same key names as for [Data Message Notifications](#data-message-notification-keys). + +### Android notifications +Notifications on Android can be customised to specify the sound, icon, LED colour, etc. that's displayed when the notification arrives. + +#### Android background notifications +If the notification message arrives while the app is in the background/not running, it will be displayed as a system notification. + +In addition to the title and body of the notification message, Android system notifications support specification of the following notification settings: +- [Icon](#android-notification-icons) +- [Sound](#android-notification-sound) +- [Color accent](#android-notification-color) +- [Channel ID](#android-notification-channels) (Android 8.0 (O) and above) + - This channel configuration enables you to specify: + - Sound + - Vibration + - LED light + - Badge + - Importance + - Visibility + - See [createChannel](#createchannel) for details. + +#### Android foreground notifications +If the notification message arrives while the app is in the foreground, by default a system notification won't be displayed and the data will be passed to [onMessageReceived](#onMessageReceived). + +However, if you set the `notification_foreground` key in the `data` section of the notification message payload, this will cause the plugin to display system notification when the message is received while your app is in the foreground. You can customise the notification using the same keys as for [Android data message notifications](#android-data-message-notifications). + +#### Android Notification Channels +- Android 8 (O) introduced [notification channels](https://developer.android.com/training/notify-user/channels). +- Notification channels are configured by the app and used to determine the sound/lights/vibration settings of system notifications. +- By default, this plugin creates a default channel with [default properties]((#default-android-channel-properties) + - These can be overridden via the [setDefaultChannel](#setdefaultchannel) function. +- The plugin enables the creation of additional custom channels via the [createChannel](#createchannel) function. + +On Android 7 and below, the sound setting of system notifications is specified in the notification message itself, for example: + + { + "name": "my_notification", + "notification": { + "body": "Notification body", + "title": "Notification title" + }, + "android": { + "notification": { + "sound": "crystal", + "tag": "default" + } + } + + +#### Android Notification Icons +By default the plugin will use the default app icon for notification messages. + +##### Android Default Notification Icon +To define a custom default notification icon, you need to create the images and deploy them to the `/platforms/android/app/src/main/res/` folders. +The easiest way to do this is using the [Image Asset Studio in Android Studio](https://developer.android.com/studio/write/image-asset-studio#create-notification) or using the [Android Asset Studio webapp](https://romannurik.github.io/AndroidAssetStudio/icons-notification.html#source.type=clipart&source.clipart=ac_unit&source.space.trim=1&source.space.pad=0&name=notification_icon). + +The icons should be monochrome transparent PNGs with the following sizes: + +- mdpi: 24x24 +- hdpi: 36x36 +- xhdpi: 48x48 +- xxhdpi: 72x72 +- xxxhdpi: 96x96 + +Once you've created the images, you need to deploy them from your Cordova project to the native Android project. +To do this, copy the `drawable-DPI` image directories into your Cordova project and add `` entries to the `` section of your `config.xml`, for example: + + + + + + + + + +The default notification icon images **must** be named `notification_icon.png`. + +You then need to add a `` block to the `config.xml` which will instruct Firebase to use your icon as the default for notifications: + + + + + + + + +##### Android Large Notification Icon +The default notification icons above are monochrome, however you can additionally define a larger multi-coloured icon. + +**NOTE:** FCM currently does not support large icons in system notifications displayed for notification messages received in the while the app is in the background (or not running). +So the large icon will currently only be used if specified in [data messages](#android-data-messages) or [foreground notifications](#foreground-notifications). + +The large icon image should be a PNG-24 that's 256x256 pixels and must be named `notification_icon_large.png` and should be placed in the `drawable-xxxhdpi` resource directory. +As with the small icons, you'll need to add a `` entry to the `` section of your `config.xml`: + + + + + + +##### Android Custom Notification Icons +You can define additional sets of notification icons in the same manner as above. +These can be specified in notification or data messages. + +For example: + + + + + + + + +When sending an FCM notification message, you will then specify the icon name in the `android.notification` section, for example: + + { + "name": "my_notification", + "notification": { + "body": "Notification body", + "title": "Notification title" + }, + "android": { + "notification": { + "icon": "my_icon", + } + }, + "data": { + "notification_foreground": "true", + } + } + +You can also reference these icons in [data messages](#android-data-messages), for example: + + { + "name": "my_data", + "data" : { + "notification_foreground": "true", + "notification_body" : "Notification body", + "notification_title": "Notification title", + "notification_android_icon": "my_icon", + } + } + + +#### Android Notification Color +On Android Lollipop (5.0/API 21) and above you can set the default accent color for the notification by adding a color setting. +This is defined as an [ARGB colour](https://en.wikipedia.org/wiki/RGBA_color_space#ARGB_(word-order)) which the plugin sets by default to `#FF00FFFF` (cyan). + +You can override this default by specifying a value using the `ANDROID_ICON_ACCENT` plugin variable during plugin installation, for example: + + cordova plugin add cordova-plugin-firebasex --variable ANDROID_ICON_ACCENT=#FF123456 + +You can override the default color accent by specifying the `colour` key as an RGB value in a notification message, e.g.: + + { + "name": "my_notification", + "notification": { + "body": "Notification body", + "title": "Notification title" + }, + "android": { + "notification": { + "color": "#00ff00" + } + } + } + +And in a data message: + + { + "name": "my_data", + "data" : { + "notification_foreground": "true", + "notification_body" : "Notification body", + "notification_title": "Notification title", + "notification_android_color": "#00ff00" + } + } + + +#### Android Notification Sound +You can specify custom sounds for notifications or play the device default notification sound. + +Custom sound files must be in `.mp3` format and deployed to the `/res/raw` directory in the Android project. +To do this, you can add `` tags to your `config.xml` to deploy the files, for example: + + + + + +In a notification message, you specify the sound file name in the `android.notification` section, for example: + + { + "name": "my_notification", + "notification": { + "body": "Notification body", + "title": "Notification title" + }, + "android": { + "notification": { + "sound": "crystal" + } + } + } + +And in a data message by specifying it in the `data` section: + + { + "name": "my_data", + "data" : { + "notification_foreground": "true", + "notification_body" : "Notification body", + "notification_title": "Notification title", + "notification_android_sound": "crystal" + } + } + +- To play the default notification sound, set `"sound": "default"`. +- To display a silent notification (no sound), omit the `sound` key from the message. + +### iOS notifications +Notifications on iOS can be customised to specify the sound and badge number that's displayed when the notification arrives. + +Notification settings are specified in the `apns.payload.aps` key of the notification message payload. +For example: + + { + "name": "my_notification", + "notification": { + "body": "Notification body", + "title": "Notification title" + }, + "apns": { + "payload": { + "aps": { + "sound": "default", + "badge": 1 + } + } + } + } + +#### iOS notification sound +You can specify custom sounds for notifications or play the device default notification sound. + +Custom sound files must be in a supported audio format (see [this Apple documentation](https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/SupportingNotificationsinYourApp.html#//apple_ref/doc/uid/TP40008194-CH4-SW10) for supported formats). +For example to convert an `.mp3` file to the supported `.caf` format run: + + afconvert my_sound.mp3 my_sound.caf -d ima4 -f caff -v + +Sound files must be deployed with the iOS application bundle. +To do this, you can add `` tags to your `config.xml` to deploy the files, for example: + + + + + +In a notification message, specify the `sound` key in the `apns.payload.aps` section, for example: + + { + "name": "my_notification", + "notification": { + "body": "Notification body", + "title": "Notification title" + }, + "apns": { + "payload": { + "aps": { + "sound": "my_sound.caf" + } + } + } + } + +- To play the default notification sound, set `"sound": "default"`. +- To display a silent notification (no sound), omit the `sound` key from the message. + +In a data message, specify the `notification_ios_sound` key in the `data` section: + + { + "name": "my_data", + "data" : { + "notification_foreground": "true", + "notification_body" : "Notification body", + "notification_title": "Notification title", + "notification_ios_sound": "my_sound.caf" + } + } + +#### iOS badge number +In a notification message, specify the `badge` key in the `apns.payload.aps` section, for example: + + { + "name": "my_notification", + "notification": { + "body": "Notification body", + "title": "Notification title" + }, + "apns": { + "payload": { + "aps": { + "badge": 1 + } + } + } + } + +In a data message, specify the `notification_ios_badge` key in the `data` section: + + { + "name": "my_data", + "data" : { + "notification_foreground": "true", + "notification_body" : "Notification body", + "notification_title": "Notification title", + "notification_ios_badge": 1 + } + } + + +### Data messages +FCM data messages are sent as an arbitrary k/v structure and by default are passed to the app for it to handle them. + +**NOTE:** FCM data messages **cannot** be sent from the Firebase Console - they can only be sent via the FCM APIs. + +#### Data message notifications +This plugin enables a data message to be displayed as a system notification. +To have the app display a notification when the data message arrives, you need to set the `notification_foreground` key in the `data` section. +You can then set a `notification_title` and `notification_body`, for example: + + { + "name": "my_data", + "data" : { + "notification_foreground": "true", + "notification_body" : "Notification body", + "notification_title": "Notification title", + "foo" : "bar" + } + } + +Additional platform-specific notification options can be set using the additional keys below (which are only relevant if the `notification_foreground` key is set). + +Note: [foreground notification messages](#foreground-notifications) can also make use of these keys. + +##### Android data message notifications +On Android: +- Data messages that arrive while your app is running in the foreground or running in the background will be immediately passed to the `onMessageReceived()` Javascript handler in the Webview. +- Data messages (not containing notification keys) that arrive while your app is **not running** will be passed to the `onMessageReceived()` Javascript handler when the app is next launched. +- Data messages containing notification keys that arrive while your app is running or **not running** will be displayed as a system notification. + +The following Android-specific keys are supported and should be placed inside the `data` section: + +- `notification_android_icon` - name of a [custom notification icon](#android-custom-notification-icons) in the drawable resources + - if not specified, the plugin will use the default `notification_icon` if it exists; otherwise the default app icon will be displayed + - if a [large icon](#android-large-notification-icon) has been defined, it will also be displayed in the system notification. +- `notification_android_color` - the [color accent](#android-notification-color) to use for the small notification icon + - if not specified, the default color accent will be used +- `notification_android_channel_id` - ID of the [notification channel](#android-notification-channels) to use to display the notification + - Only applies to Android 8.0 and above + - If not specified, the [default notification channel](#default-android-channel-properties) will be used. + - You can override the default configuration for the default notification channel using [setDefaultChannel](#setdefaultchannel). + - You can create additional channels using [createChannel](#createchannel). +- `notification_android_priority` - Specifies the notification priority + - Possible values: + - `2` - Highest notification priority for your application's most important items that require the user's prompt attention or input. + - `1` - Higher notification priority for more important notifications or alerts. + - `0` - Default notification priority. + - `-1` - Lower notification priority for items that are less important. + - `-2` - Lowest notification priority. These items might not be shown to the user except under special circumstances, such as detailed notification logs. + - Defaults to `2` if not specified. +- `notification_android_visibility` - Specifies the notification visibility + - Possible values: + - `1` - Show this notification in its entirety on all lockscreens. + - `0` - Show this notification on all lockscreens, but conceal sensitive or private information on secure lockscreens. + - `-1` - Do not reveal any part of this notification on a secure lockscreen. + - Defaults to `1` if not specified. + +The following keys only apply to Android 7 and below. +On Android 8 and above they will be ignored - the `notification_android_channel_id` property should be used to specify a [notification channel](#android-notification-channels) with equivalent settings. + +- `notification_android_sound` - name of a sound resource to play as the [notification sound](#android-notification-sound) + - if not specified, no sound is played + - `default` plays the default device notification sound + - otherwise should be the name of an `.mp3` file in the `/res/raw` directory, e.g. `my_sound.mp3` => `"sounds": "my_sound"` +- `notification_android_lights` - color and pattern to use to blink the LED light + - if not defined, LED will not blink + - in the format `ARGB, time_on_ms, time_off_ms` where + - `ARGB` is an ARGB color definition e.g. `#ffff0000` + - `time_on_ms` is the time in milliseconds to turn the LED on for + - `time_off_ms` is the time in milliseconds to turn the LED off for + - e.g. `"lights": "#ffff0000, 250, 250"` +- `notification_android_vibrate` - pattern of vibrations to use when the message arrives + - if not specified, device will not vibrate + - an array of numbers specifying the time in milliseconds to vibrate + - e.g. `"vibrate": "500, 200, 500"` + +Example data message with Android notification keys: + + { + "name": "my_data_message", + "data" : { + "notification_foreground": "true", + "notification_body" : "Notification body", + "notification_title": "Notification title", + "notification_android_channel_id": "my_channel", + "notification_android_priority": "2", + "notification_android_visibility": "1", + "notification_android_color": "#ff0000", + "notification_android_icon": "coffee", + "notification_android_sound": "crystal", + "notification_android_vibrate": "500, 200, 500", + "notification_android_lights": "#ffff0000, 250, 250" + } + } + +##### iOS data message notifications +On iOS: +- Data messages that arrive while your app is running in the foreground or running in the background will be immediately passed to the `onMessageReceived()` Javascript handler in the Webview. +- Data messages that arrive while your app is **not running** will **NOT be received by your app!** + +The following iOS-specific keys are supported and should be placed inside the `data` section: + +- `notification_ios_sound` - Sound to play when the notification is displayed + - To play a custom sound, set the name of the sound file bundled with your app, e.g. `"sound": "my_sound.caf"` - see [iOS notification sound](#ios-notification-sound) for more info. + - To play the default notification sound, set `"sound": "default"`. + - To display a silent notification (no sound), omit the `sound` key from the message. +- `notification_ios_badge` - Badge number to display on app icon on home screen. + +For example: + + { + "name": "my_data", + "data" : { + "notification_foreground": "true", + "notification_body" : "Notification body", + "notification_title": "Notification title", + "notification_ios_sound": "my_sound.caf", + "notification_ios_badge": 1 + } + } + + +## Google Tag Manager +Download your container-config json file from Tag Manager and add a resource-file node in your `config.xml`. + +### Android +``` + + + ... +``` + +### iOS +``` + + + ... +``` ## API See the full [API](docs/API.md) available for this plugin. + +#### getToken +Get the device token (id): +``` +window.FirebasePlugin.getToken(function(token) { + // save this server-side and use it to push notifications to this device + console.log(token); +}, function(error) { + console.error(error); +}); +``` +Note that token will be null if it has not been established yet. + +#### onTokenRefresh +Register for token changes: +``` +window.FirebasePlugin.onTokenRefresh(function(token) { + // save this server-side and use it to push notifications to this device + console.log(token); +}, function(error) { + console.error(error); +}); +``` +This is the best way to get a valid token for the device as soon as the token is established + +#### onMessageReceived +Registers a callback function to invoke when: +- a notification or data message is received by the app +- a system notification is tapped by the user +``` +window.FirebasePlugin.onMessageReceived(function(message) { + console.log("Message type: " + message.messageType); + if(message.messageType === "notification"){ + console.log("Notification message received"); + if(message.tap){ + console.log("Tapped in " + message.tap); + } + } + console.dir(notification); +}, function(error) { + console.error(error); +}); +``` + +The `message` object passed to the callback function will contain the full platform-specific FCM message payload along with the following keys: +- `messageType=notification|data` - indicates if received message is a notification or data message +- `tap=foreground|background` - set if the call to `onMessageReceived()` was initiated by user tapping on a system notification. + - indicates if the system notification was tapped while the app was in the foreground or background. + - not set if no system notification was tapped (i.e. message was received directly from FCM rather than via a user tap on a system notification). + + +Notification message flow: + +1. App is in foreground: + a. By default, when a notification message arrives the app receives the notification message payload in the `onMessageReceived` JavaScript callback without any system notification on the device itself. + b. If the `data` section contains the `notification_foreground` key, the plugin will display a system notification while in the foreground. +2. App is in background: + a. User receives the notification message as a system notification in the device notification bar + b. User taps the system notification which launches the app + b. User receives the notification message payload in the `onMessageReceived` JavaScript callback + +Data message flow: + +1. App is in foreground: + a. By default, when a data message arrives the app receives the data message payload in the `onMessageReceived` JavaScript callback without any system notification on the device itself. + b. If the `data` section contains the `notification_foreground` key, the plugin will display a system notification while in the foreground. +2. App is in background: + a. The app receives the data message in the `onMessageReceived` JavaScript callback while in the background + b. If the data message contains the [data message notification keys](#data-message-notifications), the plugin will display a system notification for the data message while in the background. + +#### grantPermission +Grant permission to receive push notifications (will trigger prompt) and return `hasPermission: true`. +iOS only (Android will always return true). + +``` +window.FirebasePlugin.grantPermission(function(hasPermission){ + console.log("Permission was " + (hasPermission ? "granted" : "denied")); +}); +``` +#### hasPermission +Check permission to receive push notifications and return `hasPermission: true`. +iOS only (Android will always return true). +``` +window.FirebasePlugin.hasPermission(function(hasPermission){ + console.log("Permission is " + (hasPermission ? "granted" : "denied")); +}); +``` + +#### unregister +Unregister from firebase, used to stop receiving push notifications. +Call this when you logout user from your app. +``` +window.FirebasePlugin.unregister(); +``` + + +#### setBadgeNumber +Set a number on the icon badge: +``` +window.FirebasePlugin.setBadgeNumber(3); +``` + +Set 0 to clear the badge +``` +window.FirebasePlugin.setBadgeNumber(0); +``` + +#### getBadgeNumber +Get icon badge number: +``` +window.FirebasePlugin.getBadgeNumber(function(n) { + console.log(n); +}); +``` + +#### clearAllNotifications +Clear all pending notifications from the drawer: +``` +window.FirebasePlugin.clearAllNotifications(); +``` + +#### subscribe +Subscribe to a topic. + +Topic messaging allows you to send a message to multiple devices that have opted in to a particular topic. + + +``` +window.FirebasePlugin.subscribe("latest_news"); +``` + +#### unsubscribe +Unsubscribe from a topic. + +This will stop you receiving messages for that topic +``` +window.FirebasePlugin.unsubscribe("latest_news"); +``` + +#### createChannel +Android 8+ only. +Creates a custom channel to be used by notification messages which have the channel property set in the message payload to the `id` of the created channel: +- For background (system) notifications: `android.notification.channel_id` +- For foreground/data notifications: `data.notification_android_channel_id` + +For each channel you may set the sound to be played, the color of the phone LED (if supported by the device), whether to vibrate and set vibration pattern (if supported by the device), importance and visibility. +Channels should be created as soon as possible (on program start) so notifications can work as expected. +A default channel is created by the plugin at app startup; the properties of this can be overridden see [setDefaultChannel](#setdefaultchannel) + +Calling on Android 7 or below or another platform will have no effect. + +``` +// Define custom channel - all keys are except 'id' are optional. +var channel = { + // channel ID - must be unique per app package + id: "my_channel_id", + + // Channel name. Default: empty string + name: "Channel name", + + //The sound to play once a push comes. Default value: 'default' + //Values allowed: + //'default' - plays the default notification sound + //'ringtone' - plays the currently set ringtone + //'false' - silent; don't play any sound + //filename - the filename of the sound file located in '/res/raw' without file extension (mysound.mp3 -> mysound) + sound: "mysound", + + //Vibrate on new notification. Default value: true + //Possible values: + //Boolean - vibrate or not + //Array - vibration pattern - e.g. [500, 200, 500] - milliseconds vibrate, milliseconds pause, vibrate, pause, etc. + vibration: true, + + // Whether to blink the LED + light: true, + + //LED color in ARGB format - this example BLUE color. If set to -1, light color will be default. Default value: -1. + lightColor: "0xFF0000FF", + + //Importance - integer from 0 to 4. Default value: 4 + //0 - none - no sound, does not show in the shade + //1 - min - no sound, only shows in the shade, below the fold + //2 - low - no sound, shows in the shade, and potentially in the status bar + //3 - default - shows everywhere, makes noise, but does not visually intrude + //4 - high - shows everywhere, makes noise and peeks + importance: 4, + + //Show badge over app icon when non handled pushes are present. Default value: true + badge: true, + + //Show message on locked screen. Default value: 1 + //Possible values (default 1): + //-1 - secret - Do not reveal any part of the notification on a secure lockscreen. + //0 - private - Show the notification on all lockscreens, but conceal sensitive or private information on secure lockscreens. + //1 - public - Show the notification in its entirety on all lockscreens. + visibility: 1 +}; + +// Create the channel +window.FirebasePlugin.createChannel(options, +function(){ + console.log('Channel created: ' + options.id); +}, +function(error){ + console.log('Create channel error: ' + error); +}); +``` + +Example FCM v1 API notification message payload for invoking the above example channel: + +``` + +{ + "notification": + { + "title":"Notification title", + "body":"Notification body", + }, + "android": { + "notification": { + "channel_id": "my_channel_id" + } + } +} + +``` + +#### setDefaultChannel +Android 8+ only. +Overrides the properties for the default channel. +The default channel is used if no other channel exists or is specified in the notification. +Any options not specified will not be overridden. +Should be called as soon as possible (on app start) so default notifications will work as expected. +Calling on Android 7 or below or another platform will have no effect. + +``` +var options = { + id: "my_default_channel", + name: "My Default Name", + sound: "ringtone", + vibration: [500, 200, 500], + light: true, + lightColor: "0xFF0000FF", + importance: 4, + badge: false, + visibility: -1 +}; + +window.FirebasePlugin.setDefaultChannel(options, +function(){ + console.log('Channel created: ' + options.id); +}, +function(error){ + console.log('Create channel error: ' + error); +}); +``` + +#### Default Android Channel Properties +The default channel is initialised at app startup with the following default settings: + +``` +{ + id: "fcm_default_channel", + name: "Default", + sound: "default", + vibration: true, + light: true, + lightColor: -1, + importance: 4, + badge: true, + visibility: 1 +} +``` + +#### deleteChannel +Android 8+ only. +Removes a previously defined channel. +Calling on Android 7 or below or another platform will have no effect. + +``` +window.FirebasePlugin.deleteChannel("my_channel_id", +function(){ + console.log('Channel deleted'); +}, +function(error){ + console.log('Delete channel error: ' + error); +}); + +``` + +#### listChannels +Android 8+ only. +Gets a list of all channels. +Calling on Android 7 or below or another platform will have no effect. + +``` +window.FirebasePlugin.listChannels( +function(channels){ + if(typeof channels == "undefined") + return; + + for(var i=0;i 1) { - if (FirebasePlugin.notificationStack == null) { - FirebasePlugin.notificationStack = new ArrayList(); + try { + Log.d(TAG, "Starting Firebase plugin"); + FirebaseApp.initializeApp(applicationContext); + mFirebaseAnalytics = FirebaseAnalytics.getInstance(applicationContext); + mFirebaseAnalytics.setAnalyticsCollectionEnabled(true); + if (extras != null && extras.size() > 1) { + if (FirebasePlugin.notificationStack == null) { + FirebasePlugin.notificationStack = new ArrayList(); + } + if (extras.containsKey("google.message_id")) { + extras.putString("messageType", "notification"); + extras.putString("tap", "background"); + notificationStack.add(extras); + } } if (extras.containsKey("google.message_id")) { extras.putBoolean("tap", true); @@ -309,8 +316,9 @@ public void onNewIntent(Intent intent) { super.onNewIntent(intent); final Bundle data = intent.getExtras(); if (data != null && data.containsKey("google.message_id")) { - data.putBoolean("tap", true); - FirebasePlugin.sendNotification(data, this.cordova.getActivity().getApplicationContext()); + data.putString("messageType", "notification"); + data.putString("tap", "background"); + FirebasePlugin.sendMessage(data, applicationContext); } } diff --git a/src/android/OnNotificationOpenReceiver.java b/src/android/OnNotificationOpenReceiver.java index 92e6ebc76..5a2d4728e 100644 --- a/src/android/OnNotificationOpenReceiver.java +++ b/src/android/OnNotificationOpenReceiver.java @@ -9,6 +9,7 @@ public class OnNotificationOpenReceiver extends BroadcastReceiver { + // Called on tapping foreground notification @Override public void onReceive(Context context, Intent intent) { PackageManager pm = context.getPackageManager(); @@ -17,7 +18,8 @@ public void onReceive(Context context, Intent intent) { launchIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); Bundle data = intent.getExtras(); - data.putBoolean("tap", true); + if(!data.containsKey("messageType")) data.putString("messageType", "notification"); + data.putString("tap", FirebasePlugin.inBackground() ? "background" : "foreground"); FirebasePlugin.sendNotification(data, context); diff --git a/src/ios/AppDelegate+FirebasePlugin.m b/src/ios/AppDelegate+FirebasePlugin.m index 77ecc1fd4..ed3684819 100644 --- a/src/ios/AppDelegate+FirebasePlugin.m +++ b/src/ios/AppDelegate+FirebasePlugin.m @@ -127,21 +127,18 @@ - (void)application:(UIApplication *)application didRegisterForRemoteNotificatio NSLog(@"deviceToken1 = %@", deviceToken); } -- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { - NSDictionary *mutableUserInfo = [userInfo mutableCopy]; - - [mutableUserInfo setValue:self.applicationInBackground forKey:@"tap"]; - - // Print full message. - NSLog(@"%@", mutableUserInfo); - - [FirebasePlugin.firebasePlugin sendNotification:mutableUserInfo]; -} - +//Tells the app that a remote notification arrived that indicates there is data to be fetched. +// Called when a message arrives in the foreground and remote notifications permission has been granted - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { NSDictionary *mutableUserInfo = [userInfo mutableCopy]; + NSDictionary* aps = [mutableUserInfo objectForKey:@"aps"]; + if([aps objectForKey:@"alert"] != nil){ + [mutableUserInfo setValue:@"notification" forKey:@"messageType"]; + }else{ + [mutableUserInfo setValue:@"data" forKey:@"messageType"]; + } [mutableUserInfo setValue:self.applicationInBackground forKey:@"tap"]; // Print full message. @@ -161,6 +158,108 @@ - (void)messaging:(FIRMessaging *)messaging didReceiveMessage:(FIRMessagingRemot [FirebasePlugin.firebasePlugin sendNotification:remoteMessage.appData]; } +// Scans a message for keys which indicate a notification should be shown. +// If found, extracts relevant keys and uses then to display a local notification +-(void)processMessageForForegroundNotification:(NSDictionary*)messageData { + bool showForegroundNotification = [messageData objectForKey:@"notification_foreground"]; + if(!showForegroundNotification){ + return; + } + + NSString* title = nil; + NSString* body = nil; + NSString* sound = nil; + NSString* badge = nil; + + // Extract APNS notification keys + NSDictionary* aps = [messageData objectForKey:@"aps"]; + if([aps objectForKey:@"alert"] != nil){ + NSDictionary* alert = [aps objectForKey:@"alert"]; + if([alert objectForKey:@"title"] != nil){ + title = [alert objectForKey:@"title"]; + } + if([alert objectForKey:@"body"] != nil){ + body = [alert objectForKey:@"body"]; + } + if([aps objectForKey:@"sound"] != nil){ + sound = [aps objectForKey:@"sound"]; + } + if([aps objectForKey:@"badge"] != nil){ + sound = [aps objectForKey:@"badge"]; + } + } + + // Extract data notification keys + if([messageData objectForKey:@"notification_title"] != nil){ + title = [messageData objectForKey:@"notification_title"]; + } + if([messageData objectForKey:@"notification_body"] != nil){ + body = [messageData objectForKey:@"notification_body"]; + } + if([messageData objectForKey:@"notification_ios_sound"] != nil){ + sound = [messageData objectForKey:@"notification_ios_sound"]; + } + if([messageData objectForKey:@"notification_ios_badge"] != nil){ + badge = [messageData objectForKey:@"notification_ios_badge"]; + } + + if(title == nil || body == nil){ + return; + } + + [[UNUserNotificationCenter currentNotificationCenter] getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) { + if (settings.alertSetting == UNNotificationSettingEnabled) { + UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init]; + objNotificationContent.title = [NSString localizedUserNotificationStringForKey:title arguments:nil]; + objNotificationContent.body = [NSString localizedUserNotificationStringForKey:body arguments:nil]; + + NSDictionary* alert = [[NSDictionary alloc] initWithObjectsAndKeys: + title, @"title", + body, @"body" + , nil]; + NSMutableDictionary* aps = [[NSMutableDictionary alloc] initWithObjectsAndKeys: + alert, @"alert", + nil]; + + if([sound isEqualToString:@"default"]){ + objNotificationContent.sound = [UNNotificationSound defaultSound]; + [aps setValue:sound forKey:@"sound"]; + }else if(sound != nil){ + objNotificationContent.sound = [UNNotificationSound soundNamed:sound]; + [aps setValue:sound forKey:@"sound"]; + } + + if(badge != nil){ + NSNumberFormatter* f = [[NSNumberFormatter alloc] init]; + f.numberStyle = NSNumberFormatterDecimalStyle; + objNotificationContent.badge = [f numberFromString:badge]; + [aps setValue:badge forKey:@"badge"]; + } + + + NSDictionary* userInfo = [[NSDictionary alloc] initWithObjectsAndKeys: + @"true", @"notification_foreground", + @"data", @"messageType", + aps, @"aps" + , nil]; + + objNotificationContent.userInfo = userInfo; + + UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:0.1f repeats:NO]; + UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"local_notification" content:objNotificationContent trigger:trigger]; + [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) { + if (!error) { + NSLog(@"Local Notification succeeded"); + } else { + NSLog(@"Local Notification failed: %@", error); + } + }]; + }else{ + NSLog(@"processMessageForForegroundNotification: cannot show notification as permission denied"); + } + }]; +} + - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { NSLog(@"Unable to register for remote notifications: %@", error); } @@ -178,7 +277,11 @@ - (void)userNotificationCenter:(UNUserNotificationCenter *)center if (![notification.request.trigger isKindOfClass:UNPushNotificationTrigger.class]) return; - NSDictionary *mutableUserInfo = [notification.request.content.userInfo mutableCopy]; + NSDictionary* mutableUserInfo = [notification.request.content.userInfo mutableCopy]; + NSString* messageType = [mutableUserInfo objectForKey:@"messageType"]; + if(![messageType isEqualToString:@"data"]){ + [mutableUserInfo setValue:@"notification" forKey:@"messageType"]; + } [mutableUserInfo setValue:self.applicationInBackground forKey:@"tap"]; @@ -189,6 +292,8 @@ - (void)userNotificationCenter:(UNUserNotificationCenter *)center [FirebasePlugin.firebasePlugin sendNotification:mutableUserInfo]; } +// Asks the delegate to process the user's response to a delivered notification. +// Called when user taps on system notification - (void) userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler @@ -197,12 +302,25 @@ - (void) userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:response withCompletionHandler:completionHandler]; - if (![response.notification.request.trigger isKindOfClass:UNPushNotificationTrigger.class]) + if (![response.notification.request.trigger isKindOfClass:UNPushNotificationTrigger.class] && ![response.notification.request.trigger isKindOfClass:UNTimeIntervalNotificationTrigger.class]){ + NSLog(@"didReceiveNotificationResponse: aborting as not a supported UNNotificationTrigger"); return; + } NSDictionary *mutableUserInfo = [response.notification.request.content.userInfo mutableCopy]; - - [mutableUserInfo setValue:@YES forKey:@"tap"]; + + NSString* tap; + if([self.applicationInBackground isEqual:[NSNumber numberWithBool:YES]]){ + tap = @"background"; + }else{ + tap = @"foreground"; + + } + [mutableUserInfo setValue:tap forKey:@"tap"]; + if([mutableUserInfo objectForKey:@"messageType"] == nil){ + [mutableUserInfo setValue:@"notification" forKey:@"messageType"]; + } + // Print full message. NSLog(@"Response %@", mutableUserInfo);