iOS通知删除上报配置

概述

iOS10之后,通知相关类API被统一,通过UserNotifications.framework来统一管理和使用通知。这里主要说明自定义Action结合SDK实现iOS删除上报数据。

相关类

  • UNNotificationAction(具体action)

  • UNNotificationCategory(action簇集合)

  • UNUserNotificationCenter(通知center)

代码实现

  1. 创建对应action

    /**
     *  创建并注册通知category(iOS 10+)
     */
    - (void)createCustomNotificationCategory {
        // 自定义`action1`和`action2`
        UNNotificationAction *action1 = [UNNotificationAction actionWithIdentifier:UNNotificationDefaultActionIdentifier title:@"普通_进入前台" options: UNNotificationActionOptionForeground];
        UNNotificationAction *action2 = [UNNotificationAction actionWithIdentifier:UNNotificationDismissActionIdentifier title:@"删除" options: UNNotificationActionOptionDestructive];
        // 创建id为`test_category`的category,并注册两个action到category
        // UNNotificationCategoryOptionCustomDismissAction表明可以触发通知的dismiss回调
        UNNotificationCategory *category = [UNNotificationCategory categoryWithIdentifier:@"test_category" actions:@[action1, action2] intentIdentifiers:@[] options:
                                            UNNotificationCategoryOptionCustomDismissAction];
        // 注册category到通知中心
        [self.userNotificationCenter setNotificationCategories:[NSSet setWithObjects:category, nil]];
    }
  2. 通知代理中处理对应action事件

    - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
        NSString *userAction = response.actionIdentifier;
        if ([userAction isEqualToString:UNNotificationDefaultActionIdentifier]) {
            // 处理iOS 10通知,并上报通知打开回执
            [self handleiOS10Notification:response.notification];
        }
        // 通知dismiss,category创建时传入UNNotificationCategoryOptionCustomDismissAction才可以触发
        if ([userAction isEqualToString:UNNotificationDismissActionIdentifier]) {
            //处理用户删除通知上报
        // 阿里云推送SDK 支持删除数据上报
        [CloudPushSDK sendDeleteNotificationAck:response.notification.request.content.userInfo]
        }
        completionHandler();
    }

PayLoad

key: category

value: 客户端注册的category ID(本例子中注册id = ‘test_category’)

{
  "aps":{
    "alert":"自定义Action",
    "sound":"default",
    "badge":1,
    "category":"test_category"
  }
}

注意事项

  • 在注册UNNotificationCategory时,需要使用UNNotificationCategoryOptionCustomDismissAction类型

  • 如果只是单纯监听删除事件,可以注册UNNotificationCategory,创建0个action

  • 通知栏中的全部清除无法监听

自定义action