NotificationCenter not trigger when call Quick Action

469 Views Asked by At

I implemented 3D Touch Quick Action in app when call function performActionForShortcutItem in AppDelegate, I triggering by NotificationCenter inside it but not work and call

my Code in AppDelegate:

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


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

}        

and used it 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();
}
2

There are 2 best solutions below

6
Shehata Gamal On BEST ANSWER

The problem is that ViewController is not yet loaded so the observer is not yet add to it

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

you can try to set a boolean value insideperformActionForshortcutItem and check it inside viewDidAppear of ViewController

4
Dennis Weidmann On

Your Problem is like Sh_Khan said, that you can't post on AppDelegate to a ViewController, because at this time your ViewController didn't subscribe to the Notification...

You need to do something like this:

In your AppDelegate

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

In your ViewController:

override func viewDidLoad() {
        super.viewDidLoad()
        if (UserDefaults.standard.bool(forKey: "openedByShortcutAction")) {
            //Your App has been started by selecting your Shortcut Action
        }
    }