我的应用中没有显示背景和终止案例的徽章计数。 我在appdelegate didfinishlaunch中添加了这段代码
UIApplication.shared.applicationIconBadgeNumber = 0
if #available(iOS 10, *)
{
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
guard error == nil else
{
return
}
if granted
{
UIApplication.shared.registerForRemoteNotifications()
}
}
}
else
{
let settings : UIUserNotificationSettings = UIUserNotificationSettings(types: [.alert, .sound , .badge], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
UIApplication.shared.registerForRemoteNotifications()
}
UIApplication.shared.applicationIconBadgeNumber += 1
print("Badge Count ===> \( UIApplication.shared.applicationIconBadgeNumber)")
打印显示正确的计数。但未在应用中显示。
实际上我不需要更新每个通知的徽章数。对于某些共享或类似我们需要更新徽章计数。所以我创建了一个方法并更新了计数。
func setBadgeCount()
{
if(self.currentAppState() == 1 || self.currentAppState() == 3)
{
sleep(2)
UIApplication.shared.applicationIconBadgeNumber += 1
print("Badge Count ===> \( UIApplication.shared.applicationIconBadgeNumber)")
}
}
来自
的callthis方法func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void)
{
setBadgeCount()
}
答案 0 :(得分:0)
除非应用程序实际处于打开状态,否则应用程序不会使用此方法更新徽章编号。如果要在收到通知时更新徽章编号,则必须在通知的有效负载中设置徽章编号。下面是有效载荷的样本。把你想要的号码放在那里然后发送就可以了。
{
"aps": {
"alert": "Test Push Notification",
"sound": "yourSound.aiff",
"Badge": "desiredNumber"
}
}
答案 1 :(得分:0)
您已在didFinishLaunchingWithOptions
中编写此代码,该代码仅被调用一次。那么它将如何更新徽章编号。
仅在UIApplication.shared.applicationIconBadgeNumber = 0
didFinishLaunchingWithOptions
改为使用,
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
application.applicationIconBadgeNumber = application.applicationIconBadgeNumber + 1;
}
对于推送通知使用,
func application(application: UIApplication,didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
application.applicationIconBadgeNumber = application.applicationIconBadgeNumber + 1;
}
根据您更新的问题,当您获得正确的日志时,当应用进入后台或终止时,您无法获得正确的徽章计数。这是因为为了处理这些情况,我们需要在某处存储徽章计数。您可以将其存储在UserDefaults
中,然后相应地获取它。
答案 2 :(得分:0)