How to prevent a notification disappear from notif

2019-06-24 19:24发布

问题:

I'm developing an app that receives push notifications. This push notifications, each one contains valuable information that is showed up when the user opens the app from it.

My problem is that if the user receives more than one notification, if the user taps it and open the app, all the other ones disappear from the notification center and I lost all the other important information.

I want to be able to leave/prevent the notifications from disappearing from the notification center in order to give the user the option to keep opening them from the notification center. Somehow like YouTube notifications. I even saw that behavior in Twitch app notifications.

Any idea? Thanks.

回答1:

I know it's a pretty old question, but since it doesn't have an answer, I'll tell you how I solved this issue.

In short, the issue is caused by setting UIApplication.shared.applicationIconBadgeNumber to 0; it's making all of the notifications to be removed from the notification center.

The solution is to set the applicationIconBadgeNumber to the real number of notifications the user has in the notification center. I made a function for this:

func updateIconBadge() {
    UNUserNotificationCenter.current().getDeliveredNotifications { notifications in
        DispatchQueue.main.async {
            UIApplication.shared.applicationIconBadgeNumber = notifications.count
        }
    }
}

Now you can call this function in the methods application(_application:, didFinishLaunchingWithOptions:), applicationWillEnterForeground(_application:), applicationDidBecomeActive(_application:) in AppDelegate.swift to make sure it will update when it should be.