如果从 Core Data SwiftUI 中删除,则删除本地通知

Delete Local Notification if removed from Core Data SwiftUI

我编写了这个简单的代码来尝试本地通知如何与核心数据一起工作,主要问题是,在添加数据核心项目后,我可以在 60 秒后收到通知,但如果删除它,我仍然会收到通知.当我调用我的 deleteItem 函数时,是否有一个函数可以调用以删除该特定通知?

我的另一个问题是如何设置星期几和时间来触发该通知并且在几秒后不再重复?

内容视图:

import UserNotifications
import SwiftUI
import CoreData

struct ContentView: View {
    //Core Data
    @Environment(\.managedObjectContext) var managedObjectContext
    @FetchRequest(entity: Notifications.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Notifications.date, ascending: false)]) var notifications: FetchedResults<Notifications>
    
    var titles = ["Hello", "Weekend", "Streaming", "ScoobyDoo"]
    var subtitles = ["Hello2", "Weekend2", "Streaming2", "ScoobyDoo2"]
    
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: FavoriteView()) {
                    Text("Favorite View")
                }
                List {
                    ForEach(0 ..< titles.count) {title in
                        HStack {
                            Text(self.titles[title])
                            Image(systemName: "heart")
                                .onTapGesture {
                                    if self.checkItem(title: self.titles[title]) {
                                        do {
                                            try self.deleteItem(title: self.titles[title])
                                            print("title deleted")
                                        } catch {
                                            print(error)
                                        }
                                    } else {
                                        self.addItem(item: self.titles[title])
                                        print("item added")
                                        
                                        // Notification content
                                        let content = UNMutableNotificationContent()
                                        content.title = self.titles[title]
                                        content.subtitle = self.subtitles[title]
                                        content.sound = UNNotificationSound.default
                                        
                                        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
                                        
                                        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
                                        
                                        UNUserNotificationCenter.current().add(request)
                                    }
                            }
                        }
                    }
                }
                
                Button("Request Authorization") {
                    // Ask for notification when app launches
                    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
                        if success {
                            print("All set")
                        } else if let error = error {
                            print(error.localizedDescription)
                        }
                        
                    }
                }
                
                Button("Remove Notifications") {
                    UNUserNotificationCenter.current().removeAllDeliveredNotifications()
                    print("Removed")
                }
            }
        }
    }
    private func checkItem(title: String) -> Bool {
        let request: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Notifications")
        request.predicate = NSPredicate(format: "title == %@", title)
        request.fetchLimit = 1
        var trueFalse = true
        do {
            let count = try managedObjectContext.count(for: request)
            if count == 0 {
                trueFalse = false
            } else {
                trueFalse = true
            }
        } catch {
            print(error)
        }
        return trueFalse
    }
    
    private func deleteItem(title: String) throws {
        let request: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest(entityName: "Notifications")
        request.predicate = NSPredicate(format: "title == %@", title)
        try managedObjectContext.execute(NSBatchDeleteRequest(fetchRequest: request))
        
        saveFavorites()
    }
    func addItem(item: String) {
        let newItem = Notifications(context: managedObjectContext)
        newItem.title = item
        saveFavorites()
    }
    func saveFavorites() {
        do {
            try managedObjectContext.save()
        } catch {
            print(error)
        }
    }
}

最喜欢的视图:

import SwiftUI
import CoreData

struct FavoriteView: View {
    //Core Data
    @Environment(\.managedObjectContext) var managedObjectContext
    @FetchRequest(entity: Notifications.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Notifications.date, ascending: false)]) var notifications: FetchedResults<Notifications>
    
    var body: some View {
        List {
            ForEach(notifications, id: \.self) { item in
                Text(item.title)
            }
        }
    }
}

修改核心数据模型以包含您在添加请求时提供的通知标识符。然后在从核心数据中删除通知时,您可以使用此标识符删除本地通知,如下所示:

UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: [identifier])
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [identifier])