推送通知:通知文本与其他数据

Push Notifications: notification text vs other data

我有一个 Xamarin.Forms 应用程序可以接收推送通知。收到通知后,用户点击它,应用程序处理通知附带的数据,并采取相应的行动。但我对应用程序的 iOS 部分有疑问。它不是用户友好的通知文本,而是以 json 格式显示数据,这不是为此目的而设计的。 以下是通知的发送方式:

    private static async Task SendTemplateNotificationsAsync(string json, ILogger log)
    {
        NotificationHubClient hub = NotificationHubClient.CreateClientFromConnectionString(NotificationDispatcherConstants.FullAccessConnectionString, NotificationDispatcherConstants.NotificationHubName);
        Dictionary<string, string> templateParameters = new Dictionary<string, string>();

        foreach (var tag in NotificationDispatcherConstants.SubscriptionTags)
        {
            templateParameters["messageParam"] = json;
            try
            {
                await hub.SendTemplateNotificationAsync(templateParameters, tag);
                ...
            }
            catch (Exception ex)
            {
                log.LogInformation($"Failed to send template notification: {ex.Message}");
            }
        }
    }

常量如下:

    public static string APNTemplateBody { get; set; } = "{\"aps\":{\"alert\":\"$(messageParam)\"}}";

    public const string NotificationTokenKey = "NotificationTokenKey";

以下是 AppDelegate.cs 中处理通知的方式:

    [Export("userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler:")]
    public void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
    {
        completionHandler();

        NSDictionary userInfo = response.Notification.Request.Content.UserInfo;
        ProcessNotification(userInfo);
    }

    [Export("userNotificationCenter:willPresentNotification:withCompletionHandler:")]
    public void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action<UNNotificationPresentationOptions> completionHandler)
    {
        completionHandler(UNNotificationPresentationOptions.Sound | UNNotificationPresentationOptions.Alert);

        NSDictionary userInfo = notification.Request.Content.UserInfo;
        ProcessNotification(userInfo);
    }

    void ProcessNotification(NSDictionary options)
    {
        Task.Run(() =>
        {
            // make sure we have a payload
            if (options != null && options.ContainsKey(new NSString("aps")))
            {
                // get the APS dictionary and extract message payload. Message JSON will be converted
                // into a NSDictionary so more complex payloads may require more processing
                NSDictionary aps = options.ObjectForKey(new NSString("aps")) as NSDictionary;
                string payload = string.Empty;
                NSString payloadKey = new NSString("alert");
                if (aps.ContainsKey(payloadKey))
                {
                    payload = aps[payloadKey].ToString();
                }

                if (!string.IsNullOrWhiteSpace(payload))
                {
                    if (App.UserContext.IsEmployee)
                    {
                        App.NewCall(payload);
                    }
                }
            }
            else
            {
                Debug.WriteLine($"Received request to process notification but there was no payload.");
            }
        });
    }

App.NewCall(有效载荷);是使应用程序处理有效负载的代码,这是正确的。但我不希望此有效负载显示为通知文本。如何将文本设置为不同的和用户友好的内容?

如果您只想显示默认值,则无需处理消息 UI:

请参阅此 doc 中的第 12 步,确保您的负载格式正确:

    void ProcessNotification(NSDictionary options, bool fromFinishedLaunching)
{
    // Check to see if the dictionary has the aps key.  This is the notification payload you would have sent
    if (null != options && options.ContainsKey(new NSString("aps")))
    {
        //Get the aps dictionary
        NSDictionary aps = options.ObjectForKey(new NSString("aps")) as NSDictionary;

        string alert = string.Empty;

        //Extract the alert text
        // NOTE: If you're using the simple alert by just specifying
        // "  aps:{alert:"alert msg here"}  ", this will work fine.
        // But if you're using a complex alert with Localization keys, etc.,
        // your "alert" object from the aps dictionary will be another NSDictionary.
        // Basically the JSON gets dumped right into a NSDictionary,
        // so keep that in mind.
        if (aps.ContainsKey(new NSString("alert")))
            alert = (aps [new NSString("alert")] as NSString).ToString();

        //If this came from the ReceivedRemoteNotification while the app was running,
        // we of course need to manually process things like the sound, badge, and alert.
        if (!fromFinishedLaunching)
        {
            //Manually show an alert
            if (!string.IsNullOrEmpty(alert))
            {
                var myAlert = UIAlertController.Create("Notification", alert, UIAlertControllerStyle.Alert);
                myAlert.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null));
                UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(myAlert, true, null);
            }
        }
    }
}

如果您想使用 custom user interfaces,您可以创建一个通知内容扩展并在那里创建您的 UI。