在AppDelegate中调用函数AppDelegate时,我在应用程序中实现了3D触摸快速动作,内部由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();
}发布于 2018-03-24 16:47:05
问题是ViewController还没有加载,所以观察者还没有添加到其中。
NotificationCenter.default.addObserver(self, selector: #selector(BaseViewController.didReceiveNotification), name: Notification.Name("action"), object: nil);您可以尝试在performActionForshortcutItem中设置一个布尔值,并在viewDidAppear of ViewController中检查它。
发布于 2018-03-24 17:06:34
您的问题就像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()
}在ViewController中:
override func viewDidLoad() {
super.viewDidLoad()
if (UserDefaults.standard.bool(forKey: "openedByShortcutAction")) {
//Your App has been started by selecting your Shortcut Action
}
}https://stackoverflow.com/questions/49467277
复制相似问题