Reactnative IOS pushotification/PushNotificationIOS onNotification does not called directly when notification received - ios

I used reactnative PushNotification/PushNotificationIOS modules , My issue is when notification received on foreground to my device IOS ,the function onNotification: function(notification) {} does not called directly is called by click only .
I want to fetch data notification paylaod sent via pububnub console directly without any user interaction ,this function is working fine in android but ios not all.
the console does not show anything can help me to solve this issue and thanks.
This the function and imports module:
import PushNotification from "react-native-push-notification";
import PushNotificationIOS from "#react-native-community/push-notification-ios";
onNotification: function(notification) {
if (Platform.OS=='ios')
{
console.log('notif',notification)
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
onAction: function (notification) {
},
onRegistrationError: function(err) {
},
permissions: {
alert: true,
badge: true,
sound: true,
},
popInitialNotification: true,
requestPermissions: true,
senderID: FIREBASE_SENDER_ID,
})
}
and this the object pubnub to send :
{"pn_apns":{
"aps":{
"alert": {
"body": "Course disponible",
"title": "My course"
},
"sound": "beep.wav",
"data": { "reference": "ND1004332", "startstation": "" }
},
"pn_push":[
{
"push_type":"alert",
"auth_method":"token",
"targets":[
{
"environment":"development",
"topic":"com.test.fr"
}
],
"version":"v2"
}
]
}
}

import {Platform} from 'react-native';
import PushNotification from 'react-native-push-notification';
import PushNotificationIOS from "#react-native-community/push-notification-ios";
if (Platform.OS === 'ios') {
// Must be outside of any component LifeCycle (such as `componentDidMount`).
PushNotification.configure({
onNotification: function (notification) {
console.log("NOTIFICATION:", notification);
const { foreground, userInteraction, title, message } = notification;
if (foreground && (title || message) && !userInteraction) PushNotification.localNotification(notification);
notification.finish(PushNotificationIOS.FetchResult.NoData);
},
permissions: {
// alert: true,
// badge: true,
sound: true
},
});
}

Related

Flutter with Firebase Messaging. iOS device doesn't receive data only messages

I'm sending data-only message from Cloud functions
I tried this solution: https://github.com/FirebaseExtended/flutterfire/issues/3395#issuecomment-683973108
Here are the option sendings from Cloud Functions:
{
android: {
priority: "high",
},
apns: {
payload: {
aps: {
contentAvailable: true,
},
},
headers: {
"apns-push-type": "background",
"apns-priority": "5",
"apns-topic": "io.flutter.plugins.firebase.messaging", // bundle identifier
},
},
}
And here the code which handle messages. (I want to create a notification from the client not from the server)
const AndroidNotificationChannel channel = AndroidNotificationChannel(
'high_importance_channel',
'High Importance Notifications',
'This channel is used for important notifications.',
importance: Importance.max,
);
class BackgroundHandler {
static const IOSNotificationDetails iosNotificationDetails =
IOSNotificationDetails(subtitle: 'notification');
static final AndroidNotificationDetails androidNotificationDetails =
AndroidNotificationDetails(channel.id, channel.name, channel.description);
}
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('It works');
print(message);
FlutterLocalNotificationsPlugin().show(0, 'notification', 'new notification', NotificationDetails(android: BackgroundHandler.androidNotificationDetails,
iOS: BackgroundHandler.iosNotificationDetails));
NotificationManager.handleNotificationData(message.data);
});
On Android it works perfectly and it works even with notification, but nothing happens with data only messages.

how to add custom sound in iOS with flutter?

I am new to push notifications and I have this task to add a custom sound whenever the user receives a notification. I am not using flutter local notifications, just the normal firebase configurations and its working well. Can anyone help me add a custom sound for iOS. Any help would be greatly appreciated!
Here is the payload used and the firebase configurations.
options = {
"notification": {
"title": formatter.title,
"body": formatter.body,
"sound": "notification.caf",
"content_available": true,
},
"priority": "high",
"data": {
"badge": user.unopened_notification_count,
"body": formatter.body,
"title": formatter.title,
"id": notification.id,
"notifiable_type": notification.notifiable_type,
"notifiable_id": notification.notifiable_id,
"click_action": "FLUTTER_NOTIFICATION_CLICK"
}
}
also here is my firebase configuration:
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
if (Firebase.apps.isEmpty) await Firebase.initializeApp();
print('Handling a background message ${message.data['id']}');
}
handleNotifications() async {
FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(badge: false, alert: false, sound: true); //presentation options for Apple notifications when received in the foreground.
FirebaseMessaging.onMessage.listen((message) async {
print('Got a message whilst in the FOREGROUND!');
return;
}).onData((data) async {
print('Got a DATA message whilst in the FOREGROUND!');
print('data from stream: ${data.data['id']}');
});
FirebaseMessaging.onMessageOpenedApp.listen((message) async {
print('NOTIFICATION MESSAGE TAPPED');
return;
}).onData((data) async {
print('NOTIFICATION MESSAGE TAPPED');
print('data from stream: ${data.data}');
});
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
FirebaseMessaging.instance.getInitialMessage().then((value) => value != null ? _firebaseMessagingBackgroundHandler : false);
return;
}
attached image here is where I placed the sound file inside Xcode

TypeError: Undefined is not an object (evaluating '_pushNotifications.pushNotifications.configure') React Native

I am new to React Native and am trying to create push notifications on iOS with push-notification-ios and react-native-push-notification. I am following a number of different tutorials on this as I am still learning how it works.
When I run my app I get the following error.
Here is my code
const configure = async () => {
console.log('push notification configured');
PushNotificationIOS.addEventListener('registrationError', (e) => {
PushNotifcation.configure({
onRegister: function(token) {
//process token
alert('Token!' + JSON.stringify(token));
console.log('[CATCHED] onRegister:', token);
db.setToken(token).catch(
console.log('[ERROR] device push token has not been saved on the database'),
);
},
onNotification: async function(notification) {
console.log('[CATCHED] onNotification:' + JSON.stringify(notification));
let notifType = '';
if (Platform.OS === 'ios') {
notifType = getNotificationType(
JSON.parse(notification.data.data).type,
);
} else {
notifType = getNotificationType(
notification.type,
);
}
//process the notification
//required on iOS only
if (Platform.OS === 'ios') {
notification.finish(PushNotificationIOS.FetchResult.NoData);
}
},
senderID: '-----',
permissions: {
alert: true,
badge: true,
sound: true
},
popInitialNotification: true,
requestPermissions: true,
});
});
}
export {
configure,
};
Line 5: you typed PushNotifcation instead PushNotification.
The fixed code is here:
const configure = async () => {
console.log('push notification configured');
PushNotificationIOS.addEventListener('registrationError', (e) => {
PushNotification.configure({
onRegister: function(token) {
//process token
alert('Token!' + JSON.stringify(token));
console.log('[CATCHED] onRegister:', token);
db.setToken(token).catch(
console.log('[ERROR] device push token has not been saved on the database'),
);
},
onNotification: async function(notification) {
console.log('[CATCHED] onNotification:' + JSON.stringify(notification));
let notifType = '';
if (Platform.OS === 'ios') {
notifType = getNotificationType(
JSON.parse(notification.data.data).type,
);
} else {
notifType = getNotificationType(
notification.type,
);
}
//process the notification
//required on iOS only
if (Platform.OS === 'ios') {
notification.finish(PushNotificationIOS.FetchResult.NoData);
}
},
senderID: '-----',
permissions: {
alert: true,
badge: true,
sound: true
},
popInitialNotification: true,
requestPermissions: true,
});
});
}
export {
configure,
};
You have re-build your app try:
yarn android
OR
cd android && ./gradlew clean && cd .. && react-native run-android
Good Luck :)
Your import must be the wrong path
Try this:
import PushNotification from 'react-native-push-notification';
import PushNotificationIOS from '#react-native-community/push-notificatio-ios';

iOS background notifications using Cloud Functions

I have an issue getting data when app goes in background. I'm using Firebase Cloud functions and I think something I didn't code correctly in NodeJS. I have tried many examples and solutions like putting:
content_available: true and priority: 'high' but nothing seems to work. I have to note that:
Notifications are arriving in background and foreground but I can read data from notification in foreground but data is not fetched in background. So there is NO notifications data in background even it is displayed with sound and alert.
I think I'm doing something wrong in data payload so here is my NodeJS method:
var message = {
token: tokenID,
notification: {
title: 'ChatApplication',
body: `${myUsername} send you a message`,
},
android: {
ttl: 3600 * 1000,
notification: {
icon: 'default',
sound: 'default',
click_action: "com.yupi.chatapplication.messaging"
},
data: {
from_user: user_id,
title: 'ChatApplication',
body: `${myUsername} send you a message`
},
},
apns: {
payload: {
aps: {
alert: {
title: 'ChatApplication',
body: `${myUsername} send you a message`
},
badge: 1,
sound: 'default',
content_available: true,
mutable_content: true,
priority: 'high'
},
},
},
};
return admin.messaging().send(message)
.then((response) => {
// Response is a message ID string.
return console.log('Successfully sent message:', response);
})
.catch((error) => {
return console.log('Error sending message:', error);
});
The right field names for the Node.js SDK should be contentAvailable and mutableContent: https://firebase.google.com/docs/reference/admin/node/admin.messaging.Aps

Ionic 2 - iOS NotRegistered

I have done an App in Ionic 2 with the phonegap-plugin-push for notifications.
It works really well with Android but when I try to run it on the iOS it have a few problems.
I can get the registration token but when I do a push message I get the error: NotRegistered as response.
What can it be? The wrong certeficates or some bug in code?
I'm using Ionic 2 on a windows, using phonegap to compile the app to iOS so I have to generate the certificates with openSSL.
There is a few of the code for the push notifications:
config.xml
<plugin name="phonegap-plugin-push" spec="1.8.2">
<variable name="SENDER_ID" value="883847118563"/>
</plugin>
app.component.ts
import {Push, PushObject, PushOptions} from "#ionic-native/push";
(...)
platform.ready().then(() => {
(...)
this.initPushNotification();
});
initPushNotification() {
if (!this.platform.is('cordova')) {
(...)
}
const options: PushOptions = {
android: {
senderID: "8838XXXXXXXX"
},
ios: {
senderID: "8838XXXXXXXX" ,
gcmSandbox: "true",
alert: "true",
badge: false,
sound: 'true'
},
windows: {}
};
const pushObject: PushObject = this.push.init(options);
pushObject.on('registration').subscribe((data: any) => {
(...)
});
pushObject.on('notification').subscribe((data: any) => {
(...)
});
pushObject.on('error').subscribe(error => console.error('Error with Push plugin', error));
}
app.module.ts
import { CloudSettings, CloudModule } from '#ionic/cloud-angular';
const cloudSettings: CloudSettings = {
'core': {
'app_id': 'bdeXXXX'
},
'push': {
'sender_id': '8838XXXXXXXX',
'pluginConfig': {
'ios': {
'badge': true,
'sound': true
},
'android': {
'iconColor': '#ff0000'
}
}
}
};
Thank you in advance for the help.

Resources