Reputation: 432
I've implemented a date picker for setting reminders which sends a local notification. During testing, I noticed I can set a reminder multiple times at the same time. I assumed the system would recognize I've already set it once at that particular time, and would not save another reminder. Surprisingly, the app sent more than once notification at the same time.
I figured I implemented this incorrectly so I decided to test the default Clock app. Again, I set two alarms at the same time, and I got two notifications concurrently:
Is this a normal behaviour for notifications? Are my assumptions wrong? Maybe this would've been okay when the user wanted to assign different messages to separate notifications. However, in my case, the app is supposed to remind users for one simple task, with a static message.
Is there a way to fix this "problem"? The way I see it, if I've already set a reminder, the app should still show that a new reminder has been saved, but not actually save the new one.
Upvotes: 0
Views: 53
Reputation: 4391
This is the normal and intended behaviour. Two notifications might have the same time but completely different data, so they are not restricted to one per unit time.
I would set the unique identifier of the notification and keep track of them in an array.
Here is an example:
let center = UNUserNotificationCenter.current()
// Setup content
let content = UNMutableNotificationContent()
content.title = "Notificaion title"
content.body = "Yoir text here"
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "YouCanHaveDifferentCategories"
content.userInfo = ["myKey": "myValue"]
// Setup trigger time
var calendar = Calendar.current
let now = Date()
let date = calendar.date(byAdding: .second, value: 10, to: now)
let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: false)
// Create request
// Set any unique ID here. I use the UUID tools. This value is used by notificaion center, but I alsp store it in an array property of the relevant object in my data model, so the notification can be removed if the user deletes that object.
let uniqueID = UUID().uuidString
let request = UNNotificationRequest(identifier: uniqueID, content: content, trigger: trigger)
// Add the notification request
center.add(request)
You can then selectively delete notifications with these methods, as long as you have a record in an array or your data model of the identifiers. You can pass an array to delete multiple at once.
center.removePendingNotificationRequests(withIdentifiers: "UniqueID")
center.removeDeliveredNotifications(withIdentifiers: "UniqueID")
Upvotes: 2