【问题标题】:How do I respond to a tap on a UNUserNotification?如何响应对 UNUserNotification 的点击?
【发布时间】:2017-10-20 03:34:09
【问题描述】:

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

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

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

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

【问题讨论】:

  • launchingOptions 不包含此信息吗?

标签: ios notifications unusernotificationcenter


【解决方案1】:

使用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获取要使用的值。

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    如果您还没有将AppDelegate 设置为UNUserNotificationCenterDelegate,请将以下内容添加到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()
    }
    

    然后,您可以注册该“userNotificationCenterDidReceiveResponse”通知并使用标识符做任何您喜欢的事情。无论您的应用处于何种状态(包括未运行),这都有效。

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

    【讨论】:

    • 嗯!我认为这只有在应用程序在后台运行时才有效。你说得对,这就是我所需要的。谢谢!
    猜你喜欢
    • 2011-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-02
    • 2016-03-20
    • 1970-01-01
    • 2012-01-09
    相关资源
    最近更新 更多