问题描述
我们的应用程序每天早上 8 点都会发送通知来问候用户并提醒他完成任务。这是我们正在使用的脚本:
let center = UNUserNotificationCenter.current()
center.removePendingNotificationRequests(withIdentifiers: ["dailyReminder"])
let content = UNMutableNotificationContent()
content.title = "Good morning"
content.body = notificationMessages[randomIndex]
content.sound = .default
var dateComponents = DateComponents()
dateComponents.hour = 8
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents,repeats: true)
let request = UNNotificationRequest(identifier: "dailyReminder",content: content,trigger: trigger)
center.add(request)
这是在用户完成当天任务后调用的,以便他们在第二天收到提示。但是,有些人在早上 8 点之前完成了任务。在这些情况下,我们希望在第二天早上 8 点发送通知。
我如何计算脚本是在 8 点之前还是之后运行并相应地添加 24 小时?
解决方法
由于这是在本地运行,因此您可以通过将其保存在 UserDefault 中来保存上次发送该函数的时间。例如,在代码中添加以下内容以在用户上次完成任务时进行保存:
UserDefaults.standard.set("/(youWillWriteAFunctionForDate)",forKey: "checkTaskOfDate")
然后您可以简单地检查它是否是今天发送的,并相应地进行计划:
defaults.string(forKey: "checkTaskOfDate") ?? "Never Done"