I currently have a function that writes a realm object into the database and writes a notification. When the object is written, it is added into a uicollectionview and displayed. The function below adds the object and sets a notification based on a UIDatePicker. That code is not shown since it is a lot that doesn't pertain to the problem:
func createTaskWithDate() {
let task = Task()
task.name = textField.text!
//notification code under here
try! realm.write {
realm.add(task)
updateData()
}
I also have another function that responds to an action on a notification set. When the user taps on the notification, they are given the option to "mark as complete". When the user taps "mark as complete", I am trying to retrieve the object from the "createTaskWithDate()" method and delete it from the collection view however I'm unsure on how to retrieve that object from that method:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let identifier = response.actionIdentifier
let request = response.notification.request
if identifier == "complete" {
try! realm.write {
//realm.delete(task object from createTaskWithDate())
updateData()
}
}
completionHandler()
}
How could I go about doing this?
When setting up the notification, you should store the name/primary key of the object the notification is about in your notification request. You can store any information in UNMutableNotificationContent.userInfo
and access it in userNotificationCenter(_:didReceive:withCompletionHandler:)
by
let userInfo = response.notification.content.userInfo
.
Then you can retrieve the object from Realm
with the primary key stored in userInfo
.