How to set time to live to GCM/ FCM payload in notification hub

1.6k views Asked by At

I'm using Notification Hub with FCM to send notifications to my Android application. I want to set message priority and time to live property additionally with each notification but notification hub is expecting jsonpayload and tags in SendGcmNativeNotificationAsync method on HubClinet. I am not sure that how to add these additional properties in payload.

1

There are 1 answers

0
Rahul Garg On

We can add these properties in our custom model in correct format and then convert it to json payload.

public class GcmNotification
{
    [JsonProperty("time_to_live")]
    public int TimeToLiveInSeconds { get; set; }
    public string Priority { get; set; } 
    public NotificationMessage Data { get; set; }
}


 public class NotificationMessage
 {
   public NotificationDto Message { get; set; }
 }

 public class NotificationDto
 {
        public string Key { get; set; }
        public string Value { get; set; }
 }

Call SendNotification method ans pass your model.Now you can convert your data with json converter but remember use lowercase setting in JsonConverter otherwise there might be expection on device. I have implementation of this in LowercaseJsonSerializer class.

 private void SendNotification(GcmNotification gcmNotification,string tag)
  {
     var payload = LowercaseJsonSerializer.SerializeObject(gcmNotification);
     var notificationOutcome = _hubClient.SendGcmNativeNotificationAsync(payload, tag).Result;
 }

public class LowercaseJsonSerializer
    {
        private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
        {
            ContractResolver = new LowercaseContractResolver()
        };

        public static string SerializeObject(object o)
        {
            return JsonConvert.SerializeObject(o,Settings);
        }

        public class LowercaseContractResolver : DefaultContractResolver
        {
            protected override string ResolvePropertyName(string propertyName)
            {
                return propertyName.ToLower();
            }
        }
    }