iOS10通知框架UserNotification理解与应用

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


 //创建图片附件
 UNNotificationAttachment * attach = [UNNotificationAttachment attachmentWithIdentifier:@"imageAttach" URL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"2" ofType:@"jpg"]] options:nil error:nil];
 UNMutableNotificationContent * content = [UNMutableNotificationContent new];
 //设置附件数组
 content.attachments = @[attach];
 content.badge = @1;
 content.body = @"这是iOS10的新通知内容:普通的iOS通知";
 //默认的通知提示音
 content.sound = [UNNotificationSound defaultSound];
 content.subtitle = @"这里是副标题";
 content.title = @"这里是通知的标题";
 //设置5S之后执行
 UNTimeIntervalNotificationTrigger * trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO];
 UNNotificationRequest * request = [UNNotificationRequest requestWithIdentifier:@"NotificationDefaultImage" content:content trigger:trigger];
 [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
  
 }];

效果如下图      

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

需要注意,UNNotificationContent的附件数组虽然是一个数组,但是系统的通知模板只能展示其中的第一个附件,设置多个附件也不会有额外的效果,但是如果开发者进行通知模板UI的自定义,则此数组就可以派上用场了。音频附件界面如下:

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

需要注意,添加附件的格式和大小都有一定的要求,如下表格所示:

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

创建通知内容附件UNNotificationAttachment实例的方法中有一个options配置字典,这个字典中可以进行配置的键值对如下:


//配置附件的类型的键 需要设置为NSString类型的值,如果不设置 则默认从扩展名中推断
extern NSString * const UNNotificationAttachmentOptionsTypeHintKey __IOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
//配置是否隐藏缩略图的键 需要配置为NSNumber 0或者1
extern NSString * const UNNotificationAttachmentOptionsThumbnailHiddenKey __IOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
//配置使用一个标准的矩形来对缩略图进行裁剪,需要配置为CGRectCreateDictionaryRepresentation(CGRect)创建的矩形引用
extern NSString * const UNNotificationAttachmentOptionsThumbnailClippingRectKey __IOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);
//使用视频中的某一帧作为缩略图 配置为NSNumber时间
extern NSString * const UNNotificationAttachmentOptionsThumbnailTimeKey __IOS_AVAILABLE(10.0) __WATCHOS_AVAILABLE(3.0);