如何响应UNUserNotification的点击?

我在iOS 10中使用了新的UNUserNotification框架。我可以看到如何添加动作button,但是当用户点击通知本身时该如何响应呢? 就我而言,这将是一个带有一些文字的图像。

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

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

  2. 这些工作,如果我的应用程序在后台运行或closures? UNUserNotification文档build议设置UNUserNotification的代表,但我认为这只适用于应用程序正在运行。

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

 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”通知,并使用标识符进行任何您喜欢的操作。 无论您的应用程序处于何种状态,包括未运行,这都可以工作。

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

使用UNUserNotificationCenter Delegates

当应用程序在前台时使用这个:

- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler

notification获取使用的值

而这个时候的应用程序是在后台:

- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler

response获取使用的值。

希望这会有所帮助。