当应用关闭时用户点击通知时如何获取userInfo

Raf*_*nço 7 notifications ios uilocalnotification swift swift3

我正在做一个安排本地通知并保存userInfo的应用程序.这是好的一部分.

但是当app关闭时,会出现Notification,但是当用户单击时,该方法不会被调用,我无法处理userInfo.

我看到有一种新的方式来接收通知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)
}
Run Code Online (Sandbox Code Playgroud)

有人帮我吗?我在这里看到了所有相关的问题,但没有发现任何问题.

谢谢!

编辑:

如果有人正在寻找一个解决方案,我说UNUserNotificationCenter.current().delegate = selfdidFinishLaunchingWithOptions和它的工作.

Chr*_*ris 6

从iOS 10开始,无论应用是从后台打开还是处于非活动状态,都应调用您提到的方法。也许您没有正确访问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.
    }
}
Run Code Online (Sandbox Code Playgroud)

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

UNUserNotificationCenter.current().delegate = self
Run Code Online (Sandbox Code Playgroud)

  • 我尝试过这个,但对我不起作用。当应用程序关闭时,启动时我无法获取用户信息(触摸通知)。 (2认同)