我正在安排使用唯一标识符的通知,因此我不必为每个通知创建一个新的字符串。这一切都适用于调度,但问题在于尝试取消它们。
这是我安排通知的代码......
foreach ($fighters1 as $fighter) {
foreach ($fighters2 as $fighter2) {
}
}
这是取消通知的代码......
let notifIdentifier = TaskManager.notification2.userInfo.description as String!
let trigger = UNCalendarNotificationTrigger(dateMatching: components , repeats: true)
let request = UNNotificationRequest(identifier: notifIdentifier! , content: TaskManager.notification2, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
当我试图取消它们时,它们非常受欢迎。我已经通过将标识符更改为常规字符串来测试代码,并且所有内容都应该正常运行,因此它绝对是唯一标识符。
有关为每个新任务/通知创建唯一ID的任何想法/建议吗?
答案 0 :(得分:0)
安排通知
@IBAction func scheduleNotification(_ sender: AnyObject) {
let uuid = UUID().uuidString
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Example", arguments: nil)
content.sound = UNNotificationSound.default()
//...
var dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: self.datePicker.date)
dateComponents.second = 0
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let request = UNNotificationRequest(identifier: uuid, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error) in
if let errorPerforms = error {
print(errorPerforms.localizedDescription)
} else {
print("Success")
}
}
let managedObject = ManagedObject(context: self.managedObjectContext!)
managedObject.setValue(uuid, forKey: "uuid")
//...
do {
try self.managedObjectContext.save()
self.dimiss()
} catch {}
}
从indexPath
删除通知。
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
switch editingStyle {
case .delete:
let managedObject = self.fetchedResultsController.object(at: indexPath)
self.managedObjectContext.delete(managedObject)
let center = UNUserNotificationCenter.current()
center.removeDeliveredNotifications(withIdentifiers: [managedObject.uuid!])
center.removePendingNotificationRequests(withIdentifiers: [managedObject.uuid!])
do {
try self.managedObjectContext.save()
self.tableView.reloadData()
} catch {}
default:
break
}
}
这很好用!当您使用NSFetchedResultsControllerDelegate
协议方法时。希望它有所帮助