iOS推送之本地通知UILocalNotification

2020-01-17 21:34:14王振洲

摘要: Notification是智能手机应用编程中非常常用的一种传递信息的机制,而且可以非常好的节省资源,不用消耗资源来不停地检查信息状态(Pooling),在iOS下应用分为两种不同的Notification种类,本地和远程。本地的Notification由iOS下NotificationManager统一管理,只需要将封装好的本地Notification对象加入到系统Notification管理机制队列中,系统会在指定的时间激发将本地Notification,应用只需设计好处理Notification的方法就完成了整个Notification流程了。
Notification是智能手机应用编程中非常常用的一种传递信息的机制,而且可以非常好的节省资源,不用消耗资源来不停地检查信息状态(Pooling),在iOS下应用分为两种不同的Notification种类,本地和远程。本地的Notification由iOS下NotificationManager统一管理,只需要将封装好的本地Notification对象加入到系统Notification管理机制队列中,系统会在指定的时间激发将本地Notification,应用只需设计好处理Notification的方法就完成了整个Notification流程了。

本地Notification所使用的对象是UILocalNotification,UILocalNotification的属性涵盖了所有处理Notification需要的内容。UILocalNotification的属性有fireDate、timeZone、repeatInterval、repeatCalendar、alertBody、 alertAction、hasAction、alertLaunchImage、applicationIconBadgeNumber、 soundName和userInfo。

UILocalNotification的调度

其中fireDate、timeZone、repeatInterval和repeatCalendar是用于UILocalNotification的调度。fireDate是UILocalNotification的激发的确切时间。timeZone是UILocalNotification激发时间是否根据时区改变而改变,如果设置为nil的话,那么UILocalNotification将在一段时候后被激发,而不是某一个确切时间被激发。 repeatInterval是UILocalNotification被重复激发之间的时间差,不过时间差是完全根据日历单位(NSCalendarUnit)的,例如每周激发的单位,NSWeekCalendarUnit,如果不设置的话,将不会重复激发。 repeatCalendar是UILocalNotification重复激发所使用的日历单位需要参考的日历,如果不设置的话,系统默认的日历将被作为参考日历。

UILocalNotification的提醒内容

alertBody、alertAction、hasAction和alertLaunchImage是当应用不在运行时,系统处理

1、增加一个本地推送


//设置20秒之后 
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:20];
/*
NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; 
[formatter setDateFormat:@"HH:mm:ss"]; 
NSDate *now = [formatter dateFromString:@"15:00:00"];//触发通知的时间
*/
 //chuagjian
一个本地推送
 UILocalNotification *noti = [[[UILocalNotification alloc] init] autorelease];
 if (noti) {
  //设置推送时间
  noti.fireDate = date;//=now
  //设置时区
  noti.timeZone = [NSTimeZone defaultTimeZone];
  //设置重复间隔
  noti.repeatInterval = NSWeekCalendarUnit;
  //推送声音
  noti.soundName = UILocalNotificationDefaultSoundName;
  //内容
  noti.alertBody = @"推送内容";
  //显示在icon上的红色圈中的数子
  noti.applicationIconBadgeNumber = 1;
  //设置userinfo 方便在之后需要撤销的时候使用
  NSDictionary *infoDic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];
  noti.userInfo = infoDic;
  //添加推送到uiapplication  
  UIApplication *app = [UIApplication sharedApplication];
  [app scheduleLocalNotification:noti]; 
 }