I'm trying to add notification with firebase in my ionic application (ionic 5). I follow this tutorial : https://www.positronx.io/ionic-firebase-fcm-push-notification-tutorial-with-example/
I recieve the token and when i send a notification from firebase console, the notification is displayed on the phone (emulator) but nothing is displayed in the console to handle the notification click...
I add FCM into provides in app.modules.ts and i have added the following code in the app.component.ts
import { FCM } from "#ionic-native/fcm/ngx";
...
constructor(
...
private fcm: FCM
) {}
initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
this.fcm.getToken().then(token => {
console.log(token);
});
this.fcm.onTokenRefresh().subscribe(token => {
console.log(token);
});
this.fcm.onNotification().subscribe(data => {
console.log(data);
if (data.wasTapped) {
console.log('Received in background');
} else {
console.log('Received in foreground');
}
});
if (token === null) {
this.msgService.presentToast(
"Impossible de configurer la reception des notifications"
);
}
// Observer.hasTokenFCM.next(token);
if (this.platform.is("ios") || this.platform.is("android")) {
// this.saveToken(token);
}
});
And a have installed the following plugins:
ionic cordova plugin add cordova-plugin-fcm-with-dependecy-updated
npm install #ionic-native/fcm
cordova plugin list:
cordova-plugin-fcm-with-dependecy-updated 4.4.0 "Cordova FCM Push Plugin"
In my package.json:
dependencies:
"#ionic-native/fcm": "^5.22.0",
"cordova-plugin-fcm-with-dependecy-updated": "^4.1.1",
"cordova" -> "plugins":
"cordova-plugin-fcm-with-dependecy-updated": {
"FCM_CORE_VERSION": "16.0.8",
"FCM_VERSION": "18.0.0",
"GRADLE_TOOLS_VERSION": "2.3.+",
"GOOGLE_SERVICES_VERSION": "3.0.0"
},
Thanks a lot if you found why the "this.fcm.onNotification.subscribe" is never fired...
To fix this, use cordova-plugin-fcm-with-dependecy-updated plugin instead of #ionic-native/fcm/ngx, they are conflicting with each other. If onNotification method is not fired and you can't get the payload, try to use getInitialPushPayload
...
const pushPayload = await this.fcm.getInitialPushPayload();
if (pushPayload) {
this.processPayload(pushPayload);
}
this.fcm.onNotification().subscribe(
(payload: PushNotification) => this.processPayload(payload)
);
...
apparently i need to use
this.firebase.onMessageReceived().subscribe(notification => {
if (notification["tap"]) {
...
}
....
});
with firebase plugin to handle notification... but i don't know why.
Related
I am creating an ionic-angular app. I tried to use push notification with the capacitor plugin. But I got an error like this. Can anyone help me?
**"ERROR Error: Uncaught (in promise): Error: "PushNotifications" plugin is not implemented on android
Error: "PushNotifications" plugin is not implemented on android"**
I resolved "ERROR Error: Uncaught (in promise): Error: "PushNotifications" plugin is not implemented on android
Error: "PushNotifications" plugin is not implemented on android" error please follow below step
Add google-service.json file inside android/app folder
add this code in .ts file
import {
ActionPerformed,
PushNotificationSchema,
PushNotifications,
Token,
} from '#capacitor/push-notifications';
import { Platform } from '#ionic/angular';
constructor(public platform: Platform) {
this.platform.ready().then(() => {
this.pushAdded();
})
}
pushAdded() {
// Request permission to use push notifications
// iOS will prompt user and return if they granted permission or not
// Android will just grant without prompting
PushNotifications.requestPermissions().then(result => {
if (result.receive === 'granted') {
// Register with Apple / Google to receive push via APNS/FCM
PushNotifications.register();
} else {
// Show some error
}
});
PushNotifications.addListener('registration', (token: Token) => {
alert('Push registration success, token: ' + token.value);
});
PushNotifications.addListener('registrationError', (error: any) => {
alert('Error on registration: ' + JSON.stringify(error));
});
PushNotifications.addListener(
'pushNotificationReceived',
(notification: PushNotificationSchema) => {
alert('Push received: ' + JSON.stringify(notification));
},
);
PushNotifications.addListener(
'pushNotificationActionPerformed',
(notification: ActionPerformed) => {
alert('Push action performed: ' + JSON.stringify(notification));
},
);
}
I have fixed this issue by removing the android folder and re-add that. Then it worked. Thanks, Ravi Ashara for helping.
Check your MainActivity.java within your project. In the last version of Capacitor you have to remove the code "onCreate".
See: https://capacitorjs.com/docs/updating/3-0#switch-to-automatic-android-plugin-loading
I've started moving on capacitor. After reading https://capacitorjs.com/docs/cordova/known-incompatible-plugins I found that capacitor doesn't support some cordova plugins.
I'm using cordova-plugin-fcm-with-dependecy-updated for android and cordova-plugin-fcm for iOS in my app for push notifications but capacitor doesn’t support these plugins so I used capacitor native approach guided in https://capacitorjs.com/docs/apis/push-notifications#addlistener.
The native approach is not throwing any error and I am able to get registered token as well but I am not receiving push notifications on registered device.
I also tried https://www.npmjs.com/package/capacitor-fcm but fcm.getToken() is returning null.
capacitor.config.json
"plugins": {
"PushNotifications": {
"presentationOptions": [
"badge",
"sound",
"alert"
]
}
}
app.ts
#Component({
selector: 'app-root',
templateUrl: 'app.component.html'
})
export class AppComponent implements OnInit {
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private fcmService: FcmService
) {
this.initializeApp();
}
ngOnInit() {}
initializeApp() {
this.platform.ready().then(() => {
setTimeout(() => {
this.splashScreen.hide();
}, 300);
this.fcmService.initPush();
});
}
}
fcm.service.ts
import { Injectable } from '#angular/core';
import {
Plugins,
PushNotification,
PushNotificationToken,
PushNotificationActionPerformed,
Capacitor
} from '#capacitor/core';
import { Router } from '#angular/router';
const { PushNotifications, Modals } = Plugins;
import { FCM } from '#capacitor-community/fcm';
const fcm = new FCM();
const { FCMPlugin } = Plugins;
#Injectable({
providedIn: 'root'
})
export class FcmService {
constructor(
private router: Router) { }
initPush() {
alert('Capacitor platform' + Capacitor.platform);
if (Capacitor.platform !== 'web') {
this.registerPush();
}
}
private registerPush() {
PushNotifications.requestPermission().then((permission) => {
if (permission.granted) {
// Register with Apple / Google to receive push via APNS/FCM
PushNotifications.register();
} else {
alert('No permission for push granted');
}
});
PushNotifications.addListener(
'registration',
(token: PushNotificationToken) => {
alert('APN token: ' + JSON.stringify(token));
fcm.getToken().then((r) => {
alert(`FCM Token: ${r.token}`); //---- showing null.
}).catch((err) => {
alert(`FCM Token ERROR: ${JSON.stringify(err)}`);
});
}
);
PushNotifications.addListener('registrationError', (error: any) => {
alert('Registration Error: ' + JSON.stringify(error));
});
PushNotifications.addListener(
'pushNotificationReceived',
async (notification: PushNotification) => {
Modals.alert({
title: notification.title,
message: notification.body
})
}
);
PushNotifications.addListener(
'pushNotificationActionPerformed',
async (notification: PushNotificationActionPerformed) => {
alert('Action performed: ' + JSON.stringify(notification.notification));
}
);
}
}
Is there anything I am missing or I need to add extra configurations to receive push notifications ?
You added SHA certificate fingerprints in your firebase project and update google service file ?
I use React Native FCM for messaging, and when the user logs out the application I want to delete the FCM token so that the user doesn't get Notified again.
Below is my code for logout.
_signOutAsync = async () => {
this.logoutEvent()
API.post('customer/auth/logout', null, {
headers: {
Authorization:
'Bearer ' + (await AsyncStorage.getItem(Config.ACCESS_TOKEN))
}
}).then((response) => {
console.log(response)
})
this.clearData()
}
Thanks.
Simply add below given code in your logout function -
for react-native-firebase <= v5.x.x
firebase.messaging().deleteToken()
for > 5.x.x or using #react-native-firebase/messaging
import messaging from '#react-native-firebase/messaging';
messaging().deleteToken()
await firebase.messaging().deleteToken();
is the solution.
BUT, if you get the same token even after deleting, install the npm package react-native-restart, and do the below step to get a new token
messaging()
.deleteToken(undefined,'*')
.then(() => {
RNRestart.Restart();
Install the npm package react-native-restart and Simply call like this:
const logoutAndClearAsyncStorage = async () => {
try {
await AsyncStorage.clear()
await firebase.messaging().deleteToken().then(() => {
RNRestart.Restart()
navigation.replace('LoginStack', { screen: 'WelcomeScreen' });
})
} catch (error) {
console.log(error, 'logout')
}
};
Recently I try to use FCM too, and found the issue usually due to the function comes from, i.e. where to import the functions.
I think you already have installed firebase package, call the function below will trigger delete token on firebase.
import { getMessaging, deleteToken } from 'firebase/messaging';
const messaging = getMessaging(firebaseApp);
deleteToken(messaging);
I'm trying to setup push notifications, I'm stuck here, and I have no idea where to put this code:
const cloudSettings: CloudSettings = {
'core': {
'app_id': 'APP_ID',
},
'push': {
'sender_id': 'SENDER_ID',
'pluginConfig': {
'ios': {
'badge': true,
'sound': true
},
'android': {
'iconColor': '#343434'
}
}
}
};
P.s app.modules.ts doesn't exist in my project
Ionic version: 2.1.4
Cordova: 6.4.0
Try this
http://tphangout.com/ionic-2-push-notifications/
Or you can try wiht OneSignal Push Notfications, they have great documentation...
I'm integrating FCM on my react-native application using https://github.com/evollu/react-native-fcm.
The notification works but I got this error every time.
console.error: "Notification handler err", {"line":67974,"column":14,"sourceURL":"http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false"}
Environment:
react-native-cli: 2.0.1
react-native: 0.40.0
react-native-fcm: 6.1.0
I'm testing on Android ver 6.0.1 and the app is running in foreground.
I removed old code Firebase initialisation code on index.js, and it caused the error.
firebase.initializeApp({
apiKey: "",
authDomain: "",
databaseURL: "",
storageBucket: ""
});
I removed it and it's working now.
For react-native fcm. See object aps.alert
FCM.on("FCMNotificationReceived", (notification) => {
if (Platform.OS === 'ios') {
if (notification && notification.aps) {
const localNotification = {
title: notification.aps.alert.title,
body: notification.aps.alert.body,
show_in_foreground: true,
}
FCM.presentLocalNotification(localNotification);
}
}
});
FCM.on("FCMNotificationReceived", (notification) => {
// Also trigged when FCM.presentLocalNotification() and callback a notification without **aps** object;
// So the app crash, error
// Just check if (notification && notification.aps) and make localNotification object like above code
})