public override void ReceivedRemoteNotification(UIApplication application, NSDictionary remoteNotification)
{
try
{
if (remoteNotification != null)
{
var alert = remoteNotification[FromObject("aps")];
if (alert != null)
{
string id = ((NSDictionary)alert)[FromObject("deleteId")].Description;
if (!String.IsNullOrEmpty(id))
{
List<string> idents = new List<string>();
UNUserNotificationCenter.Current.GetDeliveredNotifications(completionHandler: (UNNotification[] t) =>
{
foreach (UNNotification item in t)
{
UNNotificationRequest curRequest = item.Request;
var notificationId = ((NSDictionary)curRequest.Content.UserInfo[FromObject("aps")])[FromObject("notificationId")].Description;
if (id == notificationId)
{
idents.Add(curRequest.Identifier);
}
}
UNUserNotificationCenter.Current.RemoveDeliveredNotifications(idents.ToArray());
});
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
问题是通知在通知中心仍然可见,直到应用程序进入前台。但它会被删除。
有没有办法强制该方法立即删除通知,而不仅仅是在(重新)打开应用程序时?
答案 0 :(得分:0)
如果要清除此应用发送的通知。将其应用程序的徽章设置为0以实现此目的。
正如您所说,您向其他用户发送了无声通知,然后DidReceiveRemoteNotification()
将会触发。在这种情况下,我们可以清除所有通知:
public override void DidReceiveRemoteNotification(UIApplication application, NSDictionary userInfo, Action<UIBackgroundFetchResult> completionHandler)
{
var aps = userInfo["aps"] as NSDictionary;
if (aps["content-available"].ToString() == "1")
{
//check if this is a silent notification.
UIApplication.SharedApplication.ApplicationIconBadgeNumber = 0;
}
completionHandler(UIBackgroundFetchResult.NewData);
}
请注意,从iOS 8.0开始,您的应用程序需要注册用户通知才能设置应用程序图标徽章编号。所以请在FinishedLaunching()
:
UIUserNotificationSettings settings = UIUserNotificationSettings.GetSettingsForTypes(UIUserNotificationType.Badge, null);
UIApplication.SharedApplication.RegisterUserNotificationSettings(settings);
此外,只有当您的应用位于后台或前台时,才能接收静音通知。如果终止,则会失败。
答案 1 :(得分:0)
要删除通知,您将无提示推送通知发送到所有具有通知ID作为应删除的有效负载的设备。
您在客户端上实现了UNNotificationServiceExtension
,可让您通过其ID UNUserNotificationCenter.current().removeDeliveredNotifications
删除当前显示的通知。
这给您带来的好处是,您可以在服务器端完全控制此逻辑。