点击通知栏时,应用程序关闭后如何访问userInfo?

3

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

但是当应用程序关闭时,如果出现通知并且用户单击,则该方法不会被调用,我无法处理用户信息。

我看到有一种使用UNUserNotificationCenter 接收通知的新方法。但也不能正常工作。

我尝试了以下方法,但没有成功:

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

这是我在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
        // Handle your data here, pass it to a view controller etc.

}

有人能帮我吗?我看了所有相关的问题,但没有找到任何有用的答案。


为什么在didReceive方法中创建新的UILocalNotification()实例? 什么是applicationWorker?你能展示一下applicationWorker和它的manage()方法的代码吗? - Anton Novoselov
@AntonNovoselov,感谢您的回复,但是该方法的实现并不是重点。问题在于当应用程序通过通知启动时,此功能未被调用。 - Roberto Pinheiro
@AntonNovoselov,问题是,当我通过点击通知打开应用程序时,如何调用函数。感谢您的帮助! - Roberto Pinheiro
检查我的答案 - 检查您是否已注册通知。 - Anton Novoselov
1个回答

0

您是否已注册通知? 如果没有,请将以下内容添加到AppDelegate didFinishLaunchingWithOptions中:

// Register Notifications
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: { granted, error in

            if granted {
                print("User notifications are allowed")
            } else {
                print("User notifications are NOT allowed")
            }
        })
        UNUserNotificationCenter.current().delegate = self

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接