不显示基于自定义数据的远程通知

Do not display a remote notification based on custom data

我想让用户选择 enable/disable 某些类型的通知。例如,打开私人消息的推送通知,但关闭 public 个帖子。我想知道是否可以在收到 APN 后在客户端执行此操作(在 didReceiveRemoteNotification 中),我不确定在调用 didReceiveRemoteNotification 之前通知是否已经显示。

目前我正在使用 OneSignal 发送推送通知,并且发送内容可用为真 (1)。这会在应用程序处于后台时正确触发 didReceiveRemoteNotification。根据我发送的数据,我想显示或不显示任何横幅推送通知。

这是我到目前为止所做的尝试,我能够获得我需要的数据,但我一直无法弄清楚如何告诉 iDevice 根本不显示它:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    print("****this happened****")
    print("\(userInfo)")
    if let customData = userInfo["custom"] as? [String: Any] {
        if let additionalData = customData["a"] as? [String: Any] {
            if let notificationType = additionalData["notification_type"] as? String {
                if notificationType == "follow" {
                    print("do not want to display")
                    if var apsData = userInfo["aps"] as? [String: Any] {
                        apsData.removeValue(forKey: "content-available")
                    }
                } else {
                    print("dispaying this notification")
                }
            }
        }
    }
}

我想到的另一种方法是将用户的通知设置存储到我的数据库中,当用户发送推送通知时检查这些设置,看看他们是否应该发送推送。我只是想看看是否可以在不添加更多数据库查询的情况下解决这个问题。

编辑:我也使用 OneSignal.initWithLaunchOptions 并注意到它在 handleNotificationReceived 中的 didReceiveRemoteNotification 之前被调用,我想知道是否可以在这里停止推送通知

if receivedNotification?.payload != nil {
     if receivedNotification?.payload.additionalData != nil {
         if let data = receivedNotification?.payload.additionalData["notification_type"] as? String {
             if data == "follow" {
                print("do not display this")
             }
         }
     }
 }

相反,我建议在您的服务器上进行过滤,因为向所有设备发送通知(只是为了忽略它们的显示)有缺点,包括:当用户滑动离开应用程序时,额外的电池消耗和 content-available 通知将不起作用。

您可以使用 mutable-content 代替,这会触发您的 UNNotificationServiceExtension 但这仅适用于 iOS 10,您仍然需要考虑电池。

您可以通过调用 IdsAvailable where you can store this on your back end. Then you can then use include_player_ids on the create notification REST API call 获取设备的 OneSignal 播放器 ID,以仅定位应接收通知的用户。