Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a notification disappear from notification center when another one is opened? iOS

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.

like image 517
Pedro Anibarro Avatar asked Nov 08 '22 19:11

Pedro Anibarro


2 Answers

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.

like image 95
Ido Avatar answered Nov 15 '22 11:11

Ido


If your app receives push notifications from OneSignal, and you have therefore integrated the OneSignal SDK, you must add key OneSignal_disable_badge_clearing to the Info.plist file in Xcode, as a Boolean type set to YES, to prevent removal of all notifications after opening one.

More info here https://documentation.onesignal.com/docs/badges

like image 23
Ely Avatar answered Nov 15 '22 10:11

Ely