Swift:本地通知似乎重复然后一些消失

Swift: Local notifications seem to duplicate then some vanish

我有一个提醒应用程序,它正在搜索数组以发送服药提醒。当通知通过时,我收到了大量的通知,这些通知似乎瞬间消失了,最后还有 1 条通知。

我的初始视图控制器是 UITableViewController。我尝试将我的 fireNotifications 函数放在 viewDidLoad 中,但它似乎没有发送任何通知。如果我将 fireNotifications 函数调用放在其中一个 tableView 函数中(即 numberOfSectionsInTableView),我就能收到通知,但它们有我上面提到的奇怪行为。

我的代码是:

func fireNotifications() {
    if NSUserDefaults().boolForKey("NotifySwitch") {  //checks settings to make sure user wants reminders
        for (index, items) in myMedsList.enumerate() {
            let notification = UILocalNotification()
            notification.fireDate = NSDate(timeIntervalSinceNow: 20)
            notification.alertBody = "Reminder: Take your \(items.name) now!"
            notification.alertAction = "Let's take my meds!"
            notification.soundName = UILocalNotificationDefaultSoundName
            notification.userInfo = ["Med Index": index]
            UIApplication.sharedApplication().scheduleLocalNotification(notification)
        }
    }
}

我是不是在调用函数的地方弄错了?还是代码有问题?值得注意的是,出于测试目的,我将 fireDate 设置为 20 秒,但计划为 myMedsList 数组中的每个项目自定义 fireDate。

您似乎每次都在添加所有通知。您应该只添加之前未添加的通知。如果您不想这样做,可以在再次将它们全部添加回之前调用 cancelAllLocalNotifications()