在Swift 3中删除通知

3

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

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)

这不会有任何影响。通知仍会在设置的时间运行。(该通知是在不同的视图控制器中设置的)。
1个回答

8

请移除这段不必要的代码块:

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

  }
                }
            }

相反,做这个:
center.removePendingNotificationRequests(withIdentifiers: [notifToDelete])

谢谢!删除了通知,但它也会删除最后保存的通知。 - ASJ_14
哦!!我弄明白了,我为通知设置的标识符与我用于删除它的标识符不同。非常感谢!! - ASJ_14
没问题。如果我的回答有帮助的话,您能否接受一下呢? - The Mach System
是的,它有帮助!做到了! - ASJ_14
没问题。干杯。 - The Mach System

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接