swift - 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 小时?
解决方案
由于这是在本地运行的,因此您可以通过将函数保存在 UserDefault 中来保存上次发送函数的时间。例如,将以下内容添加到代码中以保存用户上次完成任务的时间:
UserDefaults.standard.set("/(youWillWriteAFunctionForDate)", forKey: "checkTaskOfDate")
然后您可以简单地检查它是否是今天发送的,并做出相应的计划:
defaults.string(forKey: "checkTaskOfDate") ?? "Never Done"
推荐阅读
- python - 按列索引从多个数据框中添加数据
- r - tidyverse 跨列连接字符不适用于 c_across
- html - 使用第一页 css 保持网格
- types - 如何让 Powershell 从刚加载的程序集中添加类型
- reactjs - 只画了最后一个图的圆圈
- java - JPA 存储库在 @RestController 之外返回 null
- opengl - glslLangValidator 多个预处理器替换
- vue.js - 为 Vue.js 应用程序实现 D3 交互式和动态呈现的折线图
- azure-api-management - Azure API 管理获取用户身份?
- reactjs - ReactJS:在提交和更改时访问一个非常简单的表单输入值