最近写一个mac应用,想实现一个功能,就像chrome的那种通知消息。找了好久,不知道是关键字,搜的不对,还根本没有。CAO,在我快要绝望的时候,突然冒出来,谢天谢地。
- 设置NSUserNotificationCenterDelegate
1
2
| @interface AppDelegate () <NSUserNotificationCenterDelegate>
@end
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| #pragma mark 用户通知中心
- (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 YES;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| -(void)userCenter:(NSString *)content
{
//删除已经显示过的通知(已经存在用户的通知列表中的)
[[NSUserNotificationCenter defaultUserNotificationCenter] removeAllDeliveredNotifications];
//删除已经在执行的通知(比如那些循环递交的通知)
for (NSUserNotification *notify in [[NSUserNotificationCenter defaultUserNotificationCenter] scheduledNotifications])
{
[[NSUserNotificationCenter defaultUserNotificationCenter] removeScheduledNotification:notify];
}
NSUserNotification *notification = [[NSUserNotification alloc] init];
notification.title = @"通知中心";
//notification.subtitle = @"小标题";
notification.informativeText = content;
//设置通知的代理
[[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];
[[NSUserNotificationCenter defaultUserNotificationCenter] scheduleNotification:notification];
}
|
1
| [self userCenter:@"test ok"];
|