老谭笔记

10.8中的通知中心,NSUserNotification用法

10.8中引入了类似于iOS中的通知功能,那我们如何在自己的软件中集成通知的功能呢?下面我们就通过对通知机制的介绍和编码来展示如何使用通知的功能(NSUserNotification)。

首先,用户可以在系统的偏好设置-通知中设置开启/关闭某一软件的通知功能,也可以具体的设置某软件通知的样式,如图:

那下面我们通过代码来展示如何构建一个通知事件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
NSUserNotification *notification = [[NSUserNotification alloc] init];
notification.title = @"标题";
notification.subtitle = @"小标题";
notification.informativeText = @"详细文字说明";
/*
//设置通知提交的时间
notification.deliveryDate = [NSDate dateWithTimeIntervalSinceNow:5];
//设置通知的循环(必须大于1分钟,估计是防止软件刷屏)
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setSecond:70];
notification.deliveryRepeatInterval = dateComponents;
*/
//只有当用户设置为提示模式时,才会显示按钮
notification.hasActionButton = YES;
notification.actionButtonTitle = @"OK";
notification.otherButtonTitle = @"Cancel";

一个通知的对象就这样创建好了,要让该条通知显示给用户,我们就需要使用通知中心将通知递交给用户,代码如下:

1
2
3
4
//递交通知
[[NSUserNotificationCenter defaultUserNotificationCenter] scheduleNotification:notification];
//设置通知的代理
[[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];

NSUserNotificationCenter还提供了三个代理,让软件可以在通知的不同状态时收到消息:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- (void)userNotificationCenter:(NSUserNotificationCenter *)center didDeliverNotification:(NSUserNotification *)notification
{
NSLog(@"通知已经递交!");
}
- (void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification
{
NSLog(@"用户点击了通知!");
}
- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification
{
//用户中心决定不显示该条通知(如果显示条数超过限制或重复通知等),returen YES;强制显示
return NO;
}

另外,你也可以以下的代码删除通知:

1
2
3
4
5
6
7
8
//删除已经显示过的通知(已经存在用户的通知列表中的)
[[NSUserNotificationCenter defaultUserNotificationCenter] removeAllDeliveredNotifications];
//删除已经在执行的通知(比如那些循环递交的通知)
for (NSUserNotification *notify in [[NSUserNotificationCenter defaultUserNotificationCenter] scheduledNotifications])
{
[[NSUserNotificationCenter defaultUserNotificationCenter] removeScheduledNotification:notify];
}