如何在Objective-C中设置多组通知操作按钮分类?
如何为iOS本地通知添加多组操作按钮分类
要添加多组通知分类,只需创建多个UNNotificationCategory实例,将它们全部放入集合后设置给通知中心即可,具体实现步骤如下:
- 为每组分类创建对应的操作按钮(
UNNotificationAction) - 用唯一标识符创建多个
UNNotificationCategory实例,每个实例关联专属的操作按钮数组 - 将所有分类实例存入
NSSet(官方推荐使用集合,避免重复) - 调用通知中心的
setNotificationCategories:方法完成全局设置
示例代码
// 第一组:提醒类通知的操作按钮 UNNotificationAction *snoozeAction = [UNNotificationAction actionWithIdentifier:@"Snooze" title:@"稍后提醒" options:UNNotificationActionOptionNone]; UNNotificationAction *deleteAction = [UNNotificationAction actionWithIdentifier:@"Delete" title:@"删除" options:UNNotificationActionOptionDestructive]; // 创建第一组分类 UNNotificationCategory *reminderCategory = [UNNotificationCategory categoryWithIdentifier:@"UYLReminderCategory" actions:@[snoozeAction, deleteAction] intentIdentifiers:@[] options:UNNotificationCategoryOptionNone]; // 第二组:消息类通知的操作按钮 UNNotificationAction *replyAction = [UNNotificationAction actionWithIdentifier:@"Reply" title:@"回复" options:UNNotificationActionOptionForeground]; UNNotificationAction *markAsReadAction = [UNNotificationAction actionWithIdentifier:@"MarkAsRead" title:@"标记已读" options:UNNotificationActionOptionNone]; // 创建第二组分类 UNNotificationCategory *messageCategory = [UNNotificationCategory categoryWithIdentifier:@"UYLMessageCategory" actions:@[replyAction, markAsReadAction] intentIdentifiers:@[] options:UNNotificationCategoryOptionNone]; // 将多组分类存入集合 NSSet *categories = [NSSet setWithObjects:reminderCategory, messageCategory, nil]; // 全局设置通知分类 [center setNotificationCategories:categories];
关键注意点
- 每个
UNNotificationCategory必须配置唯一标识符,后续发送通知时需通过该标识符关联对应分类 - 不同分类可绑定完全不同的操作按钮组合,适配不同业务场景的通知交互需求
- 通知弹出时,系统会根据通知的
categoryIdentifier字段自动匹配对应的操作按钮组
内容的提问来源于stack exchange,提问作者Terry Windwalker
相关产品推荐
相关产品推荐

