【问题标题】:NotificationCenter not trigger when call Quick Action调用快速操作时不触发通知中心
【发布时间】:2018-03-24 16:44:24
【问题描述】:

当在AppDelegate 中调用函数performActionForShortcutItem 时,我在应用程序中实现了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();
}

【问题讨论】:

  • 您的 ViewController 在您发布通知时是否已加载?因为 addObserver 必须在发布之前执行...如果 viewDidLoad 在 performActionForShortcutItem 之前执行,您是否尝试 print()?

标签: ios swift 3dtouch quickaction


【解决方案1】:

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

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

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

【讨论】:

  • 我也是这么想的@Alireza
  • @DennisWeidmann 我在viewDidAppearviewWillAppear 中定义了addObserver,但不能同时使用。
  • @AlirezaTarazani 当然它不会工作,你可以尝试延迟发布直到应用程序处于活动状态或存储一个布尔值作为答案吗??
  • @Sh_Khan 我认为performActionForshortcutItem 运行早于ViewController
  • 是的,这就是您可以通过 print 验证它的想法,您可以在 performActionForshortcutItem 内设置一个标志或延迟发布,但解决方案之一被授予
【解决方案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
        }
    }

【讨论】:

  • 是的,没错,这就是我已经告诉他的答案(投票)
  • @Sh_Khan 谢谢我的朋友,但我想通过NotificationCenter 处理它,我不喜欢使用标志或变量。但没办法!
  • 好吧,NotificationCenter 伴侣无法处理它 :-)
  • 是的,没有 100% 保证它可以被 notificationCenter 正确处理,一种方法是使用 dispatchAfter 来延迟 postNotification 调用,但是你设置的时间可以跨越(或多或少比) viewController 被加载的时间
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-01
  • 2013-01-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多