0

performActionForShortcutItem我在调用函数时在应用程序中实现了 3D Touch Quick Action AppDelegate,我在其中触发NotificationCenter但不工作并调用

我的代码AppDelegate

func application(_ application: UIApplication, performActionFor 
shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping 
(Bool) -> Void) {


    NotificationCenter.default.post(name: Notification.Name("action"), object: nil);

}        

并使用它ViewController

override func viewDidLoad() {
    super.viewDidLoad();


    NotificationCenter.default.addObserver(self, selector: #selector(BaseViewController.didReceiveNotification), name: Notification.Name("action"), object: nil);
}

func didReceiveNotification() {
    let alert = UIAlert(viewController: self);
    alert.content = "NotificationCenter Worked";
    alert.title = "NotificationCenter here!!";
    alert.show();
}
4

2 回答 2

2

问题是ViewController 尚未加载,因此尚未添加观察者

 NotificationCenter.default.addObserver(self, selector: #selector(BaseViewController.didReceiveNotification), name: Notification.Name("action"), object: nil);

您可以尝试在内部设置一个布尔值performActionForshortcutItem并在 viewDidAppear 的内部检查它ViewController

于 2018-03-24T16:47:05.190 回答
2

你的问题就像 Sh_Khan 说的那样,你不能在 AppDelegate 上发布到 ViewController,因为此时你的 ViewController 没有订阅通知......

你需要做这样的事情:

在你的 AppDelegate

    func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping(Bool) -> Void) {
            UserDefaults.standard.set(true, forKey: "openedByShortcutAction")
            UserDefaults.standard.synchronize()
        }

在您的视图控制器中:

override func viewDidLoad() {
        super.viewDidLoad()
        if (UserDefaults.standard.bool(forKey: "openedByShortcutAction")) {
            //Your App has been started by selecting your Shortcut Action
        }
    }
于 2018-03-24T17:06:34.770 回答