有人可以举一个例子,从Cocoa应用程序发送测试通知到通知中心?例如。当我点击一个NSButton
发送通知到山狮通知中心
55
A
回答
148
在山狮的通知由两个类处理。 NSUserNotification
和NSUserNotificationCenter
。 NSUserNotification
是您的实际通知,它有一个标题,一条消息等可以通过属性设置。要传递您创建的通知,您可以使用NSUserNotificationCenter中提供的deliverNotification:
方法。苹果的文档有详细的NSUserNotification & NSUserNotificationCenter信息,但基本的代码来发布通知如下:
- (IBAction)showNotification:(id)sender{
NSUserNotification *notification = [[NSUserNotification alloc] init];
notification.title = @"Hello, World!";
notification.informativeText = @"A notification";
notification.soundName = NSUserNotificationDefaultSoundName;
[[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];
}
这会产生一个通知,一个标题,一个消息,那会打的时候默认的声音它被显示。还有更多的事情可以通过通知来完成(比如计划通知),这些都在我链接的文档中详细说明。
一个小问题,只有当你的应用程序是关键应用程序时才会显示通知。如果您希望显示通知而不管应用程序是否为关键字,则需要指定NSUserNotificationCenter
的代理并覆盖代理方法userNotificationCenter:shouldPresentNotification:
,以便返回YES。可以找到NSUserNotificationCenterDelegate
的文档here
下面是一个向NSUserNotificationCenter提供委托,然后强制显示通知而不管应用程序是否为关键的示例。在应用程序的AppDelegate.m文件,编辑这样说:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];
}
- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification{
return YES;
}
而且在AppDelegate.h,声明类符合NSUserNotificationCenterDelegate协议:
@interface AppDelegate : NSObject <NSApplicationDelegate, NSUserNotificationCenterDelegate>
相关问题
- 1. 向山狮的通知中心发送通知
- 2. 来自Safari的山狮通知中心
- 3. 如何处理山狮通知点击
- 4. Xamarin.Forms Azure通知中心推送通知
- 5. 将推送通知从后端系统发送到Azure推送通知中心
- 6. 无法使用Azure通知中心在Android上发送通知
- 7. 发送通知给使用Azure的通知中心
- 8. 复制滑动到像山狮的通知中心一侧的屏幕?
- 9. iOS推送通知不会添加到通知中心
- 10. Xamarin.Android推送通知GCM到Azure通知中心
- 11. 发送通知
- 12. 发送通知
- 13. 如何发送原始通知到天蓝色的通知中心
- 14. 从Azure通知中心发送推送通知的单个设备的跟踪推送通知状态
- 15. 发送GPS通知,到处
- 16. 使用Azure通知中心发送推送通知(未授权401)
- 17. 通知中心?
- 18. Applescript一个应用程序来更改狮子山通知中心的背景
- 19. MobieFirst V7.1应用中心不发送推送通知到设备
- 20. 通过Firebase发送通知
- 21. 发送Facebook通知
- 22. AlarmManager发送通知
- 23. Xamarin.Mac - 发送通知
- 24. 发送Facebook通知
- 25. 通知中心:当通知postet
- 26. 从通知中心清除通知
- 27. 在通知中心的推送通知点击操作
- 28. Xamarin.iOS推送通知从Azure的通知中心
- 29. 推送通知可以跳过通知中心吗?
- 30. iPhone - 从通知中心移除的推送通知
你能如何覆盖userNotificationCenter阐述? (对不起,我真的很陌生:)) – haseo98 2012-08-05 12:50:04
@ haseo98是的,我刚刚给我的答案加了一个例子。 – alexjohnj 2012-08-05 13:10:49
Im在方法的applicationdidfinishlaunching部分旁边发生错误,将'AppDelegate * const __strong'发送到不兼容类型'id'的参数。有任何想法吗? –
haseo98
2012-08-05 13:25:47