如何回应UNUserNotification?

Bil*_*ill 2 notifications ios unusernotificationcenter

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

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

  1. 我是否可以使用自定义代码来检测我的应用程序是否因为UNUserNotification点击而被打开,理想情况下是否有关于通知的标识符信息?

  2. 如果我的应用程序在后台运行或关闭,它们会工作吗?UNUserNotification文档建议设置委托UNUserNotificationCenter,但我认为只有在应用程序运行时才有效.

mmd*_*080 6

设置AppDelegateUNUserNotificationCenterDelegate,如果你还没有,添加以下的didReceive方法:

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()
}
Run Code Online (Sandbox Code Playgroud)

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

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