iOS10通知框架UserNotification理解与应用

2020-01-18 16:20:19于海丽

需要注意,自定义的通知界面上虽然可以放按钮,可以放任何UI控件,但是其不能进行用户交互,唯一可以进行用户交互的方式是通过协议中的媒体按钮及其回调方法。

        定义好了通知UI模板,若要进行使用,还需要再Notification Content扩展中的info.plist文件的NSExtension字典的NSExtensionAttributes字典里进行一些配置,正常情况下,开发者需要进行配置的键有3个,分别如下:

UNNotificationExtensionCategory:设置模板的categoryId,用于与UNNotificationContent对应。

UNNotificationExtensionInitialContentSizeRatio:设置自定义通知界面的高度与宽度的比,宽度为固定宽度,在不同设备上有差别,开发者需要根据宽度计算出高度进行设置,系统根据这个比值来计算通知界面的高度。

UNNotificationExtensionDefaultContentHidden:是有隐藏系统默认的通知界面。

配置info.plist文件如下:

iOS10通知框架,iOS10通知框架UserNotification,iOS10远程推送,iOS10本地推送

用如下的代码创建通知:


UNNotificationAction * action = [UNNotificationAction actionWithIdentifier:@"action" title:@"活动标题1" options:UNNotificationActionOptionNone];
  //根据id拿到自定义UI的模板
  UNNotificationCategory * category = [UNNotificationCategory categoryWithIdentifier:@"myNotificationCategoryH" actions:@[action] intentIdentifiers:@[] options:UNNotificationCategoryOptionCustomDismissAction];
  UNMutableNotificationContent * content = [UNMutableNotificationContent new];
  content.badge = @1;
  content.body = @"这是iOS10的新通知内容:普通的iOS通知";
  //默认的通知提示音
  content.sound = [UNNotificationSound defaultSound];
  content.subtitle = @"这里是副标题";
  content.title = @"这里是通知的标题";
  content.categoryIdentifier = @"myNotificationCategoryH";
  //设置5S之后执行
  UNTimeIntervalNotificationTrigger * trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO];
  UNNotificationRequest * request = [UNNotificationRequest requestWithIdentifier:@"NotificationDefaultCustomUIH" content:content trigger:trigger];
  [[UNUserNotificationCenter currentNotificationCenter] setNotificationCategories:[NSSet setWithObjects:category, nil]];
  [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
    
  }];

效果如下图:

iOS10通知框架,iOS10通知框架UserNotification,iOS10远程推送,iOS10本地推送