使用核心数据属性创建 UI 本地通知

Creating UILocalNotifications with CoreData attribute

在我的 iOS 应用程序中,我试图创建一个 localNotification 以在活动开始前 15 分钟通知用户。但是我被卡住了。我正在使用 CoreData 来存储数据。我有一个可以创建的 Appointment 对象。 date 属性与 Appointment 对象关联。我真的被它困住了。我不知道如何设置 timeInterval 和通知过程的其余部分。

我不知道如何设置从创建 Appointment 到开始前 15 分钟的 timeInterval

这是我的一些代码:

func scheduleNotifications() {
    let content = UNMutableNotificationContent()
    guard let client = client, let name = client.name, let formula = formula, let date = formula.date else { return }
    content.title = "BookMe"
    content.subtitle = ""
    content.body = "Your appointment with \(name) will begin soon."
    content.badge = 1

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: ??, repeats: false)

已编辑:这就是我所拥有的,但没有发射任何东西。

let date = formula.date
let fireDate = Calendar.current.date(byAdding: DateComponents(minute: -15), to: date as Date)
guard let timeInterval = fireDate?.timeIntervalSince(Date()) else { return }

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInterval, repeats: false)

let request = UNNotificationRequest(identifier: self.timerUserNotificationIdentifier, content: content, trigger: trigger)

UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

据我了解,您正在寻找从现在到某个日期前 15 分钟之间的时间间隔,以便您可以在该日期前 15 分钟发出通知。

这是我在操场上撞到的一个简单例子

// Create a date in the future - this is what you get from your own data object and I'm creating it here just so I have a date.
let scheduledDate = Calendar.current.date(from: DateComponents(year: 2017, month: 09, day: 22, hour: 22))!

// Create a date 15 minutes earlier than your shcheduled date, this is when you want your notification to fire
let fireDate = Calendar.current.date(byAdding: DateComponents(minute: -15), to: scheduledDate)!

// Then just work out the time interval between the fire date and now to get the time interval
let timeInterval = fireDate.timeIntervalSince(Date())

请原谅创建日期的强制展开,这些是因为它是一个示例,您不应该使用感叹号并优雅地处理错误。

编辑添加

您尝试使用的 UNTimeIntervalNotificationTrigger 需要一个介于 now 和您想要触发通知的时间之间的 TimeInterval。 TimeInterval 是表示秒数的 Double。在某些情况下,例如这个,它表示延迟,即从现在到您要触发通知的时间之间的秒数。在其他情况下,它表示从固定日期开始的秒数的日期。这个固定日期可以是 timeIntervalSince1970 - "The interval between the date object and 00:00:00 UTC on 1 January 1970."(这是你用于 UNIX 时间戳的日期)或 timeIntervalSinceReferenceDate - "The interval between the date object and 00:00:00 UTC on 1 January 2001."

无论您做什么,都要抵制通过直接添加或删除秒数来修改日期的诱惑,改用 DateComponents。