如何将对象与通知一起存储,以便在收到通知时可以调用它?

时间:2017-05-19 18:03:47

标签: ios swift swift3 notifications

我是编程新手,这是我的第一个项目。我正在制作一个非常简单的提醒应用程序;我创建了一个带有属性的类提醒.moreInformation(String),. fireDate(Date),. fromDate(Date),. ititle(String)和.image(UIImage)。您可以在应用程序中编辑所有这些属性。我的问题只是:我需要一个适当的解决方案来存储这个对象'提醒'。我正在使用UserNotifications来注册我的通知:

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)
        }
    }

当用户收到通知时,他应该在启动应用时看到一个弹出视图,将他带到一个单独的视图控制器,显示描述文本,fromDate等。

但是如何将对象与通知一起存储,以便在通知到达时,另一个视图控制器显示正确的描述文本/标题等。

1 个答案:

答案 0 :(得分:1)

您可以使用userInfo实例的UNMutableNotificationContent字典来存储自定义信息。 请记住,userInfo字典中存储的对象必须是属性列表类型。这意味着您需要将reminder对象转换为此类型(例如NSDictionary)或者,这将是一个更清晰的解决方案,在{{1的类中实现NSCoding使用reminder / NSKeyedArchiver来对象和en /解码它。