首页 > 解决方案 > 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”的东西了?或者有人有更好的主意吗?

谢谢你们。

标签: iosswiftnotificationsmute

解决方案


我认为您误解了重复通知和您的 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 触发。

因此,您的应用程序现在的工作方式是您从明天开始设置每月通知,当您打开应用程序时,您会删除该每月通知并将其重新安排在一天后。通过每天打开它给你的印象是它的每日通知,但它不是,它是每月一次。这就是为什么如果你不打开应用程序,第二天什么都不会出现,它会在下个月出现。

您可以在这里查看我的类似解释:(那里的最佳答案,也许措辞更好,更容易理解)

删除计划的本地通知

以及我在这里遇到的类似问题的解决方案:

如何为任务设置每日本地通知,但在用户完成任务之前不显示


推荐阅读