How can I add 3 custom sounds in react native iOS? - ios

I want to add 3 custom sounds in react native iOS.
Have any of you ever solved it?
Currently, when I test the FCM Notification by adding and grouping a voice file (.wav) to the iOS project folder, one of the added sounds is coming out.
For example, suppose you have sound files sound01, sound02, sound03, when the backend sends an FCM notification, I want the specified sound to sound at that time.
I solved Android but I don't know how to set in iOS environment.
is iOS has channel like android?

I solved it with the code below in the source receiving Firebase Cloud Messaging (FCM).
// remote message processing function
const sendLocalNotificationWithSound = remoteMessage => {
if (Platform.OS === 'ios') {
PushNotificationIOS.addNotificationRequest({
id: remoteMessage.notification.notificationId
? remoteMessage.notification.notificationId
: new Date().toString(),
title: remoteMessage.notification.title,
subtitle: remoteMessage.notification.message
? remoteMessage.notification.message
: '',
body: remoteMessage.notification.body,
sound: remoteMessage.notification.sound
})
} else {
PushNotification.localNotification({
channelId: remoteMessage.notification.android.channelId,
id: remoteMessage.notification.notificationId
? remoteMessage.notification.notificationId
: new Date().toString(),
title: remoteMessage.notification.title,
message: remoteMessage.notification.body,
soundName: remoteMessage.notification.android.sound,
playSound: true,
smallIcon: 'ic_stat_ic_notification',
color: '#FFFFFF',
largeIcon: '',
largeIconUrl: '',
vibrate: true,
groupSummary: true
})
}
}
// remote message receiving
React.useEffect(() => {
const getMessage = messaging().onMessage(remoteMessage => {
sendLocalNotificationWithSound(remoteMessage)
})
return () => getMessage()
}, [])
First, the react-native-push-notification and #react-native-community/push-notification-ios libraries must be installed.
react-native-push-notification
#react-native-community/push-notification-ios
function messaging() in code is #react-native-firebase/messaging library.
you have to import module like:
import messaging from '#react-native-firebase/messaging'
on head in code
The official documentation for react-native FCM (firebase cloud messaging) is here -> REACT NATIVE FIREBASE
FCM sending side JSON sample file
(I test with postman)
{
"to": "your fcm token here",
"notification": {
"title": "your notification title",
"body": "your notification description",
"sound": "your notification sound name (Runs on iOS)",
"android_channel_id": "your android channel id here (Runs on Android)",
"priority": "high",
"contentAvailable": true,
"mutableContent": 1
},
"data": {
... // if you need data property
}
}

Related

Removing local notification on ios react native

Im developing an app which is connected to a bluetooth device. If the device is disconnected the user receives a push notification that the device is disconnected. This works fine on both android and iOS with this library.
If the application reconnects, then i want to remove the notification. This works fine on android, but does not remove the notification on iOS.
Here is the code for creating notification:
export const pushNotification = (title: string, message: string) => {
PushNotification.localNotification({
channelId: 'channel',
title: title,
message: message,
id: '1',
});
};
export const configurePushNotification = () => {
PushNotification.configure({
requestPermissions: true,
});
};
export const createChannelForPushNotification = () => {
PushNotification.createChannel(
{
channelId: 'channel',
channelName: 'Push Notification Channel',
channelDescription: 'A channel to send push notifications',
soundName: 'default',
importance: Importance.HIGH,
vibrate: true,
},
(created) => console.log(`createChannel returned '${created}'`),
);
};
I use the code below to remove the notification, which works fine on android.
PushNotification.cancelLocalNotification('1');
Any suggestions as to why it is not removing local notification on iOS?

Nativescript | Firebase notification not working

I'm having a problem using firebase in my Nativescript application, when I'm using android its working great but not working with IOS. the problem is on message sending.
I'm using the push-plugin in the client side
This is the register part in the IOS client side using pushPlugin
const iosSettings:any = {
badge: true,
sound: true,
alert: true,
interactiveSettings: {
actions: [{
identifier: 'READ_IDENTIFIER',
title: 'Read',
activationMode: "foreground",
destructive: false,
authenticationRequired: true
}, {
identifier: 'CANCEL_IDENTIFIER',
title: 'Cancel',
activationMode: "foreground",
destructive: true,
authenticationRequired: true
}],
categories: [{
identifier: 'READ_CATEGORY',
actionsForDefaultContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER'],
actionsForMinimalContext: ['READ_IDENTIFIER', 'CANCEL_IDENTIFIER']
}]
},
notificationCallbackIOS: (message: any) => {
alert(JSON.stringify(message));
}
};
pushPlugin.register(iosSettings, (token: string) => {
// update the token in the server
alert("Device registered. Access token: " + token);
});
}
}, (errorMessage: any) => {
alert("Device NOT registered! " + JSON.stringify(errorMessage));
});
This is how i receive my token to the push notification,
after a got the token when i'm using the pusher application everything works great, i'm getting the notification in the IOS device
but the problem is when im trying to send the notification from the server!.
I get this error :
Invalid registration token provided. Make sure it matches the
registration token the client app receives from registering with FCM.
Node code in my server
var payload = {
data: {
targetId:userToken,
body: "some text"
}
};
var options = {
priority: "high",
contentAvailable: true,
timeToLive: 60 * 60 * 24
};
Admin.messaging().sendToDevice(userToken, <any>payload,options)
.then((response) => {
console.log('notification arrived successfully', response.results[0]);
})
.catch((error) => {
console.log('notification failed', error);
});
registration token for ios is not the same for android. I encountered the same wall you've encountered. You need to use https://github.com/node-apn/node-apn for IOS push notification. and firebase for android notification. You can do the logic on your backend by saving the token. with a field called type which is ios or android if ios you use node-apn and if android use sendToDevice provided by firebase.
Thats what i'm currently using with my current nativescript projects' I'm working on that involves push notification. Hope that helps you, mate.

Firebase-admin doesn't send iOS APN notification

I can send push notifications from Firebase Console Notifications to my iOS device, and it works perfectly being the app in foreground and background.
When I try to send them using Firebase-admin by NodeJS it only works when the app is in foreground, in background nothing happens.
I think that the communications between FCM-APNs are good because it works with the console.
This is my NodeJS code:
function sendFCM(registration_ids, data, collapseKey) {
const options = {
priority: "high",
collapseKey : collapseKey,
contentAvailable : true,
timeToLive: 60 * 60 * 24
};
const payload = {
data: data,
notification: {
title: "My title",
text: "My description",
sound : "default"
}
}
admin.messaging().sendToDevice(registration_ids, payload, options)
.then(function(response) {
console.log("Successfully sent message:", response);
})
.catch(function(error) {
console.log("Error sending message:", error);
});
}
What do you think that it's happening? Do you know some way to log the issue?
The Server Protocol documentation indicates the key for notification text is body, not text. See if this change makes a difference:
const payload = {
data: data,
notification: {
title: "My title",
body: "My description", // <= CHANGE
sound : "default"
}
}

Firebase Cloud Messaging not sending aps payload in correct format for iOS Notification Content & Service Extensions

I'm trying to implement notifications using Firebase. The notification is received correctly when the app is in the background or foreground. So, the basic mechanics are working.
Now I've added Content Extensions and Service Extensions to the app. The Content Extension works when I use a local notification, but the Firebase message payload seems incorrect as far as the optional fields are considered. Here is a link to an image of my console:
And here is the Firebase remote notification payload that comes across (with some of the long Google numbers edited for anonymity:
{
aps =
{
alert =
{
body = "Eureka! 11";
title = "Patient is not doing well";
};
};
category = provider-body-panel;
gcm.message_id = 0:149073;
gcm.n.e = 1;
google.c.a.c_id = 2825604;
google.c.a.e = 1;
google.c.a.ts = 149073;
google.c.a.udt = 0;
mutable-content = 1;
}
It appears that the "category" and "mutable-content" are not in the correct place. They should be in the aps payload.
How can I get those options to be in the payload so that my app can correctly parse it and connect it with the Content and Service Extensions?
To start off, I'm going to mention that there are two types of message payloads for FCM. notification and data. See the documentation here
When sending notifications through the Firebase Notifications Console, it will be treated as a notification payload. However, if you add in Custom Data, it will add it in the payload as a custom key-value pair.
For example, in your post, the FCM payload should look something like this:
{
"notification": {
"body" : "Eureka!",
"title": "Patient is not doing well"
},
"data": {
"category": "provider-body-panel",
"mutable-content" : true,
"click_action" : "provider-body-panel"
}
}
What's wrong?
click_action should be inside notification.
mutable-content should be mutable_content (notice the underscore) and should be on the same level as notification.
(this one I might've misunderstood, but) There is no category parameter for FCM, click_action already corresponds to it.
See the docs for the parameters here.
It it is currently not possible to set the value for click_action and mutable_content when using the Firebase Notifications Console. You'll have to build the payload yourself, something like this:
{
"to": "<REGISTRATION_TOKEN_HERE>",
"mutable_content" : true,
"notification": {
"body" : "Eureka!",
"title": "Patient is not doing well",
"click_action" : "provider-body-panel"
}
}
Then send it from your own App Server. You could also do this by using Postman or cURL
"mutable-content should be "mutable_content" (keyword for firebase server to send as mutable-content for IOS) as you mentioned in your post, I think you left out in edit.
Below is an example with also the corrected format for the data section in the json sent to the FCM server.
So update would be:
{
"to" : "YOUR firebase messaging registration id here",
"mutable_content":true,
"notification": {
"title": "Its about time",
"body": "To go online Amigo",
"click_action": "NotificationCategoryIdentifier ForYourNotificationActions"
},
"data":{
"customKey":"custom data you want to appear in the message payload"
"media-attachment":"mycustom image url",
"catalogID":"mycustom catalog for my custom app"
}
}
Update Firebase Admin SDK and use sendMulticast(payload) method
var admin = require("firebase-admin")
admin.initializeApp({
credential: admin.credential.applicationDefault(),
});
// Create a list containing up to 500 registration tokens.
// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
'YOUR_REGISTRATION_TOKEN_1',
// …
'YOUR_REGISTRATION_TOKEN_N',
];
// See documentation on defining a message payload.
var message = {
notification: {
title: '$FooCorp up 1.43% on the day',
body: '$FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day.'
},
tokens: registrationTokens,
apns: {
payload: {
aps: {
'mutable-content': true, // use single quote
'category': 'INVITE_CATEGORY' // use single quote
}
},
},
};
// Send a message to the device corresponding to the provided
// registration tokens.
admin.messaging().sendMulticast(message)
.then((response) => {
if (response.failureCount > 0) {
const failedTokens = [];
response.responses.forEach((resp, idx) => {
if (!resp.success) {
failedTokens.push(registrationTokens[idx]);
}
});
console.log('List of tokens that caused failures: ' + failedTokens);
}
});
Ref: https://firebase.google.com/docs/cloud-messaging/send-message#send_messages_to_specific_devices
This worked for me with Cloud functions with Node.js
const payload = {
notification: {
title: name,
body: messageText,
badge: "1",
mutable_content: "true"
},
data: {
type: "MESSAGE",
fromUserId: name,
attachmentUrl: imageUrl
}};

Getting notification in console but not in notification center

Coding iOS app in react-native (0.35.0) and using iPad mini (9.3.5) as a test device. Already made Android app with successfully implementing react-native-fcm module for notifications.
Problem I'm facing now in iOS development is that I do receive notification while app is in background but I do not get it in notif center (I can just catch it in console). I have no idea why is it happening.
This is the module I'm using react-native-fcm . I've followed all the instructions in Cocoapods and in manual integration but I can't make it work. I get no errors what so ever. Tried by directly pushing app to device trough xCode and by archiving it (thought that it might be bundling problem).
Any help would be highly appreciated (even though if someone hasn't worked in react-native but ran into this problem in for example swift). If needed I can provide more information.
Best regards,
Bepo.
EDIT:
I'm sending this JSON:
{
"notification" : {
"body" : "Notif body",
"title" : "notif",
"icon" : "myicon",
"sound" : "default",
"vibrate": "default",
"extra" : "Some extra I need"
},
"data" :{
"redirectUrl" : "Url that I need to redirect person after it clicks on notif"
},
"to" : "token that I've gotten",
"content_available": true,
"priority" : "high",
"show_in_foreground": true
}
with headers:
Content-Type:application/json
Authorization:key= my Api key on firebase
FCM response:
{
"multicast_id": ***************45844,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "0:********************a1027b"
}
]
}
Notification i'm catching in console:
{ notification:
{ title: 'notif',
sound: 'default',
vibrate: 'default',
icon: 'myicon',
extra: 'Some extra I need',
sound2: 'default',
e: '1',
body: 'Notif body' },
redirectUrl: 'Url that I need to redirect person after it clicks on notif',
collapse_key: 'My app id',
opened_from_tray: 0,
from: '*********' }

Resources