Push Notification in Xamarin using AWS SNS - xamarin

I provide various rental space, and my app provides the feature to rent this space to people. Let's say a user with higher priority/ memebrship in my app trying to book a space that is being used up by lower priority user. As soon as the higher priority user press the book button I want a notification to pop up in the lower priority users mobile.
My app is build using Xamarin Forms. And I want to push notification using AWS SNS, but as I see SNS requires device token to send the notification. I am planning to store the device token in the database for ever user, but I am not entirely sure how to get device token depending upon both IOS and Android environment. I am thinking of using a dependency interface that
public interface INotificationService
{
Task<string> GetDeviceToken();
}
And I have not find a good source which I can use to get device token.
Can anyone help me, and correct me if it is correct to save device token in database?

I am working on this right at this moment. This is for iOS only and what's working for me.
Put this into your AppDelegate.
public async override void RegisteredForRemoteNotifications(UIApplication application, NSData token)
{
if (application.IsRegisteredForRemoteNotifications == true)
{
var snsClient = new AmazonSimpleNotificationServiceClient("your aws key id", "your aws secret key", Amazon.RegionEndpoint.YourRegion);
/* In the AWS SNS example here - https://docs.aws.amazon.com/mobile/sdkforxamarin/developerguide/getting-started-sns-ios.html
token.Description is used, for me the line below triggers an exception, so I used token.DebugDescription instead.
*/
var deviceToken = token.DebugDescription.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 = "your aws platform application arn"
});
}
}
}
As for storing it in a database, I haven't got that far, but I am think of using DynamoDb for my specific purpose.
When/if I have Android working, I will update my answer.

Related

Azure NotificationHubs how do I get the devicetoken from an iPhone

I am using Azure NotificationsHubs for iOS push notifications and want to get the deviceToken to register the device, along with the user, in a table through an api so I can send notifications to specific users/devices and keep track of badge counts. When not using Azure Notification Hubs.
func application(
_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data
) {
print("DeviceToken: \(deviceToken)")
}
I see the documentation says:
By default, the SDK will swizzle methods to automatically intercept
calls to UIApplicationDelegate/NSApplicationDelegate for calls to
registering and intercepting push notifications, as well as
UNUserNotificationCenterDelegate methods. Note this is only available
for iOS, watchOS, and Mac Catalyst. This is not supported on macOS and
tvOS.
I'm not sure what swizzling means but I don't want to disable what I have working thus far. Is there another way within the standard implementation to get the deviceToken?
I also see this in the documentation:
To target a particular user on the backend, you can specify a tag such as $UserId:{VALUE} where VALUE is the user name you have specified, just as you can target an installation using the $InstallationId:{VALUE} tag.
But how do I get the InstallationId and is that different from the deviceId or value I use in xcrun simctl push? I expect somewhere I will need to store it on the server side and associate it with a user or something.
I read this post which states:
When you send a notification from the server, one of the paramters is the device ID.
I could do it by user only, but what if they want different notification preference for different devices?
I expect to send to a specific user on a specific device from the server you would use tags, for example:
Microsoft.Azure.NotificationHubs.NotificationOutcome outcome = null;
String userTag = "(UserId:xxxx)";
// substituting for iOS
var toast = "{\"aps\":{\"alert\":\"This is a test\"}}";
outcome = await Notifications.Instance.Hub.SendWindowsNativeNotificationAsync(toast, userTag);
On the client, I am setting the user id like this:
let userId = "xxxx"
MSNotificationHub.setUserId(userId);
Even without the device id part of it, I can't get the user part working. I can send a notification without any tags, but I add in the user tag and it does not work. I assumed by calling setUserId that would add a tag, based on the links above.

one signal sdk setup for sending push notification to a particular registered android or ios device

I am very new to xamarin apps, can anyone please tell me how to setup one signal push notification for android and ios. I am able to achieve notification for all the registered device but i want to send notification to a particular registered device. How to achieve this in xamarin android and ios.
If I understood your question right, you want to attach the user data stored on your system by id or email to the device UUID acquired by OneSignal so that you can then target a user from your backend via the OneSignak API.
Xamarin has nothing to do for this, but sending the device UUID to your App backend while the user is logged in, and your App backend should store the UUID with the user data.
void SomeMethod() {
OneSignal.Current.IdsAvailable(IdsAvailable);
}
private void IdsAvailable(string userID, string pushToken) {
//here you can send the userID along with stored login token
//or any kind of id to your backend
}
for more info
https://documentation.onesignal.com/docs/xamarin-sdk

Firebase notification in Xamarin

I'm implementing Firebase in a Xamarin Forms application.
I use the Rest API for the database.
Is there a way to register the notification token using the REST API?
Write code for both iOS and Android that extracts the token and posts to a REST API endpoint?
Or perhaps there is a better solution for Firebase notifications in Xamarin?
Is there a way to register the notification token using the REST API? Write code for both iOS and Android that extracts the token and posts to a REST API endpoint?
In Xamarin.form it does not provide the cross platform API to push notification. But you can achieve push notification in each platform. Take android as an example :
[Service]
[IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })]
public class MyFirebaseInstanceIDService : FirebaseInstanceIdService {
public override void onTokenRefresh() {
// Get updated InstanceID token.
String refreshedToken = FirebaseInstanceId.Instance.Token;
// send Instance ID token to your app server.
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
//implement this method to send token to your app server
}
}
In the sendRegistrationToServerfunction you can posts the token to a REST API endpoint.
Do not forget to register the service to android manifest.
Android firebase guide
For IOS platform please refer this document guide

How to retrieve device token from Parse Installation

I have built a Trigger.io application and have been using parse for my push notifications.
I am now migrating to pushwoosh for my push notification needs, however I realise that parse uses Installation id for pushing notifications but pushwoosh uses device token.
I was unable to retrieve the device token from parse as the available function only allows me to retrieve the installtion id.
forge.parse.installationInfo(function (info) {
//info object only stores the installation id
forge.logging.info("installation: "+JSON.stringify(info));
});
However for pushwoosh, I require the device id from the server end to push a message to a specific device
//Notify some devices or a device:
Pushwoosh.notify_devices(message, devices, other_options)
So my question is after I migrate my the data from parse over to pushwoosh, how do I retrieve all the device token for all my old users so that I can send notification messages to the users who were using parse for notifications as well?
For Android you can get the devicetoken using the code below. Trigger.io does not have a JavaScript wrapper for the same in their API. You can build it though for your purpose.
ParseInstallation.getCurrentInstallation().saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
String deviceToken = (String) ParseInstallation.getCurrentInstallation().get("deviceToken");
}
});

Send push notifications using Registration ID through Azure Notification Hubs

I am trying to use Azure Notification Hubs to send push notifications to a client. I read this article which uses tags to identify each user.
https://azure.microsoft.com/en-us/documentation/articles/notification-hubs-aspnet-backend-windows-dotnet-notify-users/
It does the work, but the number of tags is limited. I was thinking to store and use the Registration ID that the Hub returns.
Is there any way to send notifications using this ID?
Another way would be using the Channel.URI that is returned by WNS. Can this be implemented somehow?
Actually NH limits only number of tags per single registration but per hub you may have as many registrations as you need and each registration may have unique tag which you can use to route the notifications.
Also there is new Installation API for Notification Hubs which I believe fits better for you. It is still not well-documented but well-done and ready to use. Here you can find short description of how to use that API. Readme is about Java but .NET SDK has pretty much the same capabilities (in the end both call same REST API).
Keyword is TAG ! If you use any spesific tag for any registered device which is Android,IOS,Windows OS etc, you can send notification to any specific device.
To do these, you should follow below steps one by one ;
As Client side, register device using a spesific tag to selected Azure Notification Hub
Client Example for Android :
`/*you don't have to use Firebase infrastructure.
You may use other ways. It doesn't matter.*/`
String FCM_token = FirebaseInstanceId.getInstance().getToken();
NotificationHub hub = new NotificationHub(NotificationSettings.HubName,
NotificationSettings.HubListenConnectionString, context);
String registrationID = hub.register(FCM_token, "UniqueTagForThisDevice").getRegistrationId();
Like you see, we have used a unique tag call "UniqueTagForThisDevice" for selected Android device.
As Server Side, you should send notification using that TAG call "UniqueTagForThisDevice".
Server Example using Web API to send push selected Android device :
[HttpGet]
[Route("api/sendnotification/{deviceTag}")]
public async Task<IHttpActionResult> sendNotification(string deviceTag)
{
//deviceTag must be "UniqueTagForThisDevice" !!!
NotificationHubClient Hub = NotificationHubClient.CreateClientFromConnectionString("<DefaultFullSharedAccessSignature>");
var notif = "{ \"data\" : {\"message\":\"Hello Push\"}}";
NotificationOutcome outcome = await Notifications.Instance.Hub.SendGcmNativeNotificationAsync(notif,deviceTag);
if (outcome != null)
{
if (!((outcome.State == NotificationOutcomeState.Abandoned) ||
(outcome.State == NotificationOutcomeState.Unknown)))
{
return Ok("Push sent successfully.");
}
}
//Push sending is failed.
return InternalServerError();
}
As last, you should call above Web API Service method using "UniqueTagForThisDevice" tag from any helper platform (Postman, Fiddler or anothers.).
Note : TAG doesn't have to be deviceToken or similar things. It just have to spesific for each devices. But I suggest you that, if you use WebAPI and it is related with Owin midlleware, you may prefer username as unique tag. I think, this is more available for application scenarios. In this way, you can carry sending notifications from unique devices to unique users ;)
That's all.

Resources