如何在Appdelegate中获取已传递的通知详细信息

时间:2018-11-07 04:07:11

标签: ios swift notifications appdelegate

我已经设法通过点击通知来打开应用程序时获取通知详细信息,但是如果用户仅通过单击应用程序图标来打开应用程序,是否有任何方法可以在应用程序内部获取传递的通知详细信息

func applicationWillResignActive(_ application: UIApplication) {

        if #available(iOS 10.0, *) {

            let center = UNUserNotificationCenter.current()
            center.getDeliveredNotifications { (notification) in
                print(notification.count) 

            }

        } else {
            // Fallback on earlier versions
        }

    }

在这里,我得到了通知计数,但是我没有从这里获取通知的详细信息(用户信息)

2 个答案:

答案 0 :(得分:1)

如果您的应用被强行关闭(滑动)并且用户单击通知打开应用,您仍然可以通过AppDelegate didFinishLaunchingWithOptions方法获取此信息:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.

    if let userInfo = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [String: AnyObject]{
        //Here you can use the notification payload information.
    }

    return true
}

答案 1 :(得分:0)

我找到了答案

func applicationDidBecomeActive(_ application: UIApplication) {
        if #available(iOS 10.0, *) {

            let center = UNUserNotificationCenter.current()


            center.getDeliveredNotifications { (receivedNotifications) in


                for notification in receivedNotifications {
                    let content = notification.request.content
                    print(" Body \(content.body)")
                    print(" Title \(content.title)")
                    print(content.userInfo as NSDictionary)

                    self.session.saveCallRequest(content.userInfo as NSDictionary)

                }

            }
    }