Откройте указанный c вид при открытии приложения через уведомление - PullRequest
1 голос
/ 19 февраля 2020

Я могу открыть определенный c вид (ToDoView), когда я использую категории с действиями для моего уведомления. Но чего бы я хотел добиться, так это того, чтобы при открытии самого уведомления открывалось также c представление. Возможно, это очень просто решить, но я пока не могу выяснить, используя 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)")
        }

ContentView .swift

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

1 Ответ

1 голос
/ 21 февраля 2020

Кстати: этот код работает, только если приложение все еще работает в фоновом режиме,

Вместо .onAppear в ContentView используйте подписку для издателя, как показано ниже

1) Объявить издателя

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

2) Добавить подписчика (в том месте, куда вы добавили .onAppear и вместо него)

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

это будет работать до тех пор, пока ContentView существует.

...