调用快速操作时NotificationCenter不会触发

时间:2018-03-24 16:44:25

标签: ios swift 3dtouch quickaction

我在performActionForShortcutItem中调用函数AppDelegate时在app中实现了3D Touch Quick Action,我在其中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();
}

2 个答案:

答案 0 :(得分:2)

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

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

您可以尝试在performActionForshortcutItem内设置一个布尔值,并在ViewController

的viewDidAppear内查看

答案 1 :(得分:2)

你的问题就像Sh_Khan所说,你不能在AppDelegate上发布一个ViewController,因为此时你的ViewController没有订阅Notification ...

你需要做这样的事情:

在你的AppDelegate

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

在ViewController中:

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