首页 > 解决方案 > 通过 Notification 打开 App 时打开特定视图

问题描述

当我将类别与操作一起用于通知时,我能够打开特定视图 (ToDoView)。但我想要实现的是,当我点击通知本身时,也会打开一个特定的视图。也许这很容易解决,但我还没有找到使用 SwiftUI 的方法。

顺便说一句:此代码仅在应用程序仍在后台运行时才有效,否则我会进入 ContentView,这也不是最佳的。

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

内容视图.swift

.....
                  .onAppear {
                NotificationCenter.default.addObserver(forName: NSNotification.Name("ToDoView"), object: nil, queue: .main) { (_) in
                    self.showToDo = true
                } }

标签: iosswiftpush-notificationnotificationsswiftui

解决方案


顺便说一句:此代码仅在应用程序仍在后台运行时才有效,

而不是.onAppearContentView使用中订阅发布者,如下所示

1) 声明发布者

struct ContentView: View {
    let todoPublisher = NotificationCenter.default.publisher(for: NSNotification.Name("ToDoView"))
    ...

2)添加订阅者(在您添加的地方.onAppear而不是它)

.onReceive(todoPublisher) { notification in
   self.showToDo = true
}

只要ContentView存在,这将起作用。


推荐阅读