如何在应用关闭时用户单击通知时获取用户信息?

How to get userInfo when user click in notification when app is closed?

我正在做一个安排本地通知并保存用户信息的应用程序。这部分没问题。

但是当应用程序关闭时,通知出现,但是当用户点击时,该方法没有被调用,我无法处理用户信息。

我看到 UNUserNotificationCenter 有一种接收通知的新方法。但是也不行。

这是我在 AppDelegate 中的实现:

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    let lNotification = UILocalNotification()
    lNotification.userInfo = response.notification.request.content.userInfo

    applicationWorker.manage(localNotification: lNotification)
}

有人帮帮我吗?我在这里看到了所有相关的问题,但没有找到任何东西。

谢谢!

编辑:

如果有人正在寻找解决方案,我在 didFinishLaunchingWithOptions 中添加了 UNUserNotificationCenter.current().delegate = self,它奏效了。

从iOS10开始,无论应用程序是从后台打开还是非活动状态,都应该调用您提到的方法。也许您没有正确访问 userInfo。下面的例子对我有用。

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

    let userInfo = response.notification.request.content.userInfo
    if let yourData = userInfo["yourKey"] as? String {
        // Handle your data here, pass it to a view controller etc.
    }
}

Edit:根据对问题的编辑,必须在 didFinishLaunching() 方法中设置通知中心委托,否则不会调用上述方法。

UNUserNotificationCenter.current().delegate = self

当应用程序从通知中打开时,您可以从启动选项中获取通知用户信息。这是代码

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

   if let notification = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [String: AnyObject] {
                if let aps = notification["aps"] as? NSDictionary
                    {

                    }
            }
}

使用UNUserNotificationCenter.current().getDeliveredNotifications 获取通知。

您可以在 viewDidLoad() 中使用

    UNUserNotificationCenter.current().getDeliveredNotifications { (notification) in

        if notification.count > 0 {
            //your code
        }

    }

希望对您有所帮助。