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

时间:2018-03-26 20:34:04

标签: ios swift swift3 notifications uilocalnotification

我正在做一个安排本地通知并保存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)
}

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

谢谢!

修改

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

3 个答案:

答案 0 :(得分:5)

从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.
    }
}

修改:根据对问题的修改,必须在didFinishLaunching()方法中设置通知中心代理,否则将无法调用上述方法。

UNUserNotificationCenter.current().delegate = self

答案 1 :(得分:0)

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

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
                    {

                    }
            }
}

答案 2 :(得分:-1)

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

您可以在viewDidLoad()

中使用
    UNUserNotificationCenter.current().getDeliveredNotifications { (notification) in

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

    }

我希望这会有所帮助。

相关问题