2

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

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

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

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

4

2 回答 2

7

如果您还没有设置AppDelegate为,则将以下内容添加到方法中:UNUserNotificationCenterDelegatedidReceive

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”通知并使用标识符做任何您喜欢的事情。无论您的应用处于何种状态(包括未运行),这都有效。

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

于 2017-05-23T18:45:53.373 回答
2

使用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

希望这会有所帮助。

于 2017-05-25T12:03:40.090 回答