如何在 UWP 应用中使用 azure 通知中心标签推送消息

问题描述

我想向特定渠道中的应用发送推送消息,例如“en-us”和“fr-fr”以本地化推送通知

首先我遵循了本教程,一切都奏效了: https://docs.microsoft.com/en-us/azure/notification-hubs/notification-hubs-windows-store-dotnet-get-started-wns-push-notification

工作登记在:

var result = await hub.RegisterNativeAsync(channel.Uri);

但这只是向所有客户端发送一条消息。然后我跟着这个教程: https://docs.microsoft.com/en-us/azure/notification-hubs/notification-hubs-windows-notification-dotnet-push-xplat-segmented-wns

从我可以从与 uwp 代码混淆的混合中提取内容是这一行:

var hub = new NotificationHub("AppName","endpoint");
            
            const string templateBodyWNS = "<toast><visual><binding template=\"ToastText01\"><text id=\"1\">$(messageParam)</text></binding></visual></toast>";

            var result = await hub.RegisterTemplateAsync(channel.Uri,templateBodyWNS,"simpleWNstemplateExample",new string[] { "en-us" });

结果也给了我一个有效的注册

然后我尝试使用 azure 通知中心控制台对其进行测试(与上一步一起将其发送给所有客户端:

enter image description here

导致应用收到通知(它不会过滤“en-us”)。 然后我尝试将“en-us”放在“发送到标签表达式”中:

enter image description here

这样,没有 toast 消息到达。

然后我尝试通过 Microsoft.Azure.NotificationHubs 包发送消息。

代码有效:

NotificationHubClient Hub = NotificationHubClient.CreateClientFromConnectionString(endpoint,name);
            string toast = @"<?xml version='1.0' encoding='utf-8'?>
  <toast>
  <visual><binding template='ToastText01'>
     <text id='1'> Test message </text>
          </binding>
          </visual>
          </toast>
          ";
      var result = await     Hub.SendWindowsNativeNotificationAsync(toast);
   

Toast 消息到达。但是一旦我将最后一行更改为:

var result = await Hub.SendWindowsNativeNotificationAsync(toast,"en-us");

什么都没有。 所以通知中心通过 WNS 成功链接到客户端,但是使用标签根本不起作用。我做错了什么?

解决方法

好的,我想通了,这里有同样问题的人:

首先,其他人也可能对此感到困惑,因为我们需要了解定义推送模板的概念与 FCM(适用于 Android)的工作方式不同。在 FCM 中,您定义推送消息服务器端的布局和内容。

在 UWP 中,它在客户端使用标签时发生。在设计 Toast 时,您可以将变量放入其中,然后由服务器端填充。

这是工作代码。

客户端:

var hub = new NotificationHub("Hubname","endpoint");
string toast = @"<toast>
<visual><binding template='ToastGeneric'>
<text id='1'>$(Title)</text>
<text id='2'>$(Message)</text>

<text placement='attribution'>via SMS</text>
</binding>
</visual>
</toast>
";
var result = await hub.RegisterTemplateAsync(channel.Uri,toast,localizedWNSTemplateExample",new string[] { "myTag" });

服务器端:

NotificationHubClient Hub = NotificationHubClient.CreateClientFromConnectionString(endpoint,name);
Dictionary<string,string> templateParams = new Dictionary<string,string>();
templateParams["Title"] = "Title here";
templateParams["Message"] = "Message here";
await Hub.SendTemplateNotificationAsync(templateParams,"myTag");

您可以从网络上使用“自定义模板”平台发送消息: enter image description here

不确定“自定义模板”是否也可以用于 android 和 iOS。会很棒。