使用azure向IOS和android发送广播通知

时间:2016-03-23 10:15:40

标签: c# azure notifications

IOS平台以下列格式发送JSON有效负载:

{"aps":{"alert":"Notification Hub test notification"}}

而Android有效载荷格式为:

{"data":{"message":"Notification Hub test notification"}}

我的SendBroadcastNotification

public void SendBroadcastNotification(string message) {

    NotificationHubClient hub = NotificationHubClient
             .CreateClientFromConnectionString(Constants.NotificationsHubConnectionString, "QiKStayNotificationHub",true);
    var notify = "{ \"data\" : {\"message\":\"" + message + "\"}}";
    var appnotify = "{ \"aps\" : {\"alert\":\"" + message + "\"}}";
    var task = hub.SendGcmNativeNotificationAsync(notify);
    task.Wait();  
}

因为我在这里发送通知给Android SendGcmNativeNotificationAsync,我特意想把它广播到所有设备。

所以我也应该改变有效载荷JSON格式

hubClient.SendAppleNativeNotificationAsync();
hubClient.SendGcmNativeNotificationAsync(notify);

1 个答案:

答案 0 :(得分:0)

在使用通知中心注册设备时,您应该维护用户的平台

 switch (platform.ToLower())
            {
                case "apns":
                    notificationMessage = "{ \"aps\" : {\"alert\":\"" + message + "\"}}";
                    break;
                case "gcm":
                    notificationMessage = "{ \"data\" : {\"message\":\"" + message + "\",\"display\":\"" + title + "\"}}";
                    break;
                default:
                    break;
            }

或您可以使用模板消息

private static async void SendTemplateNotificationAsync()
{
    // Define the notification hub.
    NotificationHubClient hub = 
        NotificationHubClient.CreateClientFromConnectionString(
            "<connection string with full access>", "<hub name>");

    // Sending the notification as a template notification. All template registrations that contain 
    // "messageParam" or "News_<local selected>" and the proper tags will receive the notifications. 
    // This includes APNS, GCM, WNS, and MPNS template registrations.
    Dictionary<string, string> templateParams = new Dictionary<string, string>();

    // Create an array of breaking news categories.
    var categories = new string[] { "World", "Politics", "Business", "Technology", "Science", "Sports"};
    var locales = new string[] { "English", "French", "Mandarin" };

    foreach (var category in categories)
    {
        templateParams["messageParam"] = "Breaking " + category + " News!";

        // Sending localized News for each tag too...
        foreach( var locale in locales)
        {
            string key = "News_" + locale;

            // Your real localized news content would go here.
            templateParams[key] = "Breaking " + category + " News in " + locale + "!";
        }

        await hub.SendTemplateNotificationAsync(templateParams, category);
    }
}