2016-05-14 59 views
0

我試圖以1天(24小時)的時間間隔顯示本地通知,它的工作正常,但現在我想取消特定日期的通知。我試過(今天),但它似乎沒有工作。我的通知仍出現,這是我已經取消通知完成:取消並重新安排本地通知(Swift)

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) 

我不知道爲什麼我不能取消通知有任何缺少或做錯的,請讓我知道。

回答

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; 
    } 
} 
+0

感謝您迴應:),但問題是我沒有這麼多通知我有一個單一的通知,這是每天重複自己,所以fireDate是一個單一的日期,所以使用你的解決方案將無法正常工作,如果我錯了@Madhumitha –

+0

它取消本地通知,但不取消自定義聲音它連續播放大約3到4秒。 –

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 
    } 
    } 
}