Search code examples
iosswift3dtouchquickaction

NotificationCenter not trigger when call Quick Action


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();
}

Solution

  • 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