我在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();
}
答案 0 :(得分:2)
问题是ViewController
尚未加载,因此观察者尚未添加
NotificationCenter.default.addObserver(self, selector: #selector(BaseViewController.didReceiveNotification), name: Notification.Name("action"), object: nil);
您可以尝试在performActionForshortcutItem
内设置一个布尔值,并在ViewController
答案 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
}
}