iOS 的本地通知(local notification)用于基于时间行为的通知,在iOS4.0后支持,比如有关日历或者 todo 列表的小应用。另外应用如果在后台执行,iOS 允许它在受限的时间内运 行,它也会发现本地通知有用。比如,一个应用在后台运行,向应用的服务器端获取消息,当消息到达时,比如下载更新版本的提示消息,通过本地通知机制通知 用户。
对本地通知的数量限制,iOS最多允许最近本地通知数量是64个,超过限制的本地通知将被iOS忽略。
注册notification:
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
// 设置notification的属性
localNotification.fireDate = [startTimePicker.picker.date dateByAddingTimeInterval:36000]; //出发时间
localNotification.alertBody = @"Time To Schedule Our Service"; // 消息内容
localNotification.repeatInterval = NSSecondCalendarUnit; // 重复的时间间隔
localNotification.soundName = UILocalNotificationDefaultSoundName; // 触发消息时播放的声音
localNotification.applicationIconBadgeNumber = 1; //应用程序Badge数目
//设置随Notification传递的参数
NSDictionary *infoDict = [NSDictionary dictionaryWithObjectsAndKeys:@"reminder", @"notificationId", @"phone", txtPhone.text, nil];
localNotification.userInfo = infoDict;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; //注册
[localNotification release]; //释放
遍历已经注册的所有LocaleNotification:
NSArray *notifications = [[UIApplication sharedApplication] scheduledLocalNotifications];
for (UILocalNotification *notification in notifications ) {
if( [[notification.userInfo objectForKey:@"source"] isEqualToString:@"dailyReminder"] ) {
[[UIApplication sharedApplication] cancelLocalNotification:notification];
break;
}
}
撤销LocaleNotification:
[[UIApplication sharedApplication] cancelAllLocalNotifications]; // 撤销所有的Notification
<pre name="code" class="cpp">[[UIApplication sharedApplication] cancelLocalNotification:notification]; // 撤销某个Notificiation,若要删除某个特定的Notification,则可以在UserInfo中加入标记,遍历所有的Notification来删除。</pre>
<pre></pre>
<p></p>
<pre></pre>
<strong></strong>
<p></p>
<p></p>
<p><strong>响应事件</strong></p>
<p>当Notification被触发后,你的应用需要对此作出反应。应用此时可能会处于以下几个状态:</p>
<ul>
<li>在前台运行 - 当应用在前台运行时,则ApplicationDelegate的didReceiveLocalNotification会被调用。<pre name="code" class="cpp">- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
NSLog(@"Notification Body: %@", notification.alertBody);
NSLog(@"%@", notification.userInfo);
application.applicationIconBadgeNumber = notification.applicationIconBadgeNumber-1;
}</pre><br>
</li><li>在后台运行 - 用户可以看到类似Push Notification的提醒,若用户选择查看提醒详情,则应用通过 ApplicationDelegate的didFinishLaunchingWithOptions进入<br>
<pre name="code" class="cpp">- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
UILocalNotification *localNotification =
[launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotification) {
NSLog(@"Notification Body: %@",localNotification.alertBody);
NSLog(@"%@", localNotification.userInfo);
application.applicationIconBadgeNumber = localNotification.applicationIconBadgeNumber-1;
}
// set up everything else
return YES;
</pre>}<br>
</li></ul>