Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4 UNUserNotificationCenter duration (get notifications in past 24 hours)

Tags:

swift

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?

like image 378
user979331 Avatar asked Aug 31 '18 19:08

user979331


1 Answers

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

like image 141
ielyamani Avatar answered Nov 04 '22 12:11

ielyamani