How to intercept AWS SNS messages to iOs mobile endpoints in Xamarin? - amazon-web-services

The documentation on AWS -SNS for use of SNS within Xamarin iOS projects shows how to register an iOS device to receive messages from SNS, but not clear how to intercept those messages within the application and programtically respond to the message. How do I capture the incoming message, and process appropriately rather than just showing the text of the message received? Is this done by sending a different message than is shown in the AWS console, and where can I intercept it in my application?
This is the example I've been following:
public override bool FinishedLaunching(UIApplication app, NSDictionary options) {
// do something
var pushSettings = UIUserNotificationSettings.GetSettingsForTypes (
UIUserNotificationType.Alert |
UIUserNotificationType.Badge |
UIUserNotificationType.Sound,
null
);
app.RegisterUserNotifications(pushSettings);
app.RegisterForRemoteNotifications();
// do something
return true;
}
public override void RegisteredForRemoteNotifications(UIApplication application, NSData token) {
var deviceToken = token.Description.Replace("<", "").Replace(">", "").Replace(" ", "");
if (!string.IsNullOrEmpty(deviceToken)) {
//register with SNS to create an endpoint ARN
var response = await SnsClient.CreatePlatformEndpointAsync(
new CreatePlatformEndpointRequest {
Token = deviceToken,
PlatformApplicationArn = "YourPlatformArn" /* insert your platform application ARN here */
});
}
}
Here is the message I'm sending:
{
"APNS_SANDBOX":"{\"aps\":{\"alert\":\"This is my message\"}}"
}
This seems to work fine for displaying a text message sent from the AWS console, whether the app is running or not, but that's not what I need for my app. (e.g. a chess app, where the SNS messages are used to exchange moves made by a pair of users and the app displays them.)
The FinishedLaunching method contains several not altogether helpful "do something" , but I can't figure out how to, say call some method in my PCL when a particular message is received and pass the content of the message to that method.

You can subscribe the DidReceiveRemoteNotification() event in AppDelegate.cs to get your content you sent on SNS.
public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
{
// retrieve something from a server somewhere
}
This event will trigger when user taps the notification to open the app and when this app is on background state or foreground state.
If this app is closed this event will not trigger, but we can also get the content in public override bool FinishedLaunching(UIApplication app, NSDictionary options) with the parameter options.
Moreover if you want to get it in PCL, we can make a MessagingCenter to achieve this:
Send content on native platform:
MessagingCenter.Send<object, NSDictionary>(this, "Notification", userInfo);
Then receive this MessagingCenter on PCL somewhere you like:
MessagingCenter.Subscribe<object, NSDictionary>(this, "Notification", (sender, dic) =>
{
});

Related

How to change settings to receive Notifications in background state from within Expo app?

I am receiving push notifications via expo-notification. I created a button within the app that allows you to set whether or not to receive notifications.
This app is made to not receive notifications while in the foreground state. I would like to implement a notification so that when that button is in the ON state, notifications can be received in the Background state, and in the OFF state, notifications cannot be received in the Background state.
const BACKGROUND_NOTIFICATION_TASK = "BACKGROUND-NOTIFICATION-TASK";
TaskManager.defineTask(BACKGROUND_NOTIFICATION_TASK, ({ data, error, executionInfo }) => {
if (error) {
console.log("error occurred");
}
if (data) {
console.log("data-----", data);
}
});
Notifications.registerTaskAsync(BACKGROUND_NOTIFICATION_TASK);
The above function is a function set for background reception.
I tried unregisterTaskAsync when the button is in OFF state and I still receive the notification in the background. What method should I use to implement changing notification settings in-app?

Is it possible to make AWS Websocket + Lambda function to constant monitoring of the DynamoDB and send response to the client?

I have a serverless project: AWS + Angular on the frontend. Currently, I get the data when page is initialized and refresh the data when press "update" button. However, I want to monitor changes in the table constantly. In Firebase there is onSnapShot() method, which sends the new data when a collection is updated.
I want to make something similar with AWS. However, in official documentation, I do not see how to correctly do it.
So here are 2 questions:
How can I connect to the WebSocket with aws-sdk? (Currently, I can connect only from the terminal with wscat -c myurl call. Or shall I simply send http.Post with websocket url?
is it possible to pass invoke in the callback URL? - I want to get data from DynamoDB when page initialize and then invoke it again and again (with a callback URL)
My Lambda function looks like this:
exports.handler = async (event, context) => {
let params = {
TableName: "documents"
}
let respond = await db.scan(params).promise();
return respond;
};
On the front-end I have:
ngOnInit(): void {
AWS.config.credentials = new AWS.Credentials({
accessKeyId: '//mykey', secretAccessKey: '//mysecretkey'
})
AWS.config.update({
region:'//myregion'
})
this.updateTable() // triggers post request to APi Gateway => lambda and receives a response with data.
}
From my understanding, you will need to set up a DynamoDB stream and a lambda function that respond to the database CRUD events, send the updated data to the WebSocket connection if the event data matches the criteria (document id for example), through AWS.ApiGatewayManagementApi. (FYI: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/ApiGatewayManagementApi.html)

Has anyone built an integration with any SMS Receivers?

I want to be able to send a text message to some number and then (upon receiving the text) basically just send a post request off to a different service after receiving the text. Does anyone know of a service I could use to set this up? Would like for it to be as fast as possible
Here's a summary of the steps to setup a sample app:
Navigate to Amazon SNS Service → Topics
Enter Name and create a new Topic
For the newly created topic, create a subscription where the Protocol is AWS Lambda (see image1 below)
Navigate to Amazon Pinpoint Service, create new Pinpoint application
Enable SMS & voice feature for this Pinpoint application
Get a new Long Code (long code price is $1/month)
For the long code, Enable two-way SMS, select the Choose an existing SNS topic option and select the SNS topic created in Step 2 above (see image2 below)
Finally, now you can send a message to that phone number from your phone and it will trigger your lambda function. In your lambda function, you can send a POST request to a different service or do whatever else. You can also respond back to the user's message - see example below.
Here's an example of how to send a message using Amazon Pinpoint in Java:
public void sendSMS(String pinpointPhoneNumber, String userPhoneNumber, String messageContent) {
// define who the message is going to and via what platform
Map<String, AddressConfiguration> addressMap = new HashMap<>();
addressMap.put(userPhoneNumber, new AddressConfiguration().withChannelType(ChannelType.SMS));
SMSMessage smsMessage = new SMSMessage();
smsMessage.setOriginationNumber(pinpointPhoneNumber);
smsMessage.setMessageType(MessageType.TRANSACTIONAL);
smsMessage.setBody(messageContent);
// add sms message to the direct message config
// this can have many other types of messages
DirectMessageConfiguration directMessageConfiguration = new DirectMessageConfiguration()
.withSMSMessage(smsMessage);
// put the phone numbers and all messages in here
MessageRequest messageRequest = new MessageRequest()
.withAddresses(addressMap)
.withMessageConfiguration(directMessageConfiguration);
// create send request
SendMessagesRequest sendMessagesRequest = new SendMessagesRequest()
.withApplicationId("put-pinpoint-app-id-here")
.withMessageRequest(messageRequest);
// send the message
AmazonPinpoint pinpointClient = AmazonPinpointClientBuilder.standard().build();
SendMessagesResult sendMessagesResult = pinpointClient.sendMessages(sendMessagesRequest);
MessageResponse messageResponse = sendMessagesResult.getMessageResponse();
}

How to send Firebase Cloud Message with AWS SNS? [duplicate]

I am using AWS resources for my android project, I am planning to add push notification service for my project with AWS SNS.there are few questions bothering me much. I did not find any questions regarding these, except one or two but with unclear explanations.
1.Does AWS support FCM? SNS work with GCM. But Google recommends to use FCM instead of GCM. I did not find AWS supporting FCM.
2.Do AWS store messages (or data) into their databases even after sending push notifications?
3.I tried putting FCM api key in SNS application platform, it is showing invalid parameters why?
FCM is backwards compatible with GCM. The steps for setting up FCM on AWS are identical to the GCM set up procedure and (at least for the moment) FCM works transparently with GCM and SNS with respect to server-side configuration.
However, if you are sending data payloads to the Android device they will not be processed unless you implement a client side service that extends FirebaseMessagingService. The default JSON message generator in the AWS console sends data messages, which will be ignored by your app unless the aforementioned service is implemented. To get around this for initial testing you can provide a custom notification payload which will be received by your device (as long as your app is not in the foreground)
There are GCM-FCM migration instructions provided by Google however the changes you need to make are predominantly on the App side.
The steps you need to follow to test GCM/FCM on your app with SNS are:
Create a Platform Application in SNS, selecting Google Cloud Messaging (GCM) as the Push Notification Platform, and providing your Server API key in the API key field.
Select the Platform Application and click the Create platform endpoint button.
Provide the InstanceID (Device Token) generated by your app. You must extend the FirebaseInstanceIDService and override the onTokenRefresh method to see this within your Android App. Once you have done this, uninstall and reinstall your app and your token should be printed to the Debug console in Android Studio on first boot.
Click the Add endpoint button.
Click on the ARN link for your platform application.
Select the newly created Endpoint for your device and click the Publish to endpoint button.
Select the JSON Message Format, and click the JSON message generator button.
Enter a test message and click the Generate JSON button
Now comes the "gotcha part".
The message that is generated by SNS will be of the form:
{
"GCM": "{ \"data\": { \"message\": \"test message\" } }"
}
As we mentioned earlier, data payloads will be ignored if no service to receive them has been implemented. We would like to test without writing too much code, so instead we should send a notification payload. To do this, simply change the JSON message to read:
{
"GCM": "{ \"notification\": { \"title\": \"test title\", \"body\": \"test body\" } }"
}
(For more information about the JSON format of an FCM message, see the FCM documentation.)
Once you have done this, make sure your app is not running on the device, and hit the Publish Message button. You should now see a notification pop up on your device.
You can of course do all this programmatically through the Amazon SNS API, however all the examples seem to use the data payload so you need to keep that in mind and generate a payload appropriate to your use case.
Now you can go to your firebase console (https://console.firebase.google.com/) select your project, click the gear icon and choose project settings, then click on the cloud messaging tab...
You'll see the legacy Server Key which is the GCM API Key and you'll have the option to generate new Server Keys which are the FCM versions
SNS will accept both versions but their menu option is still categorizing it under GCM
Here is picture for your reference:
Note that you can "accidentally" remove your Server Keys but the Legacy server key is not deletable. Also, if you click the add server key button, you'll get a new server key BELOW the first one, WITH NO WARNING! ...Nice job Google ;)
One more additional note to Nathan Dunn's great answer.
How to send data with the notification from SNS to Firebase.
We need to add data to the Json (inside the notification):
{
"default": “any value",
"GCM": "{ \"notification\": { \"body\": \”message body\”, \”title\”: \”message title \”, \"sound\":\"default\" } , \"data\" : {\”key\" : \”value\", \”key2\" : \”value\” } }”
}
In your FirebaseMessagingService implementation (Xamarin example)
public override void OnMessageReceived(RemoteMessage message)
{
try
{
var body = message?.GetNotification()?.Body;
var title = message?.GetNotification()?.Title;
var tag = message?.GetNotification()?.Tag;
var sound = message?.GetNotification()?.Sound;
var data = message?.Data
foreach (string key in data.Keys)
{
// get your data values here
}
}
catch (Exception e)
{
}
}
I tried to use solution with notification payload instead of data, but I did not receive push notifications on the mobile device. I found this tutorial https://youtu.be/iBTFLu30dSg with English subtitles of how to use FCM with AWS SNS step by step and example of how to send push notifications from AWS console and implement it on php with aws php sdk. It helped me a lot.
Just an additional note to Nathan Dunn's Answer: to add sound use the following JSON message
{
"GCM": "{ \"notification\": { \"text\": \"test message\",\"sound\":\"default\" } }"
}
It took me a while to figure out how to send the notification with the right payload (publish to topic). So I will put it here.
private void PublishToTopic(string topicArn)
{
AmazonSimpleNotificationServiceClient snsClient =
new AmazonSimpleNotificationServiceClient(Amazon.RegionEndpoint.EUWest1);
PublishRequest publishRequest = new PublishRequest();
publishRequest.TopicArn = topicArn;
publishRequest.MessageStructure = "json";
string payload = "\\\"data\\\":{\\\"text\\\":\\\"Test \\\"}";
publishRequest.Message = "{\"default\": \"default\",\"GCM\":\"{" + payload + "}\"}";
PublishResponse publishResult = snsClient.Publish(publishRequest);
}
Amazon does support FCM as all previous code has been migrated from GCM to FCM. Below article explains in detail.
Article Published by Amazon
To answer the questions:
AWS SNS does support FCM.
No AWS does not store messages after sending push notifications.
For a detailed tutorial on setting up FCM with SNS please read this article.

Amazon SNS console to push raw notification to WNS

I am testing out using AWS SNS to send push notifications to my windows app via SNS. I have done the work configuring the application and my endpoint. However, I am unable to figure out how to send a raw notification to my app. The JSON to create a badge update seems to work:
{
"WNS" : "<badge version\"1\" value\"23\"/>"
}
However, whenever I use the Raw message format, it seems to wrap the message I created and instead sends a toast message with the contents I entered. Is there any way in the console to send a pure Raw notification?
I.E. in the Raw message area I enter: 'test123', it sends a Toast notification with the following xml.
<toast><visual version="1"><binding template="ToastText01"><text id="1">test123</text></binding></visual></toast>