iOS10添加本地推送(Local Notification)实例

2020-01-17 21:27:33王旭

iOS 10 以前本地推送通知:


+ (void)registerLocalNotificationInOldWay:(NSInteger)alertTime {
  // ios8后,需要添加这个注册,才能得到授权
  // if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
  // UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
  // UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
  // categories:nil];
  // [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
  // // 通知重复提示的单位,可以是天、周、月
  // }
  
  UILocalNotification *notification = [[UILocalNotification alloc] init];
  // 设置触发通知的时间
  NSDate *fireDate = [NSDate dateWithTimeIntervalSinceNow:alertTime];
  NSLog(@"fireDate=%@",fireDate);
  
  notification.fireDate = fireDate;
  // 时区
  notification.timeZone = [NSTimeZone defaultTimeZone];
  // 设置重复的间隔
  notification.repeatInterval = kCFCalendarUnitSecond;
  
  // 通知内容
  notification.alertBody = @"该起床了...";
  notification.applicationIconBadgeNumber = 1;
  // 通知被触发时播放的声音
  notification.soundName = UILocalNotificationDefaultSoundName;
  // 通知参数
  NSDictionary *userDict = [NSDictionary dictionaryWithObject:@"开始学习iOS开发了" forKey:@"key"];
  notification.userInfo = userDict;
  
  // ios8后,需要添加这个注册,才能得到授权
  if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
    UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
    UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
                                         categories:nil];
    [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    // 通知重复提示的单位,可以是天、周、月
    notification.repeatInterval = NSCalendarUnitDay;
  } else {
    // 通知重复提示的单位,可以是天、周、月
    notification.repeatInterval = NSDayCalendarUnit;
  }
  
  // 执行通知注册
  [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持ASPKU。


注:相关教程知识阅读请移步到IOS开发频道。