8

I am using UNUserNotificationCenter to get delivered notifications like so:

UNUserNotificationCenter.current().getDeliveredNotifications { (notifications) in
    self.array = notifications
}

and then on viewWillDisappear I am clearing the applicationIconBadgeNumber like so:

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    UIApplication.shared.applicationIconBadgeNumber = 0
}

Doing this does not make my notifications last long, yes I would like the badge number to be at 0 after you see the notifications, but I would like those ones to last for 24 - 48 hours....How can I accomplish this?

pacification
  • 5,838
  • 4
  • 29
  • 51
user979331
  • 11,039
  • 73
  • 223
  • 418

1 Answers1

2

Get the date property of notifications, and only clear those that have been triggered in the last 24 hours. Use this function:

func updateAppIcon() {
    UNUserNotificationCenter.current().getDeliveredNotifications { (notifications) in            
        let past24hNotifications = notifications
            .filter { $0.date > Date().addingTimeInterval(-24 * 60 * 60)}
        DispatchQueue.main.async {
            UIApplication.shared.applicationIconBadgeNumber = past24hNotifications.count
        }
    }
}

And call it in applicationWillResignActive(_ application:) of the AppDelegate

ielyamani
  • 17,807
  • 10
  • 55
  • 90