我如何响应点击UNUserNotification? [英] How do I respond to a tap on a UNUserNotification?

查看:181
本文介绍了我如何响应点击UNUserNotification?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在iOS 10中使用新的UNUserNotification框架.我可以看到如何添加操作按钮,但是当用户点击通知本身时如何响应?就我而言,它将是带有一些文本的图像.

I'm using the new UNUserNotification framework in iOS 10. I can see how to add action buttons, but how do I respond when the user taps the notification itself? In my case, it will be an image with some text.

默认行为是打开应用程序.

The default behavior is that the application opens.

  1. 我可以使用自定义代码来检测是否由于UNUserNotification点击而打开了我的应用程序,并且理想情况下还包含有关所窃听通知的标识符信息?

  1. Can I have custom code that detects if my application is being opened because of a UNUserNotification tap, and ideally with identifier information about the notification tapped?

如果我的应用程序在后台运行或关闭,这些功能可以工作吗? UNUserNotification文档建议设置UNUserNotificationCenter的委托,但是我认为这仅在应用程序正在运行时有效.

Will these work if my app is running in the background or closed? UNUserNotification documentation suggests setting the delegate of UNUserNotificationCenter, but I think this only works if the app is running.

推荐答案

如果尚未将AppDelegate设置为UNUserNotificationCenterDelegate,则将以下内容添加到didReceive方法中:

Set AppDelegate to be UNUserNotificationCenterDelegate if you haven't already and add the following to the didReceive method:

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

    let userInfo = ["identifier":response.notification.request.identifier]
    NotificationCenter.default.post(name: Notification.Name(rawValue: "userNotificationCenterDidReceiveResponse"), object: self, userInfo: userInfo)

    completionHandler()
}

然后,您可以注册该"userNotificationCenterDidReceiveResponse"通知,并使用标识符执行任何操作.无论您的应用处于什么状态(包括未运行),此方法都有效.

You can then register for that "userNotificationCenterDidReceiveResponse" notification and do whatever you like with the identifier. This works no matter what state your app is in, including not running.

如果不清楚,我可以上传示例项目.

If this isn't clear enough I can upload a sample project.

这篇关于我如何响应点击UNUserNotification?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆