七、定义通知模板UNNotificationCategory
聊天类软件在iOS系统中,常常采用后台推送的方式推送新消息,用户可以在不进入应用程序的情况下,直接在左面回复通知推送过来的信息,这种功能就是通过UNNotificationCategory模板与UNNotificationAction用户活动来实现的。关于文本回复框,UserNotification框架中提供了UNTextInputNotificationAction类,其是UNNotificationAction的子类。示例代码如下:
//创建用户活动
/*
options参数可选如下:
//需要在解开锁屏下使用
UNNotificationActionOptionAuthenticationRequired
//是否指示有破坏性
UNNotificationActionOptionDestructive
//是否允许活动在后台启动app
UNNotificationActionOptionForeground
//无设置
UNNotificationActionOptionNone
*/
UNTextInputNotificationAction * action = [UNTextInputNotificationAction actionWithIdentifier:@"action" title:@"回复" options:UNNotificationActionOptionAuthenticationRequired textInputButtonTitle:@"活动" textInputPlaceholder:@"请输入回复内容"];
//创建通知模板
UNNotificationCategory * category = [UNNotificationCategory categoryWithIdentifier:@"myNotificationCategoryText" actions:@[action] intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction];
UNMutableNotificationContent * content = [UNMutableNotificationContent new];
content.badge = @1;
content.body = @"这是iOS10的新通知内容:普通的iOS通知";
//默认的通知提示音
content.sound = [UNNotificationSound defaultSound];
content.subtitle = @"这里是副标题";
content.title = @"这里是通知的标题";
//设置通知内容对应的模板 需要注意 这里的值要与对应模板id一致
content.categoryIdentifier = @"myNotificationCategoryText";
//设置5S之后执行
UNTimeIntervalNotificationTrigger * trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO];
[[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObjects:category, nil]];
UNNotificationRequest * request = [UNNotificationRequest requestWithIdentifier:@"NotificationDefaultText" content:content trigger:trigger];
[[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
}];
需要注意,要使用模板,通知内容UNNotificationContent的categoryIdentifier要与UNNotificationCategory的id一致。效果如下:

也可以为通知模板添加多个自定义的用户交互按钮,示例如下:










