问题
I'm trying to show a local notification with a time interval of 1 day (24 hours) and its working fine but now I want to cancel notification for a specific day. I tried(today) this but it didn't seem to work. My notification is still appearing this is what I have done for cancelling the notification:
let appNotification = appDelegate!.notification
UIApplication.sharedApplication().cancelLocalNotification(appNotification)
This is how am scheduling the notification in 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)
I don't know why am not able to cancel the notification there's anything that is missing or doing wrong, please let me know.
回答1:
Try this code
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;
}
}
回答2:
You could use the notification's userInfo
property.
For example, if you schedule it like this:
notificationID = 1
notification.category = "FIRST_CATEGORY"
// other settings...
notification.userInfo = ["NotificationID": notificationID]
You can use userInfo
to find it:
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
}
}
}
来源:https://stackoverflow.com/questions/37224367/cancel-and-reschedule-a-local-notificationswift