首页 > 解决方案 > ios - 等待 24 小时发送通知

问题描述

我们的应用程序每天早上 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 小时?

标签: swiftnsdatecomponents

解决方案


由于这是在本地运行的,因此您可以通过将函数保存在 UserDefault 中来保存上次发送函数的时间。例如,将以下内容添加到代码中以保存用户上次完成任务的时间:

UserDefaults.standard.set("/(youWillWriteAFunctionForDate)", forKey: "checkTaskOfDate")

然后您可以简单地检查它是否是今天发送的,并做出相应的计划:

defaults.string(forKey: "checkTaskOfDate") ?? "Never Done"

推荐阅读