I am new to programming and this is my very first project. I am making a pretty simple reminder app; I've created a class reminder with the properties .moreInformation (String), .fireDate (Date), .fromDate (Date), .title (String) and .image(UIImage). You can edit all these properties within in the application. My problem is just: I need a proper solution for storing this object 'reminder'. I am using UserNotifications to register my notification like that:
reminder.fireDate = date
reminder.image = image
reminder.description = descriptionTextView.text
reminder.title = titleTextView.text
reminder.savedOndate = savedOnDateString
let center = UNUserNotificationCenter.current()
let category = UNNotificationCategory(identifier: "General", actions: [], intentIdentifiers: [], options: .customDismissAction)
center.setNotificationCategories([category])
let content = UNMutableNotificationContent()
let contentText = reminder.savedOnDate
content.title = "Reminder"
content.body = "Your Reminder from the \(contentText) has arrived!"
let date2 = reminder.fireDate
var components = Calendar.current.dateComponents(in: TimeZone.current, from: date2)
components.hour = 18
components.minute = 0
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
let request = UNNotificationRequest(identifier: "Reminder", content: content, trigger: trigger)
center.add(request) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
When the user has received the notification, he should see a pop-up view when starting the app, leading him to a separate view controller that shows the description text, the fromDate etc.
But how do I store the object together with the notification so when the notification has arrived, the other view controller shows the correct description text/ title etc.?
You can use the userInfo
dictionary of your UNMutableNotificationContent
instance to store custom information.
Keep in mind that objects stored in the userInfo
dictionary must be property-list types. This means you either need to convert your reminder
object to such a type (e.g. NSDictionary
) or, and this would be a cleaner solution, implement NSCoding
in the class of the reminder
object and en/decode it using NSKeyedArchiver
/NSKeyedUnarchiver
.