Swift-交付应用程序上的本地通知图标徽章编号更新处于后台 [英] Swift - Local notification icon badge number update on deliver App is in background
问题描述
我试图弄清楚在发送本地通知时如何动态更新图标徽章编号. 按计划注册徽章编号不是一种选择,因为如果我在交付任何通知之前注册了两个或更多通知,则
I am trying to figure how I can update dynamically the icon badge number when a local notification is delivered. Registering the badge number upon scheduling is not an option since if I register two or more notification before any are delivered the
UIApplication.shared.applicationIconBadgeNumber // this will be zero
在发送通知之前,它将始终为零.
will always be zero until a notification is delivered.
我可以将UNUsernotification委托与func一起使用
I can use the UNUsernotification delegate with the func
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { }
,但仅在应用程序处于活动状态时才调用此函数. 如果该应用程序未激活怎么办?
but this function is called just if the app is active. What if the app is not active?
我已经阅读了一些,几乎所有阅读过的人都说没有办法做这样的事情!但这有可能吗?
I've read a bit around and pretty much everyone i've read says there is no way to do such a thing! But is this even possible??
Apple如何管理提醒和日历的通知?他们是本地通知,并且他们更新了图标徽章吗?还是我做错了?我相信这是在传递本地通知时更新图标徽章的一种方法吗?
How the Apple manage the notification for reminder and calendar? are they local notification and they update the icon badge? or am I making a mistake? I believe it must be a way to update the icon badge when the local notification is delivered?
有想法的人吗?不能相信苹果没有提供实现这一目标的方法!谢谢!
Any idea guys? can't believe Apple did not provide a way to achieve this! Thank you!
推荐答案
为了能够为重复通知和计划通知增加徽章,您应该在配置通知之前增加UIApplication.shared.applicationIconBadgeNumber:
In order to be able to increase the badge for both repetitive and scheduled notifications, you should increase UIApplication.shared.applicationIconBadgeNumber, before configuring the notification:
UIApplication.shared.applicationIconBadgeNumber += 1
然后简单地:
let notificationContent = UNMutableNotificationContent()
notificationContent.title = "Test"
notificationContent.subtitle = "Test"
notificationContent.body = "Test"
notificationContent.sound = UNNotificationSound.default
notificationContent.badge = UIApplication.shared.applicationIconBadgeNumber as NSNumber
要在用户每次打开应用程序时重置计数器,只需将AppDelegate.swift中的UIApplication.shared.applicationIconBadgeNumber的值设置为0,如下所示:
In order to reset the counter every time the user opens the app, just simply set the value of UIApplication.shared.applicationIconBadgeNumber to 0 in AppDelegate.swift like this:
func applicationWillResignActive(_ application: UIApplication) {
UIApplication.shared.applicationIconBadgeNumber = 0
}
这篇关于Swift-交付应用程序上的本地通知图标徽章编号更新处于后台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!