簡體   English   中英

如果從核心數據 SwiftUI 中刪除,則刪除本地通知

[英]Delete Local Notification if removed from Core Data SwiftUI

我編寫了這個簡單的代碼來嘗試本地通知如何與 Core Data 一起工作,主要問題是,在添加 Data Core 項目后,我可以在 60 秒后收到通知,但如果我刪除它,我仍然會收到它。 當我調用我的 deleteItem function 時,是否有一個 function 可以調用以刪除該特定通知?

我的另一個問題是如何設置一周中的某一天和觸發該通知的時間,而不是在幾秒鍾后重復?

內容視圖:

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)
            }
        }
    }
}

修改核心數據 model 以包含您在添加請求時提供的通知標識符。 然后在從核心數據中刪除通知時,您可以使用此標識符刪除本地通知,如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM