I have implemented an android app using ionic. i want to implement push notification with some action like accept and reject.
I used phonegap pluginpush for push notification.
But when i clicked on them nothing happens.
sent notification
POST /push/notifications HTTP/1.1
Host: api.ionic.io
Content-Type: application/json
Authorization: Bearer xxxxxxxxxxxxxx
{
"tokens": ["token1","token2"],
"profile": "profile",
"notification": {
"title": "data updated ",
"message":"allow sync immediatly",
"android": {
"data": {
"image": "www/img/icon.png",
"vibrationPattern": [100, 1000, 500, 500],
"notId": 121,
"actions": [
{ "title": "Approve ", "callback": "accept", "foreground": true},
{ "title": "Reject", "callback": "reject", "foreground": true}
]
}
}
}
}
javascript
angular.module('app')
.factory("notificationService", function ($http, $q, $ionicPlatform, baseUrl, $ionicPush, $localStorage, USER) {
window.approve = function(data){ alert("Approve Triggered"); }
window.reject = function(data){ alert("Reject Triggred"); }
var notification = function () {
$ionicPlatform.ready(function () {
$ionicPush.init({
"debug": true,
"onNotification": function (notification) {
alert("notification received");
var payload = notification.payload;
},
"onRegister": function (data) {
saveGcmToken(USER.parentId(), data);
},
"pluginConfig": {
"android": {
"badge": true,
"sound": true,
"alert": true,
"icon": "icon",
'forceShow' : true,
//"iconColor": "#948438"
},
"ios": {
"badge": true,
"sound": true,
"forceShow" : true,
"alert": true
}
}
});
$ionicPush.register({
canShowAlert: true,
canSetBadge: true,
canPlaySound: true,
canRunActionsOnWake: true,
});
});
}
function saveGcmToken(parentId, token) {
var data = {};
angular.extend(data, {
id: parentId,
name: token._token
});
$http({
method: 'PUT',
contentType: 'application/json',
data: data,
url: baseUrl + "/add-app-token"
}).success(function (response) {
alert("response from notification service" + JSON.stringify(response));
}).error(function (response) {
alert("Error " + JSON.stringify(response));
});
}
return {
notification: notification
}
})
try this update your alert function.
"onNotification": function (notification) {
alert('message = '+notification.message+' title = '+notification.title + ' actions = '+notification.android.data.actions+ ' notId = '+notification.android.data.notId);
}
For details visit : http://devgirl.org/2013/07/17/tutorial-implement-push-notifications-in-your-phonegap-application/
https://www.npmjs.com/package/phonegap-plugin-push-pgb
Related
I have written this code with nodejs to send a push notification from a nodejs server to a specific user of a mobile application:
const { admin } = require("../config/Firebase");
const sendNotification = async (req, res) => {
const requestBody = req?.body;
const registrationToken = requestBody?.registrationToken; // get it from mobile app
const data = {
message: {
token: registrationToken,
notification: {
title: "Notification Title",
body: "Notification Body ",
description: "Notification description",
},
android: {
notification: {
imageUrl: "https://foo.bar.pizza-monster.png",
},
},
apns: {
payload: {
aps: {
"mutable-content": 1,
},
},
fcm_options: {
image: "https://foo.bar.pizza-monster.png",
},
},
webpush: {
headers: {
image: "https://foo.bar.pizza-monster.png",
},
},
data: {
Nick: "Mario",
Room: "PortugalVSDenmark",
},
},
};
try {
admin.messaging().send(data.message);
res.status(200).json({ notificationStatus: "success" });
} catch (error) {
console.log("Error while sending notification: ", error);
res.status(500).json({ notificationStatus: "failed" });
}
};
But it works only for android devices. So i would like to know if there a config or something like that which makes the server sends it to both iOS and android devices ?
hi I have one endpoint which is pass multipart formdata
URL : http://100.20.168.179/public/index.php/maintenances/create_ticket
Method: Post
Body request
const SelectData = {
"description": "Fff",
"room_id": "Ghh",
"maintenance_unique_id": "1662630778728",
"lang_flag": "en",
"asset_type": "2",
"longitude": "0.0",
"work_type": "69",
"user_id": "20",
"latitude": "0.0",
"area": "291",
"location": "22",
"urgency_level": "4",
"category_name": "",
"device_id": "2",
"captured_adress": "3377",
"reported_on": "2022-09-08 03:22:58",
"is_mediafile": "0"
}
My code as below
const form = new FormData();
const imageFileData = {
name: imageFilePath?.fileName,
type: `image/jpg`,
uri: imageFilePath?.uri,
};
form.append('webdata', JSON.stringify(SelectData));
if (imageFilePath?.uri || videoFilePath?.uri ) {
form.append('file_name', imageFileData );
}
else{
form.append('file_name', JSON.stringify(null));
}
addTicket(Config.BASE_URL + '/maintenances/create_ticket',form);
useAddTicket.ts
const useAddTicket = () => {
// const [data, setData] = useState();
const [isLoading, setIsLoading] = useState(false);
const navigation = useNavigation();
const addTicket = async (url: string, data: any) => {
console.log('formDatain Hook', data);
console.log('url Hook', url);
console.log('internet', globals.GlobalVariable.isConnected);
if (globals.GlobalVariable.isConnected === true) {
try {
setIsLoading(true);
const headers = {
'Content-Type': 'multipart/form-data; boundary=V2ymHFg03ehbqgZCaKO6jy',
// Connection: 'keep-alive',
// 'Content-Disposition': 'form-data; name="webdata"',
};
const response = await axios.post(url, data, { headers: headers });
if (response.data.sStatus == 1) {
setIsLoading(false)
console.log('useAddTicket Data res -->', response);
Alert.alert(`${response.data.sData.maintenance_id}`, response.data.sMessage, [
{ text: 'OK', onPress: () => navigation.goBack() },
]);
}
} catch (error) {
console.log('useAddTicket error -->', error);
setIsLoading(false);
}
} else {
Alert.alert('No Internet!');
}
};
return {
isLoading,
// data,
addTicket,
};
};
export default useAddTicket;
Issue is Above code working in iOS emulator but in Android it is not working in emulator as well as Real device . When i try to run in android it is continuously loading API call is not happened so any idea how can I solve this ? Your all suggestions is appreciated
NOTE: I mage getting log till internet true inside addTicket function. It means my request is not reach to Endpoint
Try as below:
const oFormData = new FormData();
oFormData.append("image", {
uri: val.uri,
type: val.type,
name: val.fileName
});
return axios.post(postUrl, oFormData);
How can I leave a push message unread, even if the app is foreground?
I am creating an application using ionic. I use push notifications using firebase cloud messaging (cordova-plugin-fcm-with-dependecy-updated) to subscribe to messages, and backend for sending.
Example backend request:
{
"headers": {
"Authorization": "key = blahblah",
"Content-Type": "application / json",
"project_id": "111111111111"
},
"json": {
"registration_ids": [
"token"
],
"time_to_live": 1200,
"data": {
"title": "title",
"body": "body",
"sound": "default",
"badge": 1,
"click_action": "FCM_PLUGIN_ACTIVITY"
}
}
}
I also tried to send the notification key instead of the date key. Tried to add to root
{
...
"android": {
"ttl": "1200s",
"priority": "high",
"notification": {
"click_action": "FCM_PLUGIN_ACTIVITY"
}
},
...
"apns":{
"headers":{
"apns-priority":10,
"apns-expiration": date('U') + 1200
},
"payload":{
"aps":{
"badge":1,
"category":"FCM_PLUGIN_ACTIVITY"
}
}
}
}
The result is the same - when the application is in the background, the push is not displayed in the tray.
How can I leave push unread, if app in foreground, and call my actions at this.fcm.onNotification().subscribe(...) only on user's click?
p.s. I tried to use cordova-plugin-local-notification, but using this caused some conflict - subscribe action doesn't fire in ios
I use ionic and cordova in my app.
I am using the plugin [cordova-plugin-firebasex] (https://github.com/dpa99c/cordova-plugin-firebasex) to receive push.
To send the push, use the following json:
{
"registration_ids": [
"token"
],
"notification":{
"title":"Ionic 4 Notification",
"body":"Notification sent from POSTMAN",
"sound":"default",
"click_action":"FCM_PLUGIN_ACTIVITY",
"icon":"notification_icon"
},
"data":{
"email":"teste#gmail.com"
},
"priority":"high"
}
For android, the "notification" field that displays a notification when the application is in the background.
If you are in foreground, you have to display a notification yourself using the plugin [cordova-plugin-local-notifications] (https://github.com/katzer/cordova-plugin-local-notifications)
My code:
constructor(private firebaseCordova: FirebaseX) {}
private initializePushApp() {
this.checkNotificationPermission(false);
this.onMessageApp();
}
checkNotificationPermission(requested) {
try {
this.firebaseCordova.hasPermission().then(hasPermission => {
if (hasPermission) {
this.getTokenApp();
} else if (!requested) {
this.firebaseCordova.grantPermission().then(value => {
this.checkNotificationPermission(true);
});
} else {
// Denied
console.log("Notifications won't be shown as permission is denied");
}
});
} catch (e) {
console.error(e);
}
}
onMessageApp() {
try {
this.firebaseCordova.onMessageReceived().subscribe(data => {
this.showNotificationCordova(data);
});
} catch (e) {
console.error(e);
}
}
showNotificationCordova(notification) {
if ('background' === notification.tap) {
// click on notification in background
alert(notification.title);
} else {
this.clickNotificationSub = this.localNotifications.on('click').subscribe(data => {
// click on notification in foreground
alert(notification.title);
});
this.localNotifications.hasPermission().then(permission => {
if (permission) {
this.localNotifications.schedule({
id: 1,
title: notification.title,
text: notification.body,
icon: notification.image ? notification.image : 'notification_icon',
});
} else {
this.localNotifications.requestPermission().then(value => {
if (value) {
this.localNotifications.schedule({
id: 1,
title: notification.title,
text: notification.body,
icon: notification.image ? notification.image : 'notification_icon',
});
} else {
console.log("Notifications won't be shown as permission is denied");
}
});
}
});
}
}
When you enter this condition 'background' === notification.tap` the notification was clicked in the background
I'm using firebase cloud function for send push notification. It works but issue by default it shows badge and does not play sound when notification comes.
Below is my playload code.
var playload = {
notification: {
title: msgData.title,
body: msgData.message,
sound: 'default',
badge: '0',
click_action: 'FLUTTER_NOTIFICATION_CLICK'
},
data: {
title: msgData.title,
body: msgData.message,
sound: 'default',
badge: '0',
click_action: 'FLUTTER_NOTIFICATION_CLICK'
}
}
var options = {
priority: "high",
timeToLive: 60 * 60 * 24
};
return admin.messaging().sendToDevice(tokens, playload, options).then((response) => {
console.log('Sent to all the devices');
return response;
}).catch((err) => {
console.log(err);
return 0;
})
I have set 'sound': 'default' and badge: '0' but doesn't help me.
UPDATED:
I have tried with double quote for both keys and values but didn't work yet.
var playload = {
"notification": {
"title": msgData.title,
"body": msgData.message,
"sound": "default",
"badge": "0",
"click_action": "FLUTTER_NOTIFICATION_CLICK"
},
"data": {
"title": msgData.title,
"body": msgData.message,
"sound": "default",
"badge": "0",
"click_action": "FLUTTER_NOTIFICATION_CLICK"
}
}
Have you tried to replace your single quotes with double quotes?
From JSON.org:
A value can be a string in double quotes, or a number, or true or
false or null, or an object or an array. These structures can be
nested.
The title and the body of your message is processed before it eventually will fail which might be why it seems that your formatting is okay.
Let me know whether this has helped you.
I'm trying to trigger onNotification event if app is running in the background.
I tried to do it by this way:
$ionicPush.init({
"canShowAlert": true, //Can pushes show an alert on your screen?
"canSetBadge": true, //Can pushes update app icon badges?
"canPlaySound": true, //Can notifications play a sound?
"canRunActionsOnWake": true, //Can run actions outside the app,
"debug": true,
"onNotification": function (notification) {
console.log("onNotification");
var payload = notification.payload;
console.log(notification);
var title = "SmartCam mobile";
var message = $translate.instant('Cam') + " : " + $translate.instant(payload.eventType) + " " + $translate.instant("registered at") + " " + payload.time;
notificationService.showNotification(title, message, payload);
},
"onRegister": function (data) {
console.log("onRegister");
console.log(data.token);
localStorageService.set("STORED_VALUES_PUSH_TOKEN", data.token);
localStorageService.set("STORED_VALUES_PLATFORM", ionic.Platform.platform().toLowerCase());
}
});
A used attribute content_available: 1 in push request too:
curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer xyz" -d '
{
"tokens": ["abc"],
"profile": "smartcam",
"notification": {
"title": "Push sssTitle",
"message": "Push sotification body",
"content_available": 1,
"payload": {
"baz": "boo"
},
"android": {
"title": "Hey",
"message": "Hello Android!",
"content_available": 1,
"payload": {
"baz": "boo"
}
},
"ios": {
"title": "Howdy",
"message": "Hello iOS!",
"content_available": 1,
"payload": {
"baz": "boo"
}
}
}
}' "https://api.ionic.io/push/notifications"
But without the luck.
How can i trigger this event if app is running in the background?
Many thanks for any advice.
I found that I had to remove the "title" attribute from the "android" and "ios".
Also, you'll need to make sure you have ran this on your ionic project:
ionic config set dev_push false