通过通知打开应用程序时打开特定视图

时间:2020-02-19 17:31:58

标签: ios swift push-notification notifications swiftui

当我在通知中使用带有操作的类别时,可以打开特定的视图(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)")
        }

ContentView.swift

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

1 个答案:

答案 0 :(得分:1)

顺便说一句:仅当应用仍在 背景,

代替$/中的-0使用对发布者的订阅,如下所示

1)声明发布者

#!/bin/perl

use warnings;
use strict;

use File::Slurp;
use Data::Dumper;

my $data = read_file($ARGV[0]);

my %modules = $data =~ /module (\w+)\((.+?)\);/sg;

$modules{$_} = [split(/\s*,\s*/, $modules{$_})] for keys(%modules);

print Dumper(\%modules);

2)添加订户(在您添加.onAppear的地方代替它)

ContentView

只要存在struct ContentView: View { let todoPublisher = NotificationCenter.default.publisher(for: NSNotification.Name("ToDoView")) ... ,它就会起作用。