How do I respond to a tap on a UNUserNotification?

♀尐吖头ヾ 提交于 2019-12-01 07:35:12

问题


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

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


回答1:


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()
}

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.




回答2:


Use UNUserNotificationCenter Delegates.

Use this when app is in foreground:

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

get the values to use from notification

And this when app is in the background:

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

get the values to use from response.

Hope this will help.



来源:https://stackoverflow.com/questions/44079616/how-do-i-respond-to-a-tap-on-a-unusernotification

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!