4

我有一个包含我的日期的数组。我想在早上 6.30 安排那些日子的通知。

我遵循了appcoda 教程,该教程有助于根据日期选择器的输入安排通知,这很棒,但我有点不确定如何调用我的函数以仅在给定的日期安排通知。

所以我的问题是如何以及在哪里调用该函数?

  • 这些天是连续的天
  • 我可以给函数一个开始日期并用数组中的项目数重复它吗?

以下是我的功能:

    func scheduleNotification(at date: Date) {
        let calendar = Calendar(identifier: .gregorian)
        let components = calendar.dateComponents(in: .current, from: date)
        let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: 6, minute: 30)
        let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: false)

        let content = UNMutableNotificationContent()
        content.title = "Advent Calendar"
        content.body = "Just a reminder to open your present!"
        content.sound = UNNotificationSound.default()

        let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)
 UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        UNUserNotificationCenter.current().add(request) {(error) in
            if let error = error {
                print("Uh oh! We had an error: \(error)")
            }
        }
    }
4

1 回答 1

1

是的,所以在咨询了开发人员@gklka之后,我决定使用一个简单的 for 循环,重复 24 次)并将索引传递给函数的 day 属性,在那里我预先配置了小时、分钟、年和月,如下所示:

func scheduleNotification(day: Int) {

    var date = DateComponents()
    date.year = 2016
    date.month = 11
    date.day = day
    date.hour = 6
    date.minute = 30

    let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: false)
}

和for循环:

for index in 1...24 {
        scheduleNotification(day: index)
    }

由于我已经设置了所有内容 int AppDelegate 我调用该函数didFinishLaunchingWithOptions

12月1日更新。

所以我把所有东西都保留了下来,但早上没有发生任何通知。. 我查看了我的代码以找出原因。有2个问题。

  1. 我的函数中有一行代码可以删除之前在循环中设置的任何通知,所以我将下面的代码行注释掉了,但事情仍然没有按预期工作。UNUserNotificationCenter.current().removeAllPendingNotificationRequests()

  2. 我发现我已经使用相同的 requestIdentifier 安排了我的通知,这基本上让我在最后一天只收到了​​ 1 个通知。我只是用字符串插值在自定义 ID 变量的末尾添加了索引,如下所示:let requestId = "textNotification\(day)"

于 2016-11-30T22:52:56.600 回答