如何检测应用是否通过视图控制器中的通知操作打开



>我正在开发一个通知应用程序,想知道是否可以检测该应用程序是否是从ViewController.Swift中的通知操作而不是AppDelegate.swift中打开的。我该怎么做?

Krish,每当启动应用程序时,都会调用AppDelegate(如果未修改默认Main类(,并且在AppDelegate类中,您可以在启动选项委托中检查启动选项是否通过远程通知打开。这是您将捕获应用程序打开事件的第一个操作。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let remoteNotif = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary
if remoteNotif != nil {
let notifName = remoteNotif?["aps"] as! String
print("Notification: (notifName )")
}
else {
print("Not remote")
}
}

这是一个完整而简单的答案

在 AppDelegate 上处理事件后,您可以使用观察器让您的 ViewController 了解该事件。 通常,应将用户重定向到特定视图,具体取决于通知有效负载。

最新更新