天天看点

iOS学习笔记45—本地通知UILocalNotification

  1. UILocalNotification *notification = [[UILocalNotification alloc] init];
  2.     NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  3.     [formatter setDateFormat:@"HH:mm:ss"];
  4.     //触发通知的时间
  5.     NSDate *now = [formatter dateFromString:@"15:00:00"];
  6.     notification.fireDate = now;
  7.     //时区
  8.     notification.timeZone = [NSTimeZone defaultTimeZone];
  9.     //通知重复提示的单位,可以是天、周、月
  10.     notification.repeatInterval = NSDayCalendarUnit;
  11.     //通知内容
  12.     notification.alertBody = @"这是一个新的通知";
  13.     //通知被触发时播放的声音
  14.     notification.soundName = UILocalNotificationDefaultSoundName;
  15.     //执行通知注册
  16.     [[UIApplication sharedApplication] scheduleLocalNotification:notification];

以上代码实现了这么一个场景:一些Todo和闹钟类应用都有通知用户的功能,使用的就是iOS中的本地通知UILocalNotification,还有些应用会在每天、每周、每月固定时间提示用户回到应用看看,也是用的本地通知,以上代码片段就是实现了在每天的下午3点弹出通知提示。

如果要在通知中携带参数信息,可以使用下面的方式:

  1. NSDictionary *dic = [NSDictionary dictionaryWithObject:@"name" forKey:@"key"];
  2.     notification.userInfo = dic;

复制代码 如果软件是在运行中,则可以通过AppDelegate中的回调方法获取并处理参数信息:

  1. -(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
  2. {
  3.     if (notification) {
  4.         NSDictionary *userInfo =  notification.userInfo;
  5.         NSString *obj = [userInfo objectForKey:@"key"];
  6.         NSLog(@"%@",obj);
  7.     }
  8. }

复制代码 另外,可以通过两种方式取消注册的本地通知,一种是取消指定的通知,第二种是取消所有的注册通知:

  1. [[UIApplication sharedApplication] cancelLocalNotification:localNotification];
  2.    [[UIApplication sharedApplication] cancelAllLocalNotification];

复制代码

下一篇: ios本地通知