首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >调用快速操作时不触发NotificationCenter

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

Stack Overflow用户
提问于 2018-03-24 16:44:24
回答 2查看 329关注 0票数 0

AppDelegate中调用函数AppDelegate时,我在应用程序中实现了3D触摸快速动作,内部由NotificationCenter触发,但不工作和调用

我在AppDelegate中的代码

代码语言:javascript
复制
func application(_ application: UIApplication, performActionFor 
shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping 
(Bool) -> Void) {


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

}        

并使用它ViewController

代码语言:javascript
复制
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();
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-03-24 16:47:05

问题是ViewController还没有加载,所以观察者还没有添加到其中。

代码语言:javascript
复制
 NotificationCenter.default.addObserver(self, selector: #selector(BaseViewController.didReceiveNotification), name: Notification.Name("action"), object: nil);

您可以尝试在performActionForshortcutItem中设置一个布尔值,并在viewDidAppear of ViewController中检查它。

票数 2
EN

Stack Overflow用户

发布于 2018-03-24 17:06:34

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

你需要这样做:

在你的AppDelegate里

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

在ViewController中:

代码语言:javascript
复制
override func viewDidLoad() {
        super.viewDidLoad()
        if (UserDefaults.standard.bool(forKey: "openedByShortcutAction")) {
            //Your App has been started by selecting your Shortcut Action
        }
    }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49467277

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档