首页 > 解决方案 > 未添加本地通知

问题描述

我有直到最近才可以使用的代码。它应该根据给定日期的列表安排许多本地通知。

代码如下所示:

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该调用中添加一行,则待处理请求的数量始终为 1,并且示例通知也会在一分钟后出现。scheduleSampleNotification

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

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


编辑
有趣:当我从 更改为 时UNCalendarNotificationTriggerUNTimeIntervalNotificationTrigger所有通知都已安排。也许我的触发器有问题 - 但所有日期都在未来?


编辑 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)

不知道为什么,尤其是以前它曾经工作过...

标签: iosswiftnotifications

解决方案


推荐阅读