问题
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
} }
回答1:
By the way: This code only works if the app still runs in the background,
Instead of .onAppear
in ContentView
use subscription to publisher, like below
1) Declare publisher
struct ContentView: View {
let todoPublisher = NotificationCenter.default.publisher(for: NSNotification.Name("ToDoView"))
...
2) Add subscriber (in the place you added .onAppear
and instead of it)
.onReceive(todoPublisher) { notification in
self.showToDo = true
}
this will work as long as ContentView
exists.
来源:https://stackoverflow.com/questions/60306123/open-a-specific-view-when-opening-the-app-through-a-notification