【发布时间】:2019-03-29 22:47:06
【问题描述】:
我试图在用户第一次打开应用程序时安排一系列通知,所以我有以下代码,但问题是它们被安排在 18:30 而不是 19:30。奇怪的是,如果我在没有 while 循环的情况下只安排一个通知,则数组的索引 0 会在 19:30 工作,但其他人不会。任何想法我做错了什么?
另外,如果这是一种非常愚蠢的做法,请告诉我。 我确实需要具体的日子(所以从当天开始的 1、3、5、7、14... 天)。谢谢。
let triggerDates = [
// Notifications for the first week
Calendar.current.date(byAdding: .day, value: 1, to: Date())!,
Calendar.current.date(byAdding: .day, value: 3, to: Date())!,
Calendar.current.date(byAdding: .day, value: 5, to: Date())!,
Calendar.current.date(byAdding: .day, value: 7, to: Date())!,
// Notifications for the month
Calendar.current.date(byAdding: .day, value: 14, to: Date())!,
Calendar.current.date(byAdding: .day, value: 21, to: Date())!,
// Notifications afterward
Calendar.current.date(byAdding: .day, value: 42, to: Date())!,
Calendar.current.date(byAdding: .day, value: 84, to: Date())!]
var notificationToSchedule = 7
while notificationToSchedule >= 0 {
var dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: triggerDates[notificationToSchedule])
dateComponents.hour = 19
dateComponents.minute = 30
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let request = UNNotificationRequest(identifier: "notification\(notificationToSchedule)", content: content, trigger: trigger)
center.add(request)
print(trigger.nextTriggerDate() ?? "nil")
notificationToSchedule -= 1
}
这是控制台使用此代码输出的内容:
2019-06-21 18:30:00 +0000
2019-05-10 18:30:00 +0000
2019-04-19 18:30:00 +0000
2019-04-12 18:30:00 +0000
2019-04-05 18:30:00 +0000
2019-04-03 18:30:00 +0000
2019-04-01 18:30:00 +0000
2019-03-30 19:30:00 +0000
【问题讨论】:
-
这是因为夏令时。它在 2019 年 3 月 31 日发生变化,因此所有打印的日期都考虑到了这一点。如果您要在更早的日期尝试它,那么您会看到 19:30,如您所愿。
-
编辑——实际上,我看到了另一个问题。您能否将您的建议作为答案发布,我会稍后添加我的更正。
-
我认为您不需要更正。如果您设置断点并查看 triggerDates 数组的内容,您会发现它看起来是正确的,并且只是将它们打印到控制台的行为导致了问题。
-
@UpholderOfTruth 你是什么意思?所以notificationToSchedule既用作数组的索引又用作while循环,所以while循环需要运行8次,但数组只有0到7的索引,所以我不得不将while循环设置为> = 而不是 >,这一切都有效。我尝试通过更改设备的日期来测试通知,第一个以这种方式触发,但不是下一个。是否仍然与我缺少的 DST 有关,我只是错误地安排了它们吗?这是我需要解决的这个应用程序的最后一点,它让我非常头疼。
-
对不起,确实需要更正。你也改了什么日期?
标签: swift while-loop notifications uilocalnotification