我有一个输入供用户设置通知。它工作正常,并且在输入日期被触发,但是由于用户能够从表视图中删除特定的通知,因此我需要添加一个函数来删除具有特定标识符的通知。
我的方法是设置一个动态标识符,该标识符随每个输入而变化。可以,但是混合了要删除的通知-我认为这是因为在每个添加的通知之后,都会对数组进行排序。谁能找到一种可行的方法,还是有更好的方法?
我的方法:
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)
}
}
答案 0 :(得分:1)
我想我想出了一种解决方法。我仅将id
添加到该结构中。每增加一个通知,此id
就会增加1。通知标识符为id
,当选择删除通知时,将获取id
,并删除通知。
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)
}
}