使用Swift 3为日期数组安排通知

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)")
            }
        }
    }
1个回答

1

好的,在与@gklka开发者协商后,我决定使用一个简单的for循环,重复24次,并将索引传递给函数的day属性,在那里我像这样预配置了hour、minute、year和month:

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)
    }

由于我已经在AppDelegate中设置好了一切,因此我在didFinishLaunchingWithOptions中调用该函数。

12月1日更新。

所以我把一切都留下了,但早上没有发生任何通知。 我查看了我的代码以找出原因。 有两个问题。

  1. 在我的函数中,我有一行代码会在迭代循环时删除任何先前设置的通知,因此我注释掉了下面的代码行,但事情仍然不像预期的那样工作。UNUserNotificationCenter.current().removeAllPendingNotificationRequests()

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


这个新的scheduleNotification函数如何与你之前创建通知的那个函数交互?你所有警报的内容都一样吗? - tylerSF
@tylerSF,它一次性创建了所有24个通知,每天安排一个。该应用程序每天都包含一个新礼物,因此通知是相同的,只是为了将信息带给用户的注意力。 - Ben S

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接