I am able to open a specific view (ToDoView) when I use categories with actions for my notification.
But what I would like to achieve is that a specific view gets also opened when I click on the notification itself.
Maybe this is super simple to solve, but I couldn't find out yet using SwiftUI.
By the way: This code only works if the app still runs in the background, otherwise i land at ContentView, which is also not optimal.
AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
UNUserNotificationCenter.current().delegate = self
return true
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
if response.actionIdentifier == "open" {
NotificationCenter.default.post(name: NSNotification.Name("ToDoView"), object: nil)
}
}
NotificationManager.swift
func scheduleNotifications() -> Void {
for notification in notifications {
let content = UNMutableNotificationContent()
content.title = notification.title
var dateComponents = DateComponents()
dateComponents.hour = 18
dateComponents.minute = 10
dateComponents.weekday = notification.weekday
let open = UNNotificationAction(identifier: "open", title: "Notizen ?ffnen", options: .foreground)
let cancel = UNNotificationAction(identifier: "cancel", title: "Schlie?en", options: .destructive)
let categories = UNNotificationCategory(identifier: "action", actions: [open,cancel], intentIdentifiers: [])
UNUserNotificationCenter.current().setNotificationCategories([categories])
content.categoryIdentifier = "action"
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: notification.id, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
guard error == nil else { return }
print("Benachrichtigung mit folgender ID eingerichtet: (notification.id)")
}
ContentView.swift
.....
.onAppear {
NotificationCenter.default.addObserver(forName: NSNotification.Name("ToDoView"), object: nil, queue: .main) { (_) in
self.showToDo = true
} }
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…