我已获得用户设置通知的输入。它工作正常并且在输入日期被触发,但由于用户能够从 TableView 中删除特定通知,我需要添加一个函数来删除具有特定标识符的通知。
我的方法是设置一个随每次输入而变化的动态标识符。它有点工作,但它混淆了要删除的通知 - 我认为这是因为在每次添加通知之后,都会对数组进行排序。任何人都可以找到一种方法来实现这一点,或者有更好的方法吗?
我的方法:
func setAlert() {
let content = UNMutableNotificationContent()
content.title = notifTitle.text!
content.body = notifDescribtion.text!
content.badge = 1
let date = datePicker.date
let triggerDate = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)
let request = UNNotificationRequest(identifier: String(notStructArray.count), content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == .delete) {
notStructArray.remove(at: indexPath.item)
defaults.set(try? PropertyListEncoder().encode(notStructArray), forKey: "notStructArray")
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [String(indexPath.item)])
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
最佳答案
我想我找到了解决这个问题的方法。我只是将 id
添加到结构中。每添加一个通知,这个 id
就会增加一个。 The notifications identifier is this id
and when a notification is selected to be deleted, the id
is being fetched and the notification removed.
func createStructArray() {
notId += 1
defaults.set(notId, forKey: "notId")
let notificationData: not = not(title: notifTitle.text!, desc: notifDescribtion.text!, date: datePicker.date, type: notificationType, id: notId)
notStructArray.append(notificationData)
notStructArray.sort(by: { $0.date < $1.date })
}
func setAlert() {
let content = UNMutableNotificationContent()
content.title = notifTitle.text!
content.body = notifDescribtion.text!
content.badge = 1
let date = datePicker.date
let triggerDate = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)
let request = UNNotificationRequest(identifier: String(notId), content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == .delete) {
let array = notStructArray[indexPath.item]
let id = array.id
notStructArray.remove(at: indexPath.item)
defaults.set(try? PropertyListEncoder().encode(notStructArray), forKey: "notStructArray")
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [String(id)])
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
关于ios - Swift - 删除带有动态标识符的通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55894348/