I have an Ionic project. I can receive notifications when the app is open. But when the app is closed, notifications do not come. After sending 2-3 notifications, the application gives a closed warning. How can I receive notifications when the app is closed?
Ionic info:
Ionic:
Ionic CLI : 6.20.1 (C:\Users\xxxxx\AppData\Roaming\npm\node_modules\#ionic\cli)
Ionic Framework : #ionic/angular 6.5.0
#angular-devkit/build-angular : 13.2.6
#angular-devkit/schematics : 13.2.6
#angular/cli : 13.2.6
#ionic/angular-toolkit : 6.1.0
Cordova:
Cordova CLI : 11.0.0
Cordova Platforms : android 10.1.2
Cordova Plugins : cordova-plugin-ionic-keyboard 2.2.0, cordova-plugin-ionic-webview 5.0.0, (and 9 other plugins)
Utility:
cordova-res : 0.15.4
native-run : 1.7.1
System:
NodeJS : v18.13.0 (C:\Program Files\nodejs\node.exe)
npm : 9.3.0
OS : Windows 10
cordova-plugin-fcm-with-dependecy-updated 7.8.0 "Cordova FCM Push
Plugin"
My Code:
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
public route: Router,
public xDevice: Device,
private network: Network,
private fcm:FCM,
) {
this.initializeApp();
this.setupFCM();
}
private async setupFCM() {
this.platform.ready().then(() => {
try {
this.fcm.getInitialPushPayload().then((payload) => {
if(payload?.wasTapped) {
console.log("Received FCM when app is closed -> ", JSON.stringify(payload));
// call your function to handle the data
//this._handlePushNotificationData(payload);
}
});
this.fcm.requestPushPermission();
this.fcm.hasPermission();
this.fcm.getToken().then(token => {
console.log("Token: " + token);
console.log(token)
}).catch(error => {
console.log(error)
})
this.fcm.onNotification().subscribe(data => {
if (data.wasTapped) {
console.log('Received in background');
} else {
console.log('Received in foreground');
}
});
this.fcm.onTokenRefresh().subscribe(token => {
console.log(token)
});
} catch (error) {
console.log(error)
}
});
}
It asks for permission for notification, but when the application is closed, the notification does not come. I can't find the problem either because the app is closed. How can I solve this problem?
The issue you are facing is likely caused by the way Firebase Cloud Messaging (FCM) handles push notifications when the app is closed. FCM uses a notification tray icon to display push notifications when the app is closed. However, the notification may not appear if the user has disabled the notification tray icon for your app.
To troubleshoot this issue, you can try the following:
Ensure that you have correctly set up FCM in your app and that the correct credentials are being used.
Check if the notification tray icon is enabled for your app in the device settings.
Make sure that the FCM server key and sender ID are correctly configured in the Firebase console.
Check if the device token is being correctly retrieved and sent to the FCM server.
5.Test the notifications on different devices and see if the issue is specific to a certain device or if it's happening on all devices.
If the issue is still not resolved, you can try using a different push notification service or library that is better suited for handling push notifications when the app is closed.
Related
I am tring to do push notification on my cordova android app with Cordova plugin for Firebase Cloud Messaging plugin. I have created and registered app in Google firebase console and downloaded google-services.json file and kept it in my project root folder. Then I am trying the functions provided in the plugin documentation on device ready but did not get the device token, it is blank. My cordova android version is 9.1.0. Can someone tell me why the device token is not generated? Please help me. My js code is below:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
cordova.plugins.firebase.messaging.onMessage(function (payload) {
console.log("New foreground FCM message: ", payload);
});
cordova.plugins.firebase.messaging.onBackgroundMessage(function (payload) {
console.log("New background FCM message: ", payload);
});
cordova.plugins.firebase.messaging.requestPermission({ forceShow: true }).then(function ()
{
console.log("You'll get foreground notifications when a push message arrives");
});
cordova.plugins.firebase.messaging.getToken().then(function (token) {
alert("Got device token: ", token);
});
/*cordova.plugins.firebase.messaging.onTokenRefresh(function () {
console.log("Device token updated");
});*/
cordova.plugins.firebase.messaging.createChannel({
id: "mypushid",
name: "Push channel",
importance: 3
});
}
I created this code in my app console:
app.compontent.ts
this.firebaseX.getToken().then(token => console.log('PUSH_TOKEN: GET_TOKEN: ', token))
.catch(err => console.log(err));
if (this.platform.is('ios')) {
this.firebaseX.grantPermission().then(hasPermission => console.log(hasPermission ? 'granted' : 'denied'));
this.firebaseX.onApnsTokenReceived().subscribe(token => console.log('PUSH_TOKEN: IOS_TOKEN: ' + token));
}
this.firebaseX.onMessageReceived().subscribe(message => console.log(message));
xCode configuration:
Chrome console after sending push message via firebase console:
xCode Console when app init:
2020-01-19 17:09:22.816015+0100 myApp[8896:2663293] registerForRemoteNotifications
2020-01-19 17:09:22.816107+0100 myApp[8896:2663293] _hasPermission: YES
...
2020-01-19 17:09:22.821477+0100 myApp[8896:2663036] PUSH_TOKEN: IOS_TOKEN: d2aac51a963530-FULL_TOKEN_HERE
2020-01-19 17:09:22.821807+0100 myApp[8896:2663036] PUSH_TOKEN: GET_TOKEN: frWxHosY-gQ:APA91bEk3-FULL_TOKEN_HERE
...
2020-01-19 17:13:46.395935+0100 myApp[8896:2663036] FCM direct channel = true
2020-01-19 17:15:39.418759+0100 myApp[8896:2663036] FCM direct channel = false
I'm running my app in debug env.
Current behavior:
Android:
Getting push messages only when app working is closed (im not using app) - it is possible to get push when app is running?
iOS:
Only getting APNS token, push will not showing. I checked double Settings -> notifications -> myApp Name -> everything is enabled. In Firebase console im using both tokens (from IOS_TOKEN and GET_TOKEN) both not working.
iOS: 13.3 (17C54)
xCode: 11.3 (11C29)
"cordova-plugin-firebasex": "^7.0.1"
What should i do to start receiving pushes on iOS?
I solved my problem.
I forgot to upload my .p8 key to firebase.
https://firebase.google.com/docs/cloud-messaging/ios/certs
Lesson learnt: always read documentation :)
I have a problem with Ionic storage in my Ionic App for Windows (UWP app). I already tested and deployed my app for Android without any trouble.
Now I would like to generate an UWP app.
The app I’m developing is a workshop’s dashboard. The indicators change every day and I need to save them from one day to another. To do this I usethe storage module of Ionic.
When launching the command
$ionic serve
the app responds exactly as it should in the web browser (Firefox). From one launch to another my data are still there.
When I use
$ionic cordova run windows
the installation and launch steps of my app work fine. Every function of my app runs fine, but the call to storage (get and set) doesn’t work : when I close, and then reopen it as an autonomous application, I loose all data every time. It is the same when I run the app from Visual Studio.
Moreover, I write some console.log in the result of the promise and none of them is written in the Javascript console. It is like Windows does not recognize the command.
I tried with Visual Studio 2015 Update 3 and Visual Studio 2017, the result is identical. I followed the recommendation of Ionic Doc and add the target platform windows10 in the config.xml.
Does anyone have an idea of what I’m doing wrong ? Is there an incompatibility between Windows and Ionic ?
Thanks for any help.
Config :
Windows 10 64-bits
Ionic CLI: 3.19.1
Cordova CLI : 8.0.0
Node : v6.11.2
Visual Studio Community 2017 (15.5.27130.2036)
Extract of my code maPage.ts :
import { Storage } from '#ionic/storage';
export class maPage {
constructor(public storage: Storage) {
this.downloadData();
}
ionViewWillLeave()
{
this.saveData();
}
TabData = {
id: 0,
label: '',
Tab1: [],
Tab2: [],
attri1 : 0,
attri2: false
}
Param = {
Objet1: {NbObj1: 7},
Objet2: {NbObj2: 5}
}
saveData()
{
var Data: object;
Data =
{
TData: this.TabData,
TParam: this.Param
}
this.storage.set('Data', Data).then(_=> {
console.log('Backup done!');
}, error => {
console.log('erreur : ', JSON.stringify(error))
});
}
downloadData()
{
this.storage.ready().then(()=>{
console.log('storage ready');
this.storage.get('Data').then((val) => {
this.TabData = val.TData;
this.Param = val.TParam;
console.log('Récupération terminée !');
}).catch(erreur => {
console.log('La variable Data est vide ou n\'existe pas!');
console.log('erreur : ', JSON.stringify(erreur));
}).catch(err => {
console.log('storage not ready');
console.log('err : ', JSON.stringify(err));
});
}
}
On Windows platform, console.log is not supported. To do that, you should install cordova-plugin-console, or need to use alert function.
Regarding storage, I am suggesting you could use localstorage or cordova-sqlite-storage.
I took the sample Cordova project and added platform for Android environment then I created FCM project through Google console and then I got the sender id and server key. I added the MobileFirst server console credentials. Once I did the above steps I added the scope variable in the MobileFirst console "push.mobileclient". Finally I try to run my project using Android studio on an Android emulator.
The testing of the push notification failed while I clicked register device. Below are the error logs:
Failed to register device:"com.ibm.mobilefirstplatform.clientsdk.android.push.api.MFPPushException: Response: Status=400, Text: {\"errorCode\":\"invalid_client\",\"errorMsg\":\"Incorrect JWT format\"}, Error Message: Incorrect JWT format"
Kindly help me to resolve the issue.
Add these plugin in cordova project
cordova plugin add cordova-plugin-mfp
cordova plugin add cordova-plugin-mfp-push
Try to create fresh project in Firebase Console and add Server key & Sender ID in Mobilefirst console carefully.
Run in real device. Also use same network(wifi) in both Mobile and computer.
You can try without scope variable "push.mobileclient" in the MobileFirst console and try sample code:
sample code
function wlCommonInit(){
//initialize app for push notification
MFPPush.initialize (
function(successResponse) {
alert("Push Notification Successfully intialized");
MFPPush.registerNotificationsCallback(notificationReceived);
},
function(failureResponse) {
alert("Failed to initialize");
}
);
//Check device is Supported for push notification
MFPPush.isPushSupported (
function(successResponse) {
alert("Device is Push Supported");
},
function(failureResponse) {
alert("Failed to get push support status");
}
);
//register app for push notification
MFPPush.registerDevice( null,
function(successResponse) {
alert("Device Successfully registered");
},
function(failureResponse) {
alert("Failed to register");
}
);
var notificationReceived = function(message) {
alert(JSON.stringify(message));
};
}
Check here: Not able to send push notification to iOS devices through MFP Server V8 Console
I'm new in ionic framework, developing one simple app using ionic framework. Implementing push notification,
am following below link
https://devdactic.com/android-push-notifications/
went up to final step:
$ionicPlatform.ready(function() {
var io = Ionic.io();
var push = new Ionic.Push({
"onNotification": function(notification) {
alert('Received push notification!');
},
"pluginConfig": {
"android": {
"iconColor": "#0000FF"
}
}
});
var user = Ionic.User.current();
if (!user.id) {
user.id = Ionic.User.anonymousId();
}
// Just add some dummy data..
user.set('name', 'Simon');
user.set('bio', 'This is my little bio');
user.save();
var callback = function(data) {
push.addTokenToUser(user);
user.save();
};
push.register(callback);
});
After this run the below commend
ionic serve -w safari
getting the below error in console ( check last line)
Ionic Core: init
ionic.io.bundle.min.js:2Ionic Core: searching for cordova.js
ionic.io.bundle.min.js:2Ionic Core: attempting to mock plugins
app.js:26TypeError: 'undefined' is not a function (evaluating 'Ionic.User.anonymousId()')
if i run "ionic info" getting following lines
Your system information:
Cordova CLI: 6.1.0 (cordova-lib#undefined)
Ionic Version: 1.2.4
Ionic CLI Version: 1.7.14
Ionic App Lib Version: 0.7.0
OS: Windows 7 SP1
Node Version: v5.0.0
Dependency warning - for the CLI to run correctly,
it is highly suggested to install/upgrade the following:
Please install your Cordova CLI to version >=4.2.0 npm install -g cordova
The Ionic Platform has now moved to Beta status. Part of this change is the introduction of the Platform API and User authentication. We've deprecated the alpha API for the Users and Push services and will be removing them entirely in the coming months.
Users now require Authentication, so Ionic.User.anonymousId(); is not available.
Have a look at Migrations and user usage.