使用日期选择器的本地 UNMutableNotificationContent 触发日期

Local UNMutableNotificationContent fire date using Date picker

所以我一直在尝试实现 iOS 10 本地通知,首先我认为代码与 iOS 9 相同,只是添加了一个通知扩展目标。然而它实际上使用了 UNMutableNotificationContent class,

我可以使用时间间隔设置通知,但是如何使用日期选择器专门设置触发日期?

import UserNotifications

let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
let displayDate  = dateFormatter.string(from: datePicker.date)

let notif = UNMutableNotificationContent()

notif.title = "Reminder)"
notif.subtitle = "\(displayDate)"
notif.body = "Details"
notif.categoryIdentifier = "Details Reminder"

let notifTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)

let request = UNNotificationRequest(identifier: "myNotif", content: notif, trigger: notifTrigger)

UNNotificationRequest 触发器需要类型 UNTimeIntervalNotificationTrigger,我希望我可以添加一个日期。

我是否必须使用当前日期和日期选择器日期计算间隔时间?或者我可以用其他方式做到这一点

您需要提供 'now' 和您希望发送通知的时间间隔。

let interval = laterDate.timeIntervalSince(earlierDate)

在这种情况下,earlierDate 应该是 'now'(即只是 Date()),我假设 laterDate 是您的 datePicker.date

您应该使用 UNCalendarNotificationTrigger。

UNCalendarNotificationTrigger.init(dateMatching: NSCalendar.current.dateComponents([.day, .month, .year, .hour, .minute], from: <<YOUR_DATE>>), repeats: false)