iOS10通知框架UserNotification理解与应用

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

UNNotificationAction:用于定义通知模板中的用户交互行为。

UNNotificationRequest:注册通知请求,其中定义了通知的内容和触发方式。

UNNotificationResponse:接收到通知后的回执。

UNNotificationContent:通知的具体内容。

UNNotificationTrigger:通知的触发器,由其子类具体定义。

UNNotificationAttachment:通知附件类,为通知内容添加媒体附件。

UNNotificationSound:定义通知音效。

UNPushNotificationTrigger:远程通知的触发器,UNNotificationTrigger子类。

UNTimeInervalNotificationTrigger:计时通知的触发器,UNNotificationTrigger子类。

UNCalendarNotificationTrigger:周期通知的触发器,UNNotificationTrigger子类。

UNLocationNotificationTrigger:地域通知的触发器,UNNotificationTrigger子类。

UNNotificationCenterDelegate:协议,其中方法用于监听通知状态。

三、进行通知用户权限申请与创建普通的本地通知

        要在iOS系统中使用通知,必须获取到用户权限,UserNotification框架中申请通知用户权限需要通过UNNotificationCenter来完成,示例如下:


//进行用户权限的申请
[[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:UNAuthorizationOptionBadge|UNAuthorizationOptionSound|UNAuthorizationOptionAlert|UNAuthorizationOptionCarPlay completionHandler:^(BOOL granted, NSError * _Nullable error) {
  //在block中会传入布尔值granted,表示用户是否同意
  if (granted) {
   //如果用户权限申请成功,设置通知中心的代理
   [UNUserNotificationCenter currentNotificationCenter].delegate = self;
  }
}];

申请用户权限的方法中需要传入一个权限内容的参数,其枚举定义如下:


typedef NS_OPTIONS(NSUInteger, UNAuthorizationOptions) {
 //允许更新app上的通知数字
 UNAuthorizationOptionBadge = (1 << 0),
 //允许通知声音
 UNAuthorizationOptionSound = (1 << 1),
 //允许通知弹出警告
 UNAuthorizationOptionAlert = (1 << 2),
 //允许车载设备接收通知
 UNAuthorizationOptionCarPlay = (1 << 3),
};

获取到用户权限后,使用UserNotification创建普通的通知,示例代码如下:


 //通知内容类
 UNMutableNotificationContent * content = [UNMutableNotificationContent new];
 //设置通知请求发送时 app图标上显示的数字
 content.badge = @2;
 //设置通知的内容
 content.body = @"这是iOS10的新通知内容:普通的iOS通知";
 //默认的通知提示音
 content.sound = [UNNotificationSound defaultSound];
 //设置通知的副标题
 content.subtitle = @"这里是副标题";
 //设置通知的标题
 content.title = @"这里是通知的标题";
 //设置从通知激活app时的launchImage图片
 content.launchImageName = @"lun";
 //设置5S之后执行
 UNTimeIntervalNotificationTrigger * trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO];
 UNNotificationRequest * request = [UNNotificationRequest requestWithIdentifier:@"NotificationDefault" content:content trigger:trigger];
 //添加通知请求
 [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
  
 }];