免费开源的iOS开发学习平台

本地消息推送(基于iOS10 UserNotifications框架):3-UNNotificationTrigger类

UNNotificationTrigger类定义了推送消息触发的方式, 可以支持4种,分别为:远程消息推送、按照时间间隔、按照特定日期以及按照特定地理位置。

UNNotificationTrigger类是一个抽象类,其包含了4个子类,分别为:

  • UNPushNotificationTrigger: 对应远程消息推送,即由苹果服务器推送的提醒(APNs)
  • UNTimeIntervalNotificationTrigger: 基于固定时间间隔触发消息推送
  • UNCalendarNotificationTrigger: 基于特定日期触发消息推送
  • UNLocationNotificationTrigger: 基于特定地理位置触发消息推送

UNPushNotificationTrigger

该类型的触发器是由苹果的推送服务器推送的,推送的消息是由外部操作所决定的,因此,在UNNotificationTrigger类中,只定义了有UNPushNotificationTrigger子类,但是该子类没有定义任何的属性和方法。

UNTimeIntervalNotificationTrigger

UNTimeIntervalNotificationTrigger类型的触发器,可以设置在固定的时间间隔发送消息推送。UNTimeIntervalNotificationTrigger类中提供了如下一些常用的方法和属性。

  • 实例化方法,需要传入提醒的时间间隔,以及是否重复提醒标识
+ (instancetype)triggerWithTimeInterval:(NSTimeInterval)timeInterval repeats:(BOOL)repeats;
  • 设置下次触发时间
- (nullable NSDate *)nextTriggerDate;
  • 获取已经设置的时间间隔
@property (NS_NONATOMIC_IOSONLY, readonly) NSTimeInterval timeInterval;

UNCalendarNotificationTrigger

UNCalendarNotificationTrigger类型的触发器,可以设置在特定日期发送消息推送。例如,我们可以在一些特定的节日给用户发送消息推送。

  • 实例化方法,需要传入提醒的日期(NSDateComponents类),以及是否重复提醒标识
+ (instancetype)triggerWithDateMatchingComponents:(NSDateComponents *)dateComponents repeats:(BOOL)repeats;
  • 设置下次触发时间
- (nullable NSDate *)nextTriggerDate;
  • 获取已经设置的提醒日期
@property (NS_NONATOMIC_IOSONLY, readonly, copy) NSDateComponents *dateComponents;

UNLocationNotificationTrigger

UNLocationNotificationTrigger类型的触发器支持当用户到达特定的地理位置时,触发提醒。例如,当用户到达某个商场时,推送特定的优惠信息。

  • 实例化方法,需要传入一个标识地理位置的参数region(CLRegion类)
+ (instancetype)triggerWithRegion:(CLRegion *)region repeats:(BOOL)repeats;
  • 获得设置提醒的地理位置
@property (NS_NONATOMIC_IOSONLY, readonly, copy) CLRegion *region;