I have achieved the push notification using Azure notification hub but I want to extend the functionality to send different notification to different devices. I am registering devices using Azure Web Api using following method. I have completely followed this link but not able to figure our how can I send notification either by Device Id or User?
public async Task RegisterDeviceAsync(params string[] tags)
{
var deviceInstallation = DeviceInstallationService?.GetDeviceInstallation(tags);
await SendAsync<DeviceInstallation>(HttpMethod.Put, RequestUrl, deviceInstallation)
.ConfigureAwait(false);
await SecureStorage.SetAsync(CachedDeviceTokenKey, deviceInstallation.PushChannel)
.ConfigureAwait(false);
await SecureStorage.SetAsync(CachedTagsKey, JsonConvert.SerializeObject(tags));
}
I am using below payload template
public class Generic
{
public const string Android = "{ \"notification\": { \"title\" : \"PushDemo\", \"body\" : \"$(alertMessage)\"}, \"data\" : { \"action\" : \"$(alertAction)\" } }";
public const string iOS = "{ \"aps\" : {\"alert\" : \"$(alertMessage)\"}, \"action\" : \"$(alertAction)\" }";
}
Below method is used to send notifications:
public async Task<bool> RequestNotificationAsync(NotificationRequest notificationRequest, CancellationToken token)
{
if ((notificationRequest.Silent &&
string.IsNullOrWhiteSpace(notificationRequest?.Action)) ||
(!notificationRequest.Silent &&
(string.IsNullOrWhiteSpace(notificationRequest?.Text)) ||
string.IsNullOrWhiteSpace(notificationRequest?.Action)))
return false;
var androidPushTemplate = notificationRequest.Silent ?
PushTemplates.Silent.Android :
PushTemplates.Generic.Android;
var iOSPushTemplate = notificationRequest.Silent ?
PushTemplates.Silent.iOS :
PushTemplates.Generic.iOS;
var androidPayload = PrepareNotificationPayload(
androidPushTemplate,
notificationRequest.Text,
notificationRequest.Action);
var iOSPayload = PrepareNotificationPayload(
iOSPushTemplate,
notificationRequest.Text,
notificationRequest.Action);
try
{
if (notificationRequest.Tags.Length == 0)
{
// This will broadcast to all users registered in the notification hub
await SendPlatformNotificationsAsync(androidPayload, iOSPayload, token);
}
else if (notificationRequest.Tags.Length <= 20)
{
await SendPlatformNotificationsAsync(androidPayload, iOSPayload, notificationRequest.Tags, token);
}
else
{
var notificationTasks = notificationRequest.Tags
.Select((value, index) => (value, index))
.GroupBy(g => g.index / 20, i => i.value)
.Select(tags => SendPlatformNotificationsAsync(androidPayload, iOSPayload, tags, token));
await Task.WhenAll(notificationTasks);
}
return true;
}
catch (Exception e)
{
_logger.LogError(e, "Unexpected error sending notification");
return false;
}
}