ios - Swift:静音当天的通知
问题描述
在我的应用程序中,我每天发送通知以提醒用户访问该应用程序。此通知每天下午 1 点在本地发送。
func scheduleNotifications() -> Void {
for notification in notifications {
let content = UNMutableNotificationContent()
content.title = notification.title
let todaysDate = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd"
let currentDay = dateFormatter.string(from: todaysDate)
let currentDayInt = Int(currentDay) ?? 0
var datComp = DateComponents()
datComp.hour = 13
datComp.minute = 00
datComp.day = currentDayInt + 1
let trigger = UNCalendarNotificationTrigger(dateMatching: datComp, repeats: true)
let request = UNNotificationRequest(identifier: notification.id, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
guard error == nil else { return }
print("Scheduling notification with id: \(notification.id) on Day \(datComp.day ?? 00) at \(datComp.hour ?? 00) - \(datComp.minute ?? 00)")
}
}
}
如您所见,我添加了“当天 + 1”行,因为如果用户在下午 1 点之前打开应用程序,则无需在这一天发送通知。所以每次用户打开应用程序时,我都会UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
删除并重新安排第二天的通知(通过调用上面的函数)。
我的问题:只要用户打开应用程序,通知应该每天重复,它确实如此。但是如果用户一天没有打开应用程序,那么接下来的几天就没有通知。
有没有办法让当天的通知静音,这样我就不必使用这个“当天+1”的东西了?或者有人有更好的主意吗?
谢谢你们。
解决方案
我认为您误解了重复通知和您的 datComp 在这里的工作方式。
例如(让我们使用今天的日期:5 月 27 日)
datComp.hour = 13
datComp.minute = 00
datComp.day = currentDayInt + 1 // in our example it's 28
let trigger = UNCalendarNotificationTrigger(dateMatching: datComp, repeats: true)
意味着您的通知将在每个月的 28 日触发,您的触发器知道的所有参数是小时、分钟、天,并且通过重复它,将在每个 28 日的 13:00 触发。
因此,您的应用程序现在的工作方式是您从明天开始设置每月通知,当您打开应用程序时,您会删除该每月通知并将其重新安排在一天后。通过每天打开它给你的印象是它的每日通知,但它不是,它是每月一次。这就是为什么如果你不打开应用程序,第二天什么都不会出现,它会在下个月出现。
您可以在这里查看我的类似解释:(那里的最佳答案,也许措辞更好,更容易理解)
以及我在这里遇到的类似问题的解决方案:
推荐阅读
- node.js - Jquery 数据表 Nodejs 服务器端渲染
- c# - 后台工作线程和异步调用
- c - 通过从文件中读取将数字提取到字符串数组
- python - 不同编程语言的副作用
- c++ - 为什么在使用 STL 复制算法时出现“将 'const Person' 作为 'this' 参数丢弃限定符”?
- data-protection - Dot Net Core 3.1 包括包“Microsoft.AspNetCore.DataProtection.EntityFrameworkCore”无法识别 EntityFrameworkCore 部分
- c# - async/await,如何正确使用
- javascript - JS & DOM 查询 - 我的代码有问题吗?
- twitterapi-python - Python 的类型错误
- javascript - 隐式检查 axios 调用是否成功