Search code examples
swiftcore-dataswiftuiuilocalnotification

SWiftUI - Access UUID.uuidString Identifier in Local Notification


How can I access a UUID.uuidString Identifier of a Notification after being added? Let's assume I want to delete that notification, how can I call that?

I cannot use a unique string for one item because I might have two notifications in different timing sored in different Core Data entities and if I use a string for on, it will effect all the notifications for the same item.

// Notification
                                        
let content = UNMutableNotificationContent()
content.title = self.test.testData[item].title
content.body = "Notification"
content.sound = UNNotificationSound.default
                                        
var dateComponents = DateComponents()
dateComponents.weekday = 5 
dateComponents.hour = 6
dateComponents.minute = 13
                                        
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
                                        
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
                                        
UNUserNotificationCenter.current().add(request)

Solution

  • Since you're adding local notification corresponding to a particular element in testData, you could add a new attribute to the Core Data object testData and name it notificationIdentifier. Recreate the model for the testData Core Data entity and then before saving testData entity to core data set the notificationIdentifier value.

    let notificationIdentifier = UUID().uuidString
    let request = UNNotificationRequest(identifier: notificationIdentifier, content: content, trigger: trigger)
    //...
    UNUserNotificationCenter.current().add(request)
    //...
    testEntity.notificationIdentifier = notificationIdentifier
    

    Here you can get the notificationIdentifier for a particular testEntity and from the identifier you could delete an old local notification and create new local notification with new notificationIdentifier and update the new notificationIdentifier to the Core Data testEntity.