未添加本地通知

时间:2019-01-08 18:02:35

标签: ios swift notifications

我有以前一直工作到现在的代码。它应该根据给定日期的列表安排一些本地通知。

代码如下:

static func scheduleNotifications()
{
    // Here, a list of dates when notifications should appear is
    // created. This is called pendingNotifications. It contains
    // a list of dates and the number of events on that date
    ...

    // Now I want to schedule up to 20 local notifications for
    // each of the dates. The badge should show the number of events
    let sortedDates = pendingNotifications.keys.sorted()
    for i in 0 ..< min(20, sortedDates.count)
    {
        let notificationDate = ...

        let content = UNMutableNotificationContent()
        content.title = "The title"
        content.body = "The description"
        content.sound = UNNotificationSound.default()
        content.badge = NSNumber(value: pendingNotifications[sortedDates[i]]!)

        let ident = UUID().uuidString
        let trigger = UNCalendarNotificationTrigger(dateMatching: calendar.dateComponents(in: calendar.timeZone, from: notificationDate), repeats: false)
        let request = UNNotificationRequest(identifier: ident, content: content, trigger: trigger)

        let center = UNUserNotificationCenter.current()
        center.add(request) { error in
            center.getPendingNotificationRequests() { requests in
                print(requests.count)
            }
        }
    }
}

该代码执行没有错误,但是我在完成处理程序中打印的请求计数始终输出0,并且没有得到任何显示。

然后我有第二个功能,可以独立于任何其他条件来安排样本通知:

static func scheduleSampleNotification()
{
    let content = UNMutableNotificationContent()
    content.title = "Test"
    content.body = "Sample Notification!"
    content.sound = UNNotificationSound.default()
    content.badge = 5

    let ident = UUID().uuidString
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: false)
    let request = UNNotificationRequest(identifier: ident, content: content, trigger: trigger)
    let center = UNUserNotificationCenter.current()
    center.add(request)
}

如果我在scheduleNotifications上添加一行,在我写有关创建日期列表的注释之前立即调用scheduleSampleNotification,则挂起的请求数始终为1,并且示例通知也会出现在一分钟。

我实际上不知道我在这里做错了什么,我有点迷茫,特别是因为在我将最低的最低iOS版本从9更改为10.3之前,相同的代码可以正常工作(在我检查的先前版本中是否在iOS 9上运行并使用旧方法提供本地通知-现在我从10.3开始删除了该代码,因为我知道您应该使用UNUserNotificationCenter)。

我正在模拟器和iOS 12设备上进行测试。我使用的是XCode 10.1。


编辑
有趣:当我从UNCalendarNotificationTrigger更改为UNTimeIntervalNotificationTrigger时,所有通知都已排定。触发器可能有问题-但是所有日期都在将来?


编辑2
好的,我发现了问题。显然,以下内容不再起作用:

let dateComponents = calendar.dateComponents(in: calendar.timeZone, from: notificationDate)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)

以下内容确实有效:

let dateComponents = calendar.dateComponents([.day, .month, .year, .hour, .minute], from: notificationDate)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)

不知道为什么,特别是因为它以前曾经工作过...

0 个答案:

没有答案