In my app, i couldn't parse the "payload" object coming from push notification. There is automatically added '/' in each property in payload after push sent from server. How can i parse the payload property/object and get the notification data in my code?
Here is the payload object :
"payload":"{\"android\":{\"badge\":\"2\",\"alert\":\"Microfinaa_new_ne\",\"sound\":\"door_bell\",\"icon\":\"little_star\",\"vibrate\":true,\"title\":\"Mahboob Zaman\"}}"
And here is the full notification message coming from fcm server:
{"type":"callback","source":{"showTrayNotification":true,"pushType":"gcm","enabled":false,"showTrayNotificationsWhenFocused":false,"singleCallback":false,"focusAppOnPush":false,"showAppOnTrayClick":true,"debug":false,"apiName":"Ti.Module","bubbleParent":true,"invocationAPIs":[],"__propertiesDefined__":true,"_events":{"callback":{}}},"payload":"{\"android\":{\"badge\":\"2\",\"alert\":\"Microfinaa_new_ne\",\"sound\":\"door_bell\",\"icon\":\"little_star\",\"vibrate\":true,\"title\":\"Mahboob Zaman\"}}","bubbles":false,"cancelBubble":false}
And here is my code -
CloudPush.addEventListener('callback', function(evt) {
var json = JSON.stringify(evt.payload);
Ti.API.info("datos = " + json.android);// This line shows undefined
});
Payload is already string you need to parse it and use inverse function
var json = JSON.stringify(evt.payload);
JSON.stringify(Object) -> return String
JSON.parse(StringOject) -> return Object
Related
I'm writing VB.NET code to send notification to android Emulator. I can successfully send test message from the firebase control. However, it failed when I tried to send message via VB.NET code in my local machine and get error "The remote server returned an error: (401) Unauthorized".
I have tried looking at the following link:
FCM (Firebase Cloud Messaging) Push Notification with Asp.Net
and following the instructions but it still not working.
Here is my code:
Imports System.Net
Imports Newtonsoft.Json
Public Class Notification
Public Sub SendNotification(ByVal deviceIDList As List(Of String), ByVal title As String, ByVal bodyMsg As String)
Dim fcmPath As String = "https://fcm.googleapis.com/fcm/send"
Dim serverKey As String = "AIzaxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxoCAeI"
Dim senderID As String = "35xxxxxxx37"
Dim request As HttpWebRequest = CType(HttpWebRequest.Create(fcmPath), HttpWebRequest)
With request
.Method = "POST"
.ContentType = "application/json"
.Headers.Add(String.Format("Authorization: key={0}", serverKey))
.Headers.Add(String.Format("Sender: id={0}", senderID))
End With
Using streamWriter = New StreamWriter(request.GetRequestStream())
Dim webObject As New WebRequestFcmData
With webObject
.registration_ids = deviceIDList
.notification.title = title
.notification.body = bodyMsg
.notification.content_available = True
.notification.sound = "default"
.notification.priority = "high"
End With
Dim body = JsonConvert.SerializeObject(webObject)
With streamWriter
.Write(body)
.Flush()
.Close()
End With
End Using
Dim httpResponse = CType(request.GetResponse(), HttpWebResponse)
Using streamReader As New StreamReader(httpResponse.GetResponseStream)
Dim result = streamReader.ReadToEnd
End Using
End Sub
End Class
Public Class WebRequestFcmData
Public Property registration_ids As List(Of String)
Public Property notification As New NotificationData
End Class
Public Class NotificationData
Public Property body As String
Public Property content_available As Boolean
Public Property priority As String
Public Property title As String
Public Property sound As String
End Class
The error occurred at the line:
Dim httpResponse = CType(request.GetResponse(), HttpWebResponse)
Here is the server key and sender ID that I use:
Updated:
I tried sending web request from Postman application and it also gave the same error (401: Unauthorized) as shown in the figure below:
OK. I made a silly mistake by using API Key which is not actual Server key. Even though I have read that I should go to cloud messaging tab in project setting, I misunderstood that I have to look in cloud messaging tab in the side bar which is wrong. Here is the step where I found server key:
Click on the setting button near Project Overview
Choose the first option (Project setting)
Click on the second tab (Cloud messaging)
Use the server key and sender ID in this page
At first, I tried looking for server key in cloud messaging tab in the sidebar which is wrong location.
this question is asked before here and here but i dont get answer from there.
I'm developing application in which i'm using pubsub and xmpp, for android i'm using smack library. i want to send custom payload to the node and on receiving custom payload how to parse and display it in to list? now i am able to send and receive message but it is just a small example from documentaion. here is my example,
String msg = "room pubsub test";
SimplePayload payload = new SimplePayload("message", "pubsub:test:message", "<message xmlns='pubsub:test:message'><body>" + msg + "</body></message>");
PayloadItem<SimplePayload> item = new PayloadItem<>(null, payload);
node.publish(item);
and when i receive item
node.addItemEventListener(new ItemEventListener() {
#Override
public void handlePublishedItems(ItemPublishEvent items) {
System.out.println("======================handlePublishedItems==============================");
System.out.println(items.getItems());
}
}
and the output i'm getting is
[org.jivesoftware.smackx.pubsub.PayloadItem |
Content [<item id='5E277A9C33A58'>
<message xmlns='pubsub:test:message'>
<body xmlns='pubsub:test:message'>room pubsub test</body><
/message>
</item>]]
i want to send custom payload like the time at which message is sent, who have sent this message etc.
so, how can i send custom payload? and how to parse it and show it to user?
Send custom payload for time and sender using below code:
SimplePayload payload = new SimplePayload("message", "pubsub:test:message", "<message xmlns='pubsub:test:message'><body>" + textMessage + "</body><from>"+Sender+"</from><time>"+time+"</time></message>");
For parsing you can use XmlPullParser and parse response using Tag name
I have an Android app which calls a web service to send messages to us for support.
There is a website which we develop where we can respond to a message and we use Firebase for that. Up until now we were just sending a title and a message like so:
var applicationID = "snip";
var senderId = "snip";
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
var data = new
{
to = model.RequestFirebaseID,
notification = new
{
body = model.ResponseMessage,
title = model.ResponseTitle
}
};
In the Android app I am able to extract the message title using the following Java code
String notificationTitle = remoteMessage.getNotification().getTitle();
String notificationBody = remoteMessage.getNotification().getBody();
However now I am trying to send back a custom field called id,so I amend the code to be
var data = new
{
to = model.RequestFirebaseID,
notification = new
{
body = model.ResponseMessage,
title = model.ResponseTitle,
requestid = model.id
}
};
So now when I send a message back to the device using Firebase I have this code to try and read the id field.
String messageID = remoteMessage.getData().get("requestid");
However this causes ends up as null.
So I have tried testing sending this via the Firebase console, I add requestid to the custom data section and give it a value and the above code is able to read it.
It seems that when I am sending via the web application it cannot see the requestid field.
You have to include the data message inside the payload. Something like this:
var payload = new
{
to = model.RequestFirebaseID,
notification = new
{
body = model.ResponseMessage,
title = model.ResponseTitle
},
data = new
{
requestid = model.id
}
};
I changed the root variable name to payload to distinguish it.
If you add a custom data when using the Firebase Notifications console to send the message, it is included inside a data message parameter instead of the notification message. See the Message Types documentation for the difference of the two.
I have a problem regarding my SNS Push Notifications. I have the following lambda code:
db.scan(params, function(err, data) {
if (err) {
console.log(err); // an error occurred
}
else {
data.Items.forEach(function(record) {
var receiverID = record.userDeviceToken.S;
var message = "You have a new invitation to the event";
var topic = "Friend's invitation";
var eventText = JSON.stringify(event);
console.log("Received event:", eventText);
var sns = new AWS.SNS();
var params = {
Message: message,
Subject: "Friend's invitation",
TargetArn: receiverID,
};
sns.publish(params, function(err, data) {
if (err) {
console.log('Failed to publish SNS message');
context.fail(err);
}
else {
console.log('SNS message published successfully');
context.succeed(data);
}
});
});
//context.succeed(data.Items); // data.Items
}
});
};
Now my goal is to get the "Subject" or "topic" sometimes, if it is possible. I cannot find it in documentation, and I need it to customize my notification title depending on the push message sent (I have few functions).
When I used sample amazon app I found this cound in Push Listener Service:
public static String getMessage(Bundle data) {
// If a push notification is sent as plain text, then the message appears in "default".
// Otherwise it's in the "message" for JSON format.
return data.containsKey("default") ? data.getString("default") : data.getString(
"message", "");
}
This works, but the "data" itself has the following data:
Bundle[{google.sent_time=1480364966070, google.message_id=0:1480364966079787%22269524f9fd7ecd, default=You have a new invitation to the event, collapse_key=do_not_collapse}]
Therefore, it is just providing some internal data and the "message" itself. I cannot access the topic.
My question is: how to get other variables in the Android code so I can use them further on? Can I add custom variables by myself through data bundle?
I have notifications in JSON format. I just wonder, whether the only way is to put the data I want in JSON format inside the message, and then read the message accordingly, or maybe I can attach the required data from lambda function to the push notification already?
I am using parse for my application
I have one fragment on user which have to write article and save on parse but with not approve
when admin approve that user filed I want to send push notification automatically to that user with particular article is approved message
How can I implement this things..?
Parse.Cloud.afterSave("Data", function(request) {var dirtyKeys = request.object.dirtyKeys();for (var i = 0; i < dirtyKeys.length; ++i) {
var dirtyKey = dirtyKeys[i];
if (dirtyKey === "name") {
//Get value from Data Object
var username = request.object.get("name");
//Set push query
var pushQuery = new Parse.Query(Parse.Installation);
pushQuery.equalTo("name",username);
//Send Push message
Parse.Push.send({
where: pushQuery,
data: {
alert: "Name Updated",
sound: "default"
}
},{
success: function(){
response.success('true');
},
error: function (error) {
response.error(error);
}
});
return; } } response.success();});
If this is a matter of just hitting "approve", I would create a cloud code function for "Approve article" that is called by the admin tapping an approve button. This function sets the approve status and then calls a function (still in cloud code) for sending the push message to the user.
More on cloud code functions: https://parse.com/docs/cloudcode/guide#cloud-code-cloud-functionshttps://parse.com/docs/cloudcode/guide#cloud-code-cloud-functions
Alternatively the approve button can change status and save the document, and then an afterSave() function in cloud code can handle the push. This is less clear, though, since the afterSave() function will always be called when the record is saved, and it would need to check for status and only send push if the article has been approved.