取消本地通知

Cancel local notification

我想列出预定的本地通知以检查触发日期,取消好的通知。

这就是我添加本地通知的方式:

let notification = UILocalNotification()
notification.fireDate = date
notification.alertBody = message
notification.soundName = UILocalNotificationDefaultSoundName
notification.timeZone = NSTimeZone.defaultTimeZone()

这就是我列出所有通知以找到合适通知的方式:

for oneEvent in UIApplication.sharedApplication().scheduledLocalNotifications! {
    if date == notification.fireDate {
        app.cancelLocalNotification(notification)
    }
}

问题是我创建了很多通知,但 scheduledLocalNotifications 中总是只有一个通知!

通知已正确触发,但我无法检索它们是 scheduledLocalNotifications 变量。

我没听懂你的问题,但我对下面的代码有一些疑问试试这个:

您必须在创建通知后写下这一行。

UIApplication.sharedApplication().scheduleLocalNotification(notification)

然后

for oneEvent in UIApplication.sharedApplication().scheduledLocalNotifications! {
    if date == oneEvent.fireDate {
         app.cancelLocalNotification(oneEvent)
    }
}

如果您使用的是 ios10,您可以尝试导入 UserNotifications 框架 (UserNotifications.framework),然后

let center = UNUserNotificationCenter.current()
center.getPendingNotificationRequests(...)

在IOS10中,Apple迁移到新的Notification框架,您仍然可以使用旧方法(sharedApplication.scheduleLocalNotification)创建和安排本地通知,但是处理它们时会有奇怪的行为旧方法 (UIApplication.sharedApplication().scheduledLocalNotifications).