取消并重新安排本地通知(Swift)
我试图以1天(24小时)的时间间隔显示本地通知,并且其工作正常,但是现在我想取消特定date的通知。 我试过(今天)这个,但似乎没有工作。 我的通知仍然出现,这是我已经做了取消通知:
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)
我不知道为什么不能取消通知,有任何遗漏或做错的,请告诉我。
试试这个代码
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; } }
您可以使用通知的userInfo
属性。
例如,如果你这样安排:
notificationID = 1 notification.category = "FIRST_CATEGORY" // other settings... notification.userInfo = ["NotificationID": notificationID]
你可以使用userInfo
来find它:
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 } } }