我不确定我是否出了问题但是从我能找到的例子中得知。我写了那个小小的helloworld。
#import <Foundation/Foundation.h>
#import <Foundation/NSUserNotification.h>
int main (int argc, const char * argv[])
{
NSUserNotification *userNotification = [[NSUserNotification alloc] init];
userNotification.title = @"Some title";
userNotification.informativeText = @"Some text";
[[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:userNotification];
return 0;
}
我用以下代码编译它:
cc -framework Foundation -o app main.m
它编译并且我可以执行它但它不会显示任何内容。由于某些原因,没有任何东西出现。我读到如果应用程序是主要角色,则可能无法显示通知。如何让它显示通知?
答案 0 :(得分:7)
设置委托并覆盖
- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center
shouldPresentNotification:(NSUserNotification *)notification {
return YES;
}
答案 1 :(得分:0)
我知道这是一个老问题 - 但是因为可能有人在寻找答案如何在Python&amp; PyObjC我会在这里发布正确的语法(因为它是google搜索结果中的一个)。由于我无法评论imp的评论,我会将此作为另一个答案发布。
可以用pyobjc以这种方式在Python中做同样的事情:
def userNotificationCenter_shouldPresentNotification_(self, center, notification):
return True
全班看起来像这样:
from Cocoa import NSObject
import objc
class MountainLionNotification(NSObject):
""" MacOS Notifications """
# Based on http://stackoverflow.com/questions/12202983/working-with-mountain-lions-notification-center-using-pyobjc
def userNotificationCenter_shouldPresentNotification_(self, center, notification):
return True
def init(self):
self = super(MountainLionNotification, self).init()
if self is None: return None
# Get objc references to the classes we need.
self.NSUserNotification = objc.lookUpClass('NSUserNotification')
self.NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
return self
def clearNotifications(self):
"""Clear any displayed alerts we have posted. Requires Mavericks."""
NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
NSUserNotificationCenter.defaultUserNotificationCenter().removeAllDeliveredNotifications()
def notify(self, title="", subtitle="", text="", url=""):
"""Create a user notification and display it."""
notification = self.NSUserNotification.alloc().init()
notification.setTitle_(str(title))
notification.setSubtitle_(str(subtitle))
notification.setInformativeText_(str(text))
# notification.setSoundName_("NSUserNotificationDefaultSoundName")
notification.setHasActionButton_(False)
notification.setActionButtonTitle_("View")
# notification.setUserInfo_({"action":"open_url", "value": url})
self.NSUserNotificationCenter.defaultUserNotificationCenter().setDelegate_(self)
self.NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)
# Note that the notification center saves a *copy* of our object.
return notification
答案 2 :(得分:0)
请确保为任何新通知分配新的标识符。除非使用新的标识符或用户清除其通知历史记录,否则通知只会显示一次。