2017-03-08 82 views
1

HI我正在开发一个应用程序,该应用程序能够通知特定的时间和日期,并显示在TableViewController中。所以我在表格中有多个通知。我如何删除特定的通知? 如果我删除包含通知的行,它仍然不会被删除。在swift中删除通知3

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
     let context = getContext() 
     if editingStyle == .delete { 
      // Delete the row from the data source 
      context.delete(names[(indexPath as NSIndexPath).row]) 

      let a = (names[(indexPath as NSIndexPath).row]) 

      let center = UNUserNotificationCenter.current() 
      let notifToDelete = a.name 

      center.getPendingNotificationRequests { (notifications) in 
        print(notifications) 
       for item in notifications { 
        if(item.identifier.contains(notifToDelete!)) 
{ 
    center.removePendingNotificationRequests(withIdentifiers: [item.identifier]) 

    } 
       } 
      } 

      do { 
       try context.save() 
      }catch { 
       let saveError = error as NSError 
       print(saveError) 
      } 
      names.remove(at: (indexPath as NSIndexPath).row) 

      tableView.deleteRows(at: [indexPath], with: .automatic) 

这不会影响任何方式。通知仍在设定的时间运行。 (通知设置在不同的视图控制器中)。

回答

3

删除此块的不必要的代码:

center.getPendingNotificationRequests { (notifications) in 
        print(notifications) 
       for item in notifications { 
        if(item.identifier.contains(notifToDelete!)) 
{ 
    center.removePendingNotificationRequests(withIdentifiers: [item.identifier]) 

    } 
       } 
      } 

相反,这样做:

center.removePendingNotificationRequests(withIdentifiers: [notifToDelete]) 
+0

谢谢!!删除了通知,但删除了上次保存的通知。 –

+0

哦!我想出了我为通知设置的标识符与我给它删除的标识符不同。万分感谢 !! –

+0

不用担心。如果有帮助,请您接受我的回答。 –