取消并重新安排本地通知(Swift)

时间:2016-05-14 08:19:27

标签: ios swift2 uilocalnotification

我正在尝试显示本地通知,时间间隔为1天(24小时)且工作正常,但现在我想取消特定日期的通知。我试过(今天)这个,但它似乎没有用。我的通知仍然显示这是我为取消通知所做的工作:

let appNotification = appDelegate!.notification

UIApplication.sharedApplication().cancelLocalNotification(appNotification)

这是我在appDelegate中安排通知的方式:

//scheduling notification

dateComp.year = 2015;
dateComp.month = 01;
dateComp.day = 20;
dateComp.hour = 21;
dateComp.minute = 05;
dateComp.timeZone = NSTimeZone.systemTimeZone()

notification.category = "FIRST_CATEGORY"
notification.alertBody = "my daily notiification ?"
notification.soundName = UILocalNotificationDefaultSoundName
notification.fireDate  = finalFireDate
notification.repeatInterval = NSCalendarUnit.Day

let dateNow = NSDate()
let noticalendar = NSCalendar.currentCalendar()
let hour = calendar.component(NSCalendarUnit.Hour, fromDate: dateNow)
UIApplication.sharedApplication().scheduleLocalNotification(notification)

我不知道为什么我们无法取消通知中有任何遗漏或错误的通知,请告诉我。

2 个答案:

答案 0 :(得分:7)

试试此代码

var app:UIApplication = UIApplication.sharedApplication()
for oneEvent in app.scheduledLocalNotifications! {
    var notification = oneEvent as UILocalNotification
    if notification.fireDate == "your date" {
        //Cancelling local notification
        app.cancelLocalNotification(notification)
        break;
    }
}

答案 1 :(得分:4)

您可以使用通知的userInfo属性。

例如,如果您按照以下方式安排:

notificationID = 1
notification.category = "FIRST_CATEGORY"
// other settings...
notification.userInfo = ["NotificationID": notificationID]

您可以使用userInfo找到它:

let application = UIApplication.sharedApplication()
let scheduledNotifications = application.scheduledLocalNotifications!

for notification in scheduledNotifications {
  if let nID = notification.userInfo?["NotificationID"] as? Int {
    if nID == appDelegate!.notificationID {
      application.cancelLocalNotification(notification)
      break
    }
  }
}