这样应该可以吧?
import SwiftUI
import UserNotifications
class NotificationManager {
static let shared = NotificationManager()
func scheduleNotification(for item: Item) {
let notificationId = String(item.id.hashValue)
let content = UNMutableNotificationContent()
content.title = "Items"
content.body = "Itemize the items"
content.sound = .default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: notificationId, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Failed to schedule notification: \(error.localizedDescription)")
}
}
}
func removeNotification(for item: Item) {
let notificationId = String(item.id.hashValue)
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [notificationId])
}
}
hashValue
不稳定,并且会在应用程序的执行之间发生变化。来自
hashValue 文档:
不保证不同执行的哈希值相等 你的程序的。不要保存哈希值以供将来使用 执行。目前最好的解决方案似乎是在我的模型中存储一个 notificationId ,恕我直言,这看起来确实比从 id 中提取 UUID 的黑客扩展更干净。