繁体   English   中英

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

[英]How to store an object together with a notification so that I can call it when receiving the notification?

我是编程新手,这是我的第一个项目。 我正在制作一个非常简单的提醒应用程序; 我创建了一个带有属性 .moreInformation (String)、.fireDate (Date)、.fromDate (Date)、.title (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 等。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM